@vtxmacro/cli 2026.9.40 → 2026.9.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/vtx.js CHANGED
@@ -77,7 +77,7 @@ var init_agent_cli_release = __esm({
77
77
  "agent-cli-release.json"() {
78
78
  agent_cli_release_default = {
79
79
  package_name: "@vtxmacro/cli",
80
- package_version: "2026.9.40",
80
+ package_version: "2026.9.42",
81
81
  codex_package_name: "@openai/codex",
82
82
  codex_version: "0.153.3",
83
83
  copilot_sdk_package_name: "@github/copilot-sdk",
@@ -4196,8 +4196,8 @@ var init_az = __esm({
4196
4196
  });
4197
4197
 
4198
4198
  // node_modules/zod/v4/locales/be.js
4199
- function getBelarusianPlural(count3, one, few, many) {
4200
- const absCount = Math.abs(count3);
4199
+ function getBelarusianPlural(count4, one, few, many) {
4200
+ const absCount = Math.abs(count4);
4201
4201
  const lastDigit = absCount % 10;
4202
4202
  const lastTwoDigits = absCount % 100;
4203
4203
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -6156,8 +6156,8 @@ var init_hu = __esm({
6156
6156
  });
6157
6157
 
6158
6158
  // node_modules/zod/v4/locales/hy.js
6159
- function getArmenianPlural(count3, one, many) {
6160
- return Math.abs(count3) === 1 ? one : many;
6159
+ function getArmenianPlural(count4, one, many) {
6160
+ return Math.abs(count4) === 1 ? one : many;
6161
6161
  }
6162
6162
  function withDefiniteArticle(word) {
6163
6163
  if (!word)
@@ -8326,8 +8326,8 @@ var init_pt = __esm({
8326
8326
  });
8327
8327
 
8328
8328
  // node_modules/zod/v4/locales/ru.js
8329
- function getRussianPlural(count3, one, few, many) {
8330
- const absCount = Math.abs(count3);
8329
+ function getRussianPlural(count4, one, few, many) {
8330
+ const absCount = Math.abs(count4);
8331
8331
  const lastDigit = absCount % 10;
8332
8332
  const lastTwoDigits = absCount % 100;
8333
8333
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -17682,17 +17682,17 @@ async function readInferenceHostCredentialContextTransition(config2) {
17682
17682
  if (!value || typeof value !== "object" || Array.isArray(value)) {
17683
17683
  throw new Error("Inference host credential context transition is invalid.");
17684
17684
  }
17685
- const record4 = value;
17685
+ const record5 = value;
17686
17686
  const expectedKeys = ["schema_version", "operation", "phase", "previous", "candidate"];
17687
- if (Object.keys(record4).sort().join("\0") !== expectedKeys.sort().join("\0") || record4.schema_version !== "vtx_inference_credential_context_transition_v1" || record4.operation !== "selection" && record4.operation !== "cleanup" || record4.phase !== "prepared" && record4.phase !== "committed") {
17687
+ if (Object.keys(record5).sort().join("\0") !== expectedKeys.sort().join("\0") || record5.schema_version !== "vtx_inference_credential_context_transition_v1" || record5.operation !== "selection" && record5.operation !== "cleanup" || record5.phase !== "prepared" && record5.phase !== "committed") {
17688
17688
  throw new Error("Inference host credential context transition is invalid.");
17689
17689
  }
17690
17690
  return {
17691
17691
  schema_version: "vtx_inference_credential_context_transition_v1",
17692
- operation: record4.operation,
17693
- phase: record4.phase,
17694
- previous: record4.previous === null ? null : assertInferenceHostCredentialContext(record4.previous, config2),
17695
- candidate: record4.candidate === null ? null : assertInferenceHostCredentialContext(record4.candidate, config2)
17692
+ operation: record5.operation,
17693
+ phase: record5.phase,
17694
+ previous: record5.previous === null ? null : assertInferenceHostCredentialContext(record5.previous, config2),
17695
+ candidate: record5.candidate === null ? null : assertInferenceHostCredentialContext(record5.candidate, config2)
17696
17696
  };
17697
17697
  }
17698
17698
  async function clearInferenceHostCredentialContextTransition(config2) {
@@ -17725,26 +17725,26 @@ function assertInferenceHostCredentialContext(value, config2) {
17725
17725
  if (!value || typeof value !== "object" || Array.isArray(value)) {
17726
17726
  throw new Error("Inference host credential context is invalid.");
17727
17727
  }
17728
- const record4 = value;
17728
+ const record5 = value;
17729
17729
  const expectedKeys = [
17730
17730
  "schema_version",
17731
17731
  "instance_name",
17732
17732
  "credential_store_mode",
17733
17733
  "credential_file_path"
17734
17734
  ];
17735
- if (Object.keys(record4).sort().join("\0") !== expectedKeys.sort().join("\0") || record4.schema_version !== "vtx_inference_credential_context_v1" || record4.instance_name !== config2.instanceName || record4.credential_store_mode !== "os" && record4.credential_store_mode !== "file" || (record4.credential_store_mode === "os" ? record4.credential_file_path !== null : typeof record4.credential_file_path !== "string" || !record4.credential_file_path)) {
17735
+ if (Object.keys(record5).sort().join("\0") !== expectedKeys.sort().join("\0") || record5.schema_version !== "vtx_inference_credential_context_v1" || record5.instance_name !== config2.instanceName || record5.credential_store_mode !== "os" && record5.credential_store_mode !== "file" || (record5.credential_store_mode === "os" ? record5.credential_file_path !== null : typeof record5.credential_file_path !== "string" || !record5.credential_file_path)) {
17736
17736
  throw new Error("Inference host credential context is invalid.");
17737
17737
  }
17738
- const credentialFilePath = record4.credential_store_mode === "file" ? requireNamedInstancePath(
17738
+ const credentialFilePath = record5.credential_store_mode === "file" ? requireNamedInstancePath(
17739
17739
  config2.instanceName,
17740
17740
  config2.instanceName === DEFAULT_INFERENCE_HOST_INSTANCE ? config2.baseDir : join(config2.baseDir, "instances", config2.instanceName),
17741
- record4.credential_file_path,
17741
+ record5.credential_file_path,
17742
17742
  "Stored inference credential path"
17743
17743
  ) : null;
17744
17744
  return {
17745
17745
  schema_version: "vtx_inference_credential_context_v1",
17746
17746
  instance_name: config2.instanceName,
17747
- credential_store_mode: record4.credential_store_mode,
17747
+ credential_store_mode: record5.credential_store_mode,
17748
17748
  credential_file_path: credentialFilePath
17749
17749
  };
17750
17750
  }
@@ -17752,7 +17752,7 @@ function assertLocalState(value) {
17752
17752
  if (!value || typeof value !== "object" || Array.isArray(value)) {
17753
17753
  throw new Error("Inference host local state is invalid.");
17754
17754
  }
17755
- const record4 = value;
17755
+ const record5 = value;
17756
17756
  const exactKeys = [
17757
17757
  "schema_version",
17758
17758
  "issuer",
@@ -17761,10 +17761,10 @@ function assertLocalState(value) {
17761
17761
  "host_generation",
17762
17762
  "key_generation"
17763
17763
  ];
17764
- if (Object.keys(record4).sort().join("\0") !== exactKeys.slice().sort().join("\0") || record4.schema_version !== 1 || typeof record4.issuer !== "string" || !record4.issuer || typeof record4.client_id !== "string" || !record4.client_id || typeof record4.host_id !== "string" || !record4.host_id || !Number.isSafeInteger(record4.host_generation) || Number(record4.host_generation) < 1 || !Number.isSafeInteger(record4.key_generation) || Number(record4.key_generation) < 1) {
17764
+ if (Object.keys(record5).sort().join("\0") !== exactKeys.slice().sort().join("\0") || record5.schema_version !== 1 || typeof record5.issuer !== "string" || !record5.issuer || typeof record5.client_id !== "string" || !record5.client_id || typeof record5.host_id !== "string" || !record5.host_id || !Number.isSafeInteger(record5.host_generation) || Number(record5.host_generation) < 1 || !Number.isSafeInteger(record5.key_generation) || Number(record5.key_generation) < 1) {
17765
17765
  throw new Error("Inference host local state is invalid.");
17766
17766
  }
17767
- return record4;
17767
+ return record5;
17768
17768
  }
17769
17769
  async function ensureInferencePrivateDirectory(path, dependencies = {}) {
17770
17770
  const platform = dependencies.platform ?? process.platform;
@@ -18796,7 +18796,7 @@ function validateInferenceHostCredential(value) {
18796
18796
  if (!value || typeof value !== "object" || Array.isArray(value)) {
18797
18797
  throw new Error("Inference host credential is invalid.");
18798
18798
  }
18799
- const record4 = value;
18799
+ const record5 = value;
18800
18800
  const exactKeys = [
18801
18801
  "schema_version",
18802
18802
  "issuer",
@@ -18809,21 +18809,21 @@ function validateInferenceHostCredential(value) {
18809
18809
  "created_at",
18810
18810
  "updated_at"
18811
18811
  ];
18812
- if (Object.keys(record4).sort().join("\0") !== exactKeys.sort().join("\0")) {
18812
+ if (Object.keys(record5).sort().join("\0") !== exactKeys.sort().join("\0")) {
18813
18813
  throw new Error("Inference host credential fields are invalid.");
18814
18814
  }
18815
- if (record4.schema_version !== 1) {
18815
+ if (record5.schema_version !== 1) {
18816
18816
  throw new Error("Inference host credential version is invalid.");
18817
18817
  }
18818
- const issuer = canonicalUrl(String(record4.issuer || ""), "Inference OAuth issuer");
18818
+ const issuer = canonicalUrl(String(record5.issuer || ""), "Inference OAuth issuer");
18819
18819
  const resource = canonicalUrl(
18820
- String(record4.resource || ""),
18820
+ String(record5.resource || ""),
18821
18821
  "Inference OAuth resource"
18822
18822
  );
18823
- const clientId = String(record4.client_id || "");
18824
- const hostId = String(record4.host_id || "");
18825
- const refreshToken = String(record4.refresh_token || "");
18826
- const privateKey = String(record4.x25519_private_key || "");
18823
+ const clientId = String(record5.client_id || "");
18824
+ const hostId = String(record5.host_id || "");
18825
+ const refreshToken = String(record5.refresh_token || "");
18826
+ const privateKey = String(record5.x25519_private_key || "");
18827
18827
  if (!clientId || clientId.length > 512) {
18828
18828
  throw new Error("Inference OAuth client ID is invalid.");
18829
18829
  }
@@ -18836,11 +18836,11 @@ function validateInferenceHostCredential(value) {
18836
18836
  if (!BASE64URL_32_BYTES.test(privateKey)) {
18837
18837
  throw new Error("Inference host private key is invalid.");
18838
18838
  }
18839
- if (!Number.isSafeInteger(record4.key_generation) || Number(record4.key_generation) < 1) {
18839
+ if (!Number.isSafeInteger(record5.key_generation) || Number(record5.key_generation) < 1) {
18840
18840
  throw new Error("Inference host key generation is invalid.");
18841
18841
  }
18842
- const createdAt = isoTimestamp(record4.created_at, "Credential creation timestamp");
18843
- const updatedAt = isoTimestamp(record4.updated_at, "Credential update timestamp");
18842
+ const createdAt = isoTimestamp(record5.created_at, "Credential creation timestamp");
18843
+ const updatedAt = isoTimestamp(record5.updated_at, "Credential update timestamp");
18844
18844
  return {
18845
18845
  schema_version: 1,
18846
18846
  issuer,
@@ -18849,7 +18849,7 @@ function validateInferenceHostCredential(value) {
18849
18849
  host_id: hostId,
18850
18850
  refresh_token: refreshToken,
18851
18851
  x25519_private_key: privateKey,
18852
- key_generation: Number(record4.key_generation),
18852
+ key_generation: Number(record5.key_generation),
18853
18853
  created_at: createdAt,
18854
18854
  updated_at: updatedAt
18855
18855
  };
@@ -19109,17 +19109,17 @@ var init_credential_store = __esm({
19109
19109
  if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) {
19110
19110
  throw new Error("Inference credential fallback file is invalid.");
19111
19111
  }
19112
- const record4 = envelope;
19113
- if (record4.schema_version !== 1 || record4.namespace !== INFERENCE_CREDENTIAL_NAMESPACE || typeof record4.account_key !== "string") {
19112
+ const record5 = envelope;
19113
+ if (record5.schema_version !== 1 || record5.namespace !== INFERENCE_CREDENTIAL_NAMESPACE || typeof record5.account_key !== "string") {
19114
19114
  throw new Error("Inference credential fallback identity is invalid.");
19115
19115
  }
19116
- const credential = validateInferenceHostCredential(record4.credential);
19116
+ const credential = validateInferenceHostCredential(record5.credential);
19117
19117
  const exactAccountKey = inferenceCredentialAccountKey({
19118
19118
  issuer: credential.issuer,
19119
19119
  clientId: credential.client_id,
19120
19120
  hostId: credential.host_id
19121
19121
  });
19122
- if (record4.account_key !== exactAccountKey || accountKey2 && record4.account_key !== accountKey2) {
19122
+ if (record5.account_key !== exactAccountKey || accountKey2 && record5.account_key !== accountKey2) {
19123
19123
  throw new Error("Inference credential fallback identity is invalid.");
19124
19124
  }
19125
19125
  return credential;
@@ -19169,22 +19169,22 @@ var init_credential_store = __esm({
19169
19169
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
19170
19170
  throw new Error("Inference credential recovery file is invalid.");
19171
19171
  }
19172
- const record4 = parsed;
19173
- if (Object.keys(record4).sort().join("\0") !== [
19172
+ const record5 = parsed;
19173
+ if (Object.keys(record5).sort().join("\0") !== [
19174
19174
  "account_key",
19175
19175
  "credential",
19176
19176
  "namespace",
19177
19177
  "schema_version"
19178
- ].join("\0") || record4.schema_version !== 1 || record4.namespace !== INFERENCE_CREDENTIAL_NAMESPACE || typeof record4.account_key !== "string") {
19178
+ ].join("\0") || record5.schema_version !== 1 || record5.namespace !== INFERENCE_CREDENTIAL_NAMESPACE || typeof record5.account_key !== "string") {
19179
19179
  throw new Error("Inference credential recovery identity is invalid.");
19180
19180
  }
19181
- const credential = validateInferenceHostCredential(record4.credential);
19181
+ const credential = validateInferenceHostCredential(record5.credential);
19182
19182
  const accountKey2 = inferenceCredentialAccountKey({
19183
19183
  issuer: credential.issuer,
19184
19184
  clientId: credential.client_id,
19185
19185
  hostId: credential.host_id
19186
19186
  });
19187
- if (record4.account_key !== accountKey2) {
19187
+ if (record5.account_key !== accountKey2) {
19188
19188
  throw new Error("Inference credential recovery identity is invalid.");
19189
19189
  }
19190
19190
  return { accountKey: accountKey2, credential };
@@ -22981,26 +22981,26 @@ var require_resolve = __commonJS({
22981
22981
  return true;
22982
22982
  }
22983
22983
  function countKeys(schema) {
22984
- var count3 = 0, item;
22984
+ var count4 = 0, item;
22985
22985
  if (Array.isArray(schema)) {
22986
22986
  for (var i = 0; i < schema.length; i++) {
22987
22987
  item = schema[i];
22988
- if (typeof item == "object") count3 += countKeys(item);
22989
- if (count3 == Infinity) return Infinity;
22988
+ if (typeof item == "object") count4 += countKeys(item);
22989
+ if (count4 == Infinity) return Infinity;
22990
22990
  }
22991
22991
  } else {
22992
22992
  for (var key in schema) {
22993
22993
  if (key == "$ref") return Infinity;
22994
22994
  if (SIMPLE_INLINED[key]) {
22995
- count3++;
22995
+ count4++;
22996
22996
  } else {
22997
22997
  item = schema[key];
22998
- if (typeof item == "object") count3 += countKeys(item) + 1;
22999
- if (count3 == Infinity) return Infinity;
22998
+ if (typeof item == "object") count4 += countKeys(item) + 1;
22999
+ if (count4 == Infinity) return Infinity;
23000
23000
  }
23001
23001
  }
23002
23002
  }
23003
- return count3;
23003
+ return count4;
23004
23004
  }
23005
23005
  function getFullPath(id2, normalize) {
23006
23006
  if (normalize !== false) id2 = normalizeId(id2);
@@ -30413,7 +30413,7 @@ var init_agent_state = __esm({
30413
30413
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(message);
30414
30414
  return value;
30415
30415
  };
30416
- hasExactKeys = (record4, keys) => Object.keys(record4).sort().join("\0") === [...keys].sort().join("\0");
30416
+ hasExactKeys = (record5, keys) => Object.keys(record5).sort().join("\0") === [...keys].sort().join("\0");
30417
30417
  assertInferenceAgentFailureFence = (value) => {
30418
30418
  const message = "Inference Agent failure fence is invalid.";
30419
30419
  const fence = assertPlainObject(value, message);
@@ -30596,17 +30596,17 @@ var init_agent_state = __esm({
30596
30596
  if (!value || typeof value !== "object" || Array.isArray(value)) {
30597
30597
  throw new Error("Agent-driven inference next recovery state is invalid.");
30598
30598
  }
30599
- const record4 = value;
30600
- if (Object.keys(record4).sort().join("\0") !== ["schema_version", "operation_id", "requested_at"].sort().join("\0") || record4.schema_version !== "vtx_inference_agent_next_v1" || typeof record4.operation_id !== "string" || !record4.operation_id || typeof record4.requested_at !== "string" || !Number.isFinite(Date.parse(record4.requested_at))) {
30599
+ const record5 = value;
30600
+ if (Object.keys(record5).sort().join("\0") !== ["schema_version", "operation_id", "requested_at"].sort().join("\0") || record5.schema_version !== "vtx_inference_agent_next_v1" || typeof record5.operation_id !== "string" || !record5.operation_id || typeof record5.requested_at !== "string" || !Number.isFinite(Date.parse(record5.requested_at))) {
30601
30601
  throw new Error("Agent-driven inference next recovery state is invalid.");
30602
30602
  }
30603
- return record4;
30603
+ return record5;
30604
30604
  };
30605
30605
  assertAttemptState = (value) => {
30606
30606
  if (!value || typeof value !== "object" || Array.isArray(value)) {
30607
30607
  throw new Error("Agent-driven inference attempt state is invalid.");
30608
30608
  }
30609
- const record4 = value;
30609
+ const record5 = value;
30610
30610
  const exactKeys = [
30611
30611
  "schema_version",
30612
30612
  "host_id",
@@ -30623,22 +30623,22 @@ var init_agent_state = __esm({
30623
30623
  "pending_terminal"
30624
30624
  ];
30625
30625
  const freshnessKeys = ["provider_dispatch_not_after", "provider_dispatch_local_not_after"];
30626
- if ("execution_mode" in record4) {
30627
- if (!["server", "client"].includes(String(record4.execution_mode))) {
30626
+ if ("execution_mode" in record5) {
30627
+ if (!["server", "client"].includes(String(record5.execution_mode))) {
30628
30628
  throw new Error("Agent-driven inference execution mode is invalid.");
30629
30629
  }
30630
30630
  exactKeys.push("execution_mode");
30631
30631
  }
30632
- if (freshnessKeys.some((key) => key in record4)) {
30633
- if (freshnessKeys.some((key) => typeof record4[key] !== "string" || !Number.isFinite(Date.parse(record4[key])))) {
30632
+ if (freshnessKeys.some((key) => key in record5)) {
30633
+ if (freshnessKeys.some((key) => typeof record5[key] !== "string" || !Number.isFinite(Date.parse(record5[key])))) {
30634
30634
  throw new Error("Agent-driven inference freshness recovery state is invalid.");
30635
30635
  }
30636
30636
  exactKeys.push(...freshnessKeys);
30637
30637
  }
30638
- if (Object.keys(record4).sort().join("\0") !== exactKeys.slice().sort().join("\0") || record4.schema_version !== "vtx_inference_agent_attempt_v1" || typeof record4.host_id !== "string" || !record4.host_id || typeof record4.job_id !== "string" || !record4.job_id || typeof record4.attempt_id !== "string" || !record4.attempt_id || typeof record4.claim_handle !== "string" || !record4.claim_handle || typeof record4.completion_operation_id !== "string" || !record4.completion_operation_id || typeof record4.failure_operation_id !== "string" || !record4.failure_operation_id || typeof record4.requested_model !== "string" || !record4.requested_model || typeof record4.requested_reasoning_effort !== "string" || !record4.requested_reasoning_effort || !["provider_response", "decision_candidate"].includes(String(record4.response_mode)) || typeof record4.deadline_at !== "string" || !Number.isFinite(Date.parse(record4.deadline_at)) || typeof record4.received_at !== "string" || !Number.isFinite(Date.parse(record4.received_at))) {
30638
+ if (Object.keys(record5).sort().join("\0") !== exactKeys.slice().sort().join("\0") || record5.schema_version !== "vtx_inference_agent_attempt_v1" || typeof record5.host_id !== "string" || !record5.host_id || typeof record5.job_id !== "string" || !record5.job_id || typeof record5.attempt_id !== "string" || !record5.attempt_id || typeof record5.claim_handle !== "string" || !record5.claim_handle || typeof record5.completion_operation_id !== "string" || !record5.completion_operation_id || typeof record5.failure_operation_id !== "string" || !record5.failure_operation_id || typeof record5.requested_model !== "string" || !record5.requested_model || typeof record5.requested_reasoning_effort !== "string" || !record5.requested_reasoning_effort || !["provider_response", "decision_candidate"].includes(String(record5.response_mode)) || typeof record5.deadline_at !== "string" || !Number.isFinite(Date.parse(record5.deadline_at)) || typeof record5.received_at !== "string" || !Number.isFinite(Date.parse(record5.received_at))) {
30639
30639
  throw new Error("Agent-driven inference attempt state is invalid.");
30640
30640
  }
30641
- const pending2 = record4.pending_terminal;
30641
+ const pending2 = record5.pending_terminal;
30642
30642
  if (pending2 !== null) {
30643
30643
  if (!pending2 || typeof pending2 !== "object" || Array.isArray(pending2)) {
30644
30644
  throw new Error("Agent-driven inference terminal recovery state is invalid.");
@@ -30655,7 +30655,7 @@ var init_agent_state = __esm({
30655
30655
  throw new Error("Agent-driven inference terminal recovery state is invalid.");
30656
30656
  }
30657
30657
  }
30658
- return record4;
30658
+ return record5;
30659
30659
  };
30660
30660
  }
30661
30661
  });
@@ -30902,14 +30902,14 @@ var init_runner = __esm({
30902
30902
  };
30903
30903
  };
30904
30904
  safeInteger = (value, minimum) => typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
30905
- exactObjectKeys = (record4, keys) => Object.keys(record4).sort().join("\0") === [...keys].sort().join("\0");
30905
+ exactObjectKeys = (record5, keys) => Object.keys(record5).sort().join("\0") === [...keys].sort().join("\0");
30906
30906
  validIso = (value) => typeof value === "string" && value.length > 0 && Number.isFinite(Date.parse(value));
30907
30907
  validateAttemptReceipt = (value) => {
30908
30908
  if (!value || typeof value !== "object" || Array.isArray(value)) {
30909
30909
  throw new Error("Inference host attempt receipt is invalid.");
30910
30910
  }
30911
- const record4 = value;
30912
- if (!exactObjectKeys(record4, [
30911
+ const record5 = value;
30912
+ if (!exactObjectKeys(record5, [
30913
30913
  "schema_version",
30914
30914
  "attempt_id",
30915
30915
  "job_id",
@@ -30925,30 +30925,30 @@ var init_runner = __esm({
30925
30925
  "start_request",
30926
30926
  "terminal_request",
30927
30927
  "updated_at"
30928
- ]) || record4.schema_version !== ATTEMPT_RECEIPT_SCHEMA_VERSION || typeof record4.attempt_id !== "string" || !record4.attempt_id || typeof record4.job_id !== "string" || !record4.job_id || !safeInteger(record4.profile_id, 1) || typeof record4.input_sha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record4.input_sha256) || !safeInteger(record4.claim_generation, 1) || !safeInteger(record4.attempt_index, 0) || !["claimed", "started", "dispatched", "terminal_pending"].includes(String(record4.phase)) || !["not_dispatched", "confirmed_dispatched", "outcome_unknown"].includes(String(record4.dispatch_outcome)) || record4.terminal_operation_id !== null && typeof record4.terminal_operation_id !== "string" || !safeInteger(record4.job_heartbeat_sequence, 0) || !validIso(record4.updated_at)) {
30928
+ ]) || record5.schema_version !== ATTEMPT_RECEIPT_SCHEMA_VERSION || typeof record5.attempt_id !== "string" || !record5.attempt_id || typeof record5.job_id !== "string" || !record5.job_id || !safeInteger(record5.profile_id, 1) || typeof record5.input_sha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record5.input_sha256) || !safeInteger(record5.claim_generation, 1) || !safeInteger(record5.attempt_index, 0) || !["claimed", "started", "dispatched", "terminal_pending"].includes(String(record5.phase)) || !["not_dispatched", "confirmed_dispatched", "outcome_unknown"].includes(String(record5.dispatch_outcome)) || record5.terminal_operation_id !== null && typeof record5.terminal_operation_id !== "string" || !safeInteger(record5.job_heartbeat_sequence, 0) || !validIso(record5.updated_at)) {
30929
30929
  throw new Error("Inference host attempt receipt is invalid.");
30930
30930
  }
30931
- const claim = record4.claim;
30932
- if (!claim || typeof claim !== "object" || Array.isArray(claim) || claim.claim_state !== "claimed" || claim.job_id !== record4.job_id || claim.claim_generation !== record4.claim_generation || claim.attempt_index !== record4.attempt_index || claim.input_sha256 !== record4.input_sha256) {
30931
+ const claim = record5.claim;
30932
+ if (!claim || typeof claim !== "object" || Array.isArray(claim) || claim.claim_state !== "claimed" || claim.job_id !== record5.job_id || claim.claim_generation !== record5.claim_generation || claim.attempt_index !== record5.attempt_index || claim.input_sha256 !== record5.input_sha256) {
30933
30933
  throw new Error("Inference host persisted claim is invalid.");
30934
30934
  }
30935
- const startRequest = attemptStartRequestSchema.parse(record4.start_request);
30936
- if (startRequest.attempt_id !== record4.attempt_id || startRequest.job_id !== record4.job_id || startRequest.claim_generation !== record4.claim_generation || startRequest.attempt_index !== record4.attempt_index || startRequest.input_sha256 !== record4.input_sha256) {
30935
+ const startRequest = attemptStartRequestSchema.parse(record5.start_request);
30936
+ if (startRequest.attempt_id !== record5.attempt_id || startRequest.job_id !== record5.job_id || startRequest.claim_generation !== record5.claim_generation || startRequest.attempt_index !== record5.attempt_index || startRequest.input_sha256 !== record5.input_sha256) {
30937
30937
  throw new Error("Inference host persisted start request is invalid.");
30938
30938
  }
30939
30939
  let terminalRequest = null;
30940
- if (record4.terminal_request !== null) {
30941
- const schemaVersion = record4.terminal_request.schema_version;
30942
- terminalRequest = schemaVersion === "external_inference_job_complete_v1" ? jobCompleteRequestSchema.parse(record4.terminal_request) : jobFailRequestSchema.parse(record4.terminal_request);
30943
- if (terminalRequest.attempt_id !== record4.attempt_id || terminalRequest.job_id !== record4.job_id || terminalRequest.claim_generation !== record4.claim_generation) {
30940
+ if (record5.terminal_request !== null) {
30941
+ const schemaVersion = record5.terminal_request.schema_version;
30942
+ terminalRequest = schemaVersion === "external_inference_job_complete_v1" ? jobCompleteRequestSchema.parse(record5.terminal_request) : jobFailRequestSchema.parse(record5.terminal_request);
30943
+ if (terminalRequest.attempt_id !== record5.attempt_id || terminalRequest.job_id !== record5.job_id || terminalRequest.claim_generation !== record5.claim_generation) {
30944
30944
  throw new Error("Inference host persisted terminal request is invalid.");
30945
30945
  }
30946
30946
  }
30947
- if (record4.phase === "terminal_pending" !== (terminalRequest !== null)) {
30947
+ if (record5.phase === "terminal_pending" !== (terminalRequest !== null)) {
30948
30948
  throw new Error("Inference host terminal receipt phase is invalid.");
30949
30949
  }
30950
30950
  return {
30951
- ...record4,
30951
+ ...record5,
30952
30952
  claim,
30953
30953
  start_request: startRequest,
30954
30954
  terminal_request: terminalRequest
@@ -30958,7 +30958,7 @@ var init_runner = __esm({
30958
30958
  if (!value || typeof value !== "object" || Array.isArray(value)) {
30959
30959
  throw new Error("Inference host runtime receipt is invalid.");
30960
30960
  }
30961
- const record4 = value;
30961
+ const record5 = value;
30962
30962
  const legacyKeys = [
30963
30963
  "schema_version",
30964
30964
  "host_id",
@@ -30974,17 +30974,17 @@ var init_runner = __esm({
30974
30974
  "updated_at"
30975
30975
  ];
30976
30976
  const currentKeys = [...legacyKeys, "pending_claim_request"];
30977
- if (!(exactObjectKeys(record4, legacyKeys) || exactObjectKeys(record4, currentKeys) || exactObjectKeys(record4, [...legacyKeys, "last_advertisement"]) || exactObjectKeys(record4, [...currentKeys, "last_advertisement"])) || record4.schema_version !== RUNTIME_RECEIPT_SCHEMA_VERSION || typeof record4.host_id !== "string" || !record4.host_id || !safeInteger(record4.host_generation, 1) || !safeInteger(record4.key_generation, 1) || !safeInteger(record4.advertisement_generation, 1) || record4.advertisement_expires_at !== null && !validIso(record4.advertisement_expires_at) || typeof record4.registered !== "boolean" || !safeInteger(record4.host_heartbeat_sequence, 0) || !safeInteger(record4.claim_sequence, 0) || !record4.attempts || typeof record4.attempts !== "object" || Array.isArray(record4.attempts) || !validIso(record4.updated_at)) {
30977
+ if (!(exactObjectKeys(record5, legacyKeys) || exactObjectKeys(record5, currentKeys) || exactObjectKeys(record5, [...legacyKeys, "last_advertisement"]) || exactObjectKeys(record5, [...currentKeys, "last_advertisement"])) || record5.schema_version !== RUNTIME_RECEIPT_SCHEMA_VERSION || typeof record5.host_id !== "string" || !record5.host_id || !safeInteger(record5.host_generation, 1) || !safeInteger(record5.key_generation, 1) || !safeInteger(record5.advertisement_generation, 1) || record5.advertisement_expires_at !== null && !validIso(record5.advertisement_expires_at) || typeof record5.registered !== "boolean" || !safeInteger(record5.host_heartbeat_sequence, 0) || !safeInteger(record5.claim_sequence, 0) || !record5.attempts || typeof record5.attempts !== "object" || Array.isArray(record5.attempts) || !validIso(record5.updated_at)) {
30978
30978
  throw new Error("Inference host runtime receipt is invalid.");
30979
30979
  }
30980
- const lastAdvertisement = record4.last_advertisement == null ? null : hostAdvertisementSchema.parse(record4.last_advertisement);
30981
- const pendingAdvertisement = record4.pending_advertisement === null ? null : hostAdvertisementSchema.parse(record4.pending_advertisement);
30982
- const pendingClaimRequest = record4.pending_claim_request == null ? null : jobClaimRequestSchema.parse(record4.pending_claim_request);
30983
- if (pendingClaimRequest && (pendingClaimRequest.host_id !== record4.host_id || pendingClaimRequest.host_generation !== record4.host_generation || pendingClaimRequest.key_generation !== record4.key_generation || pendingClaimRequest.advertisement_generation > Number(record4.advertisement_generation))) {
30980
+ const lastAdvertisement = record5.last_advertisement == null ? null : hostAdvertisementSchema.parse(record5.last_advertisement);
30981
+ const pendingAdvertisement = record5.pending_advertisement === null ? null : hostAdvertisementSchema.parse(record5.pending_advertisement);
30982
+ const pendingClaimRequest = record5.pending_claim_request == null ? null : jobClaimRequestSchema.parse(record5.pending_claim_request);
30983
+ if (pendingClaimRequest && (pendingClaimRequest.host_id !== record5.host_id || pendingClaimRequest.host_generation !== record5.host_generation || pendingClaimRequest.key_generation !== record5.key_generation || pendingClaimRequest.advertisement_generation > Number(record5.advertisement_generation))) {
30984
30984
  throw new Error("Inference host pending claim receipt is invalid.");
30985
30985
  }
30986
30986
  const attempts = Object.fromEntries(
30987
- Object.entries(record4.attempts).map(([key, attempt]) => {
30987
+ Object.entries(record5.attempts).map(([key, attempt]) => {
30988
30988
  const validated = validateAttemptReceipt(attempt);
30989
30989
  if (key !== validated.attempt_id) {
30990
30990
  throw new Error("Inference host attempt receipt key is invalid.");
@@ -30993,9 +30993,9 @@ var init_runner = __esm({
30993
30993
  })
30994
30994
  );
30995
30995
  return {
30996
- ...record4,
30996
+ ...record5,
30997
30997
  pending_advertisement: pendingAdvertisement,
30998
- ..."last_advertisement" in record4 ? { last_advertisement: lastAdvertisement } : {},
30998
+ ..."last_advertisement" in record5 ? { last_advertisement: lastAdvertisement } : {},
30999
30999
  pending_claim_request: pendingClaimRequest,
31000
31000
  attempts
31001
31001
  };
@@ -34523,9 +34523,18 @@ var init_runner = __esm({
34523
34523
  };
34524
34524
  }
34525
34525
  });
34526
+ const wakeScheduledAtMs = this.now();
34527
+ let nextWakeAtMs = null;
34528
+ let wakeError;
34529
+ try {
34530
+ nextWakeAtMs = wakeScheduledAtMs + parseInferenceAgentWake(result2.turn.text, assignment) * 1e3;
34531
+ } catch (error48) {
34532
+ wakeError = error48;
34533
+ }
34534
+ const scheduledWakeAt = nextWakeAtMs === null ? null : new Date(nextWakeAtMs).toISOString();
34526
34535
  state = { ...state, pending_turn: {
34527
34536
  ...state.pending_turn,
34528
- next_wake_at: null,
34537
+ next_wake_at: scheduledWakeAt,
34529
34538
  terminal_receipt: {
34530
34539
  terminal_status: "completed",
34531
34540
  failure_code: null,
@@ -34544,12 +34553,7 @@ var init_runner = __esm({
34544
34553
  }
34545
34554
  }, updated_at: nowIso() };
34546
34555
  await writeInferenceAgentRuntimeState(this.options.statePath, state);
34547
- const wakeSeconds = parseInferenceAgentWake(result2.turn.text, assignment);
34548
- const wakeScheduledAtMs = this.now();
34549
- const nextWakeAtMs = wakeScheduledAtMs + wakeSeconds * 1e3;
34550
- const scheduledWakeAt = new Date(nextWakeAtMs).toISOString();
34551
- state = { ...state, pending_turn: { ...state.pending_turn, next_wake_at: scheduledWakeAt } };
34552
- await writeInferenceAgentRuntimeState(this.options.statePath, state);
34556
+ if (nextWakeAtMs === null || scheduledWakeAt === null) throw wakeError;
34553
34557
  const wakeHeartbeat = await this.options.controlClient.heartbeat({
34554
34558
  operation_id: randomUUID(),
34555
34559
  host_id: this.options.hostId,
@@ -35781,9 +35785,9 @@ var init_codex_adapter = __esm({
35781
35785
  continue;
35782
35786
  }
35783
35787
  if (!event || typeof event !== "object" || Array.isArray(event)) continue;
35784
- const record4 = event;
35785
- const payload = record4.payload;
35786
- if (record4.type === "session_meta" && payload && typeof payload === "object" && !Array.isArray(payload) && resolve3(String(payload.cwd || "")) === resolve3(checkpoint.workspacePath)) {
35788
+ const record5 = event;
35789
+ const payload = record5.payload;
35790
+ if (record5.type === "session_meta" && payload && typeof payload === "object" && !Array.isArray(payload) && resolve3(String(payload.cwd || "")) === resolve3(checkpoint.workspacePath)) {
35787
35791
  threadPaths.add(path);
35788
35792
  break;
35789
35793
  }
@@ -36950,16 +36954,16 @@ $items = @(Get-CimInstance Win32_Process | Where-Object { $_.Name -in @('node.ex
36950
36954
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
36951
36955
  throw new Error("Windows process ownership inventory was invalid.");
36952
36956
  }
36953
- const record4 = entry;
36954
- if (!Number.isSafeInteger(record4.process_id) || Number(record4.process_id) < 1 || typeof record4.name !== "string" || record4.executable_path !== null && typeof record4.executable_path !== "string" || record4.command_line !== null && typeof record4.command_line !== "string" || record4.creation_date !== null && typeof record4.creation_date !== "string") {
36957
+ const record5 = entry;
36958
+ if (!Number.isSafeInteger(record5.process_id) || Number(record5.process_id) < 1 || typeof record5.name !== "string" || record5.executable_path !== null && typeof record5.executable_path !== "string" || record5.command_line !== null && typeof record5.command_line !== "string" || record5.creation_date !== null && typeof record5.creation_date !== "string") {
36955
36959
  throw new Error("Windows process ownership inventory was invalid.");
36956
36960
  }
36957
36961
  return {
36958
- process_id: Number(record4.process_id),
36959
- name: record4.name,
36960
- executable_path: record4.executable_path,
36961
- command_line: record4.command_line,
36962
- creation_date: record4.creation_date
36962
+ process_id: Number(record5.process_id),
36963
+ name: record5.name,
36964
+ executable_path: record5.executable_path,
36965
+ command_line: record5.command_line,
36966
+ creation_date: record5.creation_date
36963
36967
  };
36964
36968
  });
36965
36969
  };
@@ -41453,14 +41457,14 @@ var init_exo_credential_store = __esm({
41453
41457
  if (!value || typeof value !== "object" || Array.isArray(value)) {
41454
41458
  throw new Error("Stored Exo credential is invalid.");
41455
41459
  }
41456
- const record4 = value;
41457
- if (typeof record4.provider !== "string" || typeof record4.api_key !== "string") {
41460
+ const record5 = value;
41461
+ if (typeof record5.provider !== "string" || typeof record5.api_key !== "string") {
41458
41462
  throw new Error("Stored Exo credential is invalid.");
41459
41463
  }
41460
- const provider = validateProvider(record4.provider);
41461
- const apiKey = validateApiKey(record4.api_key);
41464
+ const provider = validateProvider(record5.provider);
41465
+ const apiKey = validateApiKey(record5.api_key);
41462
41466
  const identity2 = credentialIdentity(provider, apiKey);
41463
- if (record4.schema_version !== 1 || record4.adapter !== "exo" || record4.identity !== identity2 || Object.keys(record4).sort().join(",") !== "adapter,api_key,identity,provider,schema_version") {
41467
+ if (record5.schema_version !== 1 || record5.adapter !== "exo" || record5.identity !== identity2 || Object.keys(record5).sort().join(",") !== "adapter,api_key,identity,provider,schema_version") {
41464
41468
  throw new Error("Stored Exo credential failed validation.");
41465
41469
  }
41466
41470
  return { provider, apiKey, identity: identity2 };
@@ -41654,11 +41658,11 @@ var init_pi_credential_store = __esm({
41654
41658
  if (!value || typeof value !== "object" || Array.isArray(value)) {
41655
41659
  throw new Error("Stored Pi credential is invalid.");
41656
41660
  }
41657
- const record4 = value;
41658
- const provider = validateProvider2(String(record4.provider ?? ""));
41659
- const apiKey = validateApiKey2(String(record4.api_key ?? ""));
41661
+ const record5 = value;
41662
+ const provider = validateProvider2(String(record5.provider ?? ""));
41663
+ const apiKey = validateApiKey2(String(record5.api_key ?? ""));
41660
41664
  const identity2 = credentialIdentity2(provider, apiKey);
41661
- if (record4.schema_version !== 1 || record4.adapter !== "pi" || record4.identity !== identity2 || Object.keys(record4).sort().join(",") !== "adapter,api_key,identity,provider,schema_version") {
41665
+ if (record5.schema_version !== 1 || record5.adapter !== "pi" || record5.identity !== identity2 || Object.keys(record5).sort().join(",") !== "adapter,api_key,identity,provider,schema_version") {
41662
41666
  throw new Error("Stored Pi credential failed validation.");
41663
41667
  }
41664
41668
  return { provider, apiKey, identity: identity2 };
@@ -41811,10 +41815,10 @@ var init_deepseek_credential_store = __esm({
41811
41815
  if (!value || typeof value !== "object" || Array.isArray(value)) {
41812
41816
  throw new Error("Stored DeepSeek Harness credential is invalid.");
41813
41817
  }
41814
- const record4 = value;
41815
- const apiKey = validateApiKey3(String(record4.api_key ?? ""));
41818
+ const record5 = value;
41819
+ const apiKey = validateApiKey3(String(record5.api_key ?? ""));
41816
41820
  const identity2 = credentialIdentity3(apiKey);
41817
- if (record4.schema_version !== 1 || record4.adapter !== "deepseek-harness" || record4.identity !== identity2 || Object.keys(record4).sort().join(",") !== "adapter,api_key,identity,schema_version") {
41821
+ if (record5.schema_version !== 1 || record5.adapter !== "deepseek-harness" || record5.identity !== identity2 || Object.keys(record5).sort().join(",") !== "adapter,api_key,identity,schema_version") {
41818
41822
  throw new Error("Stored DeepSeek Harness credential failed validation.");
41819
41823
  }
41820
41824
  return { apiKey, identity: identity2 };
@@ -41967,6 +41971,9 @@ var init_runtime_policy_generated = __esm({
41967
41971
  "lib/runtime-policy.generated.json with { type: 'json' }"() {
41968
41972
  runtime_policy_generated_default = {
41969
41973
  ui: {
41974
+ performance_defaults: {
41975
+ default_timeframe: "30d"
41976
+ },
41970
41977
  auth_bootstrap_retry: {
41971
41978
  max_attempts: 3,
41972
41979
  jitter_milliseconds: 750,
@@ -42192,28 +42199,28 @@ var init_service = __esm({
42192
42199
  if (!value || typeof value !== "object" || Array.isArray(value)) {
42193
42200
  throw new Error("Inference-host service worker is invalid.");
42194
42201
  }
42195
- const record4 = value;
42196
- if (typeof record4.instance_name !== "string" || !/^[a-z0-9](?:[a-z0-9-]{0,46}[a-z0-9])?$/u.test(record4.instance_name) || typeof record4.adapter !== "string" || !isDurableInferenceAdapterId(record4.adapter) || typeof record4.display_name !== "string" || !record4.display_name || record4.max_concurrency !== null && (!Number.isSafeInteger(record4.max_concurrency) || Number(record4.max_concurrency) < 1) || record4.authenticated_account_email !== null && typeof record4.authenticated_account_email !== "string" || record4.authenticated_account_identity !== void 0 && record4.authenticated_account_identity !== null && typeof record4.authenticated_account_identity !== "string" || record4.authenticated_account_plan !== null && typeof record4.authenticated_account_plan !== "string") {
42202
+ const record5 = value;
42203
+ if (typeof record5.instance_name !== "string" || !/^[a-z0-9](?:[a-z0-9-]{0,46}[a-z0-9])?$/u.test(record5.instance_name) || typeof record5.adapter !== "string" || !isDurableInferenceAdapterId(record5.adapter) || typeof record5.display_name !== "string" || !record5.display_name || record5.max_concurrency !== null && (!Number.isSafeInteger(record5.max_concurrency) || Number(record5.max_concurrency) < 1) || record5.authenticated_account_email !== null && typeof record5.authenticated_account_email !== "string" || record5.authenticated_account_identity !== void 0 && record5.authenticated_account_identity !== null && typeof record5.authenticated_account_identity !== "string" || record5.authenticated_account_plan !== null && typeof record5.authenticated_account_plan !== "string") {
42197
42204
  throw new Error("Inference-host service worker is invalid.");
42198
42205
  }
42199
42206
  return {
42200
- instance_name: record4.instance_name,
42201
- adapter: record4.adapter,
42202
- display_name: record4.display_name,
42203
- max_concurrency: record4.max_concurrency === null ? null : Number(record4.max_concurrency),
42204
- authenticated_account_identity: record4.authenticated_account_identity,
42205
- authenticated_account_email: record4.authenticated_account_email,
42206
- authenticated_account_plan: record4.authenticated_account_plan,
42207
- runtime_environment: assertRuntimeEnvironment(record4.runtime_environment)
42207
+ instance_name: record5.instance_name,
42208
+ adapter: record5.adapter,
42209
+ display_name: record5.display_name,
42210
+ max_concurrency: record5.max_concurrency === null ? null : Number(record5.max_concurrency),
42211
+ authenticated_account_identity: record5.authenticated_account_identity,
42212
+ authenticated_account_email: record5.authenticated_account_email,
42213
+ authenticated_account_plan: record5.authenticated_account_plan,
42214
+ runtime_environment: assertRuntimeEnvironment(record5.runtime_environment)
42208
42215
  };
42209
42216
  };
42210
42217
  assertManifest = (value) => {
42211
42218
  if (!value || typeof value !== "object" || Array.isArray(value)) {
42212
42219
  throw new Error("Inference-host service manifest is invalid.");
42213
42220
  }
42214
- const record4 = value;
42215
- if (record4.schema_version === "vtx_inference_service_v1") {
42216
- const legacy = record4;
42221
+ const record5 = value;
42222
+ if (record5.schema_version === "vtx_inference_service_v1") {
42223
+ const legacy = record5;
42217
42224
  if (legacy.adapter !== "codex" || typeof legacy.installed_at !== "string" || !Number.isFinite(Date.parse(legacy.installed_at)) || typeof legacy.executable !== "string" || !legacy.executable || typeof legacy.script !== "string" || !legacy.script || typeof legacy.display_name !== "string" || !legacy.display_name || typeof legacy.log_path !== "string" || !legacy.log_path) throw new Error("Inference-host service manifest is invalid.");
42218
42225
  const runtime_environment = withoutConcurrencyLimit(
42219
42226
  assertRuntimeEnvironment(legacy.runtime_environment)
@@ -42237,8 +42244,8 @@ var init_service = __esm({
42237
42244
  workers: [worker]
42238
42245
  };
42239
42246
  }
42240
- if (record4.schema_version === "vtx_inference_service_v2") {
42241
- const legacy = record4;
42247
+ if (record5.schema_version === "vtx_inference_service_v2") {
42248
+ const legacy = record5;
42242
42249
  if (typeof legacy.installed_at !== "string" || !Number.isFinite(Date.parse(legacy.installed_at)) || typeof legacy.executable !== "string" || !legacy.executable || typeof legacy.script !== "string" || !legacy.script || typeof legacy.log_path !== "string" || !legacy.log_path || !Array.isArray(legacy.workers) || legacy.workers.length < 1) {
42243
42250
  throw new Error("Inference-host service manifest is invalid.");
42244
42251
  }
@@ -42271,19 +42278,19 @@ var init_service = __esm({
42271
42278
  workers: workers2
42272
42279
  };
42273
42280
  }
42274
- if (record4.schema_version !== "vtx_inference_service_v3" || typeof record4.installed_at !== "string" || !Number.isFinite(Date.parse(record4.installed_at)) || typeof record4.executable !== "string" || !record4.executable || typeof record4.script !== "string" || !record4.script || typeof record4.log_path !== "string" || !record4.log_path || !Array.isArray(record4.workers) || record4.workers.length < 1) {
42281
+ if (record5.schema_version !== "vtx_inference_service_v3" || typeof record5.installed_at !== "string" || !Number.isFinite(Date.parse(record5.installed_at)) || typeof record5.executable !== "string" || !record5.executable || typeof record5.script !== "string" || !record5.script || typeof record5.log_path !== "string" || !record5.log_path || !Array.isArray(record5.workers) || record5.workers.length < 1) {
42275
42282
  throw new Error("Inference-host service manifest is invalid.");
42276
42283
  }
42277
- assertServicePath(record4.executable);
42278
- assertServicePath(record4.script);
42279
- assertServicePath(record4.log_path);
42280
- const workers = record4.workers.map(assertWorker);
42284
+ assertServicePath(record5.executable);
42285
+ assertServicePath(record5.script);
42286
+ assertServicePath(record5.log_path);
42287
+ const workers = record5.workers.map(assertWorker);
42281
42288
  if (new Set(workers.map((worker) => worker.instance_name)).size !== workers.length) {
42282
42289
  throw new Error("Inference-host service worker names must be unique.");
42283
42290
  }
42284
42291
  return {
42285
- ...record4,
42286
- generation: manifestGeneration(record4.generation, String(record4.installed_at)),
42292
+ ...record5,
42293
+ generation: manifestGeneration(record5.generation, String(record5.installed_at)),
42287
42294
  workers
42288
42295
  };
42289
42296
  };
@@ -42291,11 +42298,11 @@ var init_service = __esm({
42291
42298
  if (!value || typeof value !== "object" || Array.isArray(value)) {
42292
42299
  throw new Error("Inference-host service runtime state is invalid.");
42293
42300
  }
42294
- const record4 = value;
42295
- if (record4.schema_version !== "vtx_inference_service_runtime_v1" || typeof record4.manifest_generation !== "string" || record4.rejected_manifest_generation !== void 0 && record4.rejected_manifest_generation !== null && typeof record4.rejected_manifest_generation !== "string" || typeof record4.updated_at !== "string" || !Number.isFinite(Date.parse(record4.updated_at)) || !Array.isArray(record4.workers)) {
42301
+ const record5 = value;
42302
+ if (record5.schema_version !== "vtx_inference_service_runtime_v1" || typeof record5.manifest_generation !== "string" || record5.rejected_manifest_generation !== void 0 && record5.rejected_manifest_generation !== null && typeof record5.rejected_manifest_generation !== "string" || typeof record5.updated_at !== "string" || !Number.isFinite(Date.parse(record5.updated_at)) || !Array.isArray(record5.workers)) {
42296
42303
  throw new Error("Inference-host service runtime state is invalid.");
42297
42304
  }
42298
- const workers = record4.workers.map((worker) => {
42305
+ const workers = record5.workers.map((worker) => {
42299
42306
  if (!worker || typeof worker !== "object" || Array.isArray(worker)) {
42300
42307
  throw new Error("Inference-host service worker runtime state is invalid.");
42301
42308
  }
@@ -42309,17 +42316,17 @@ var init_service = __esm({
42309
42316
  error: item.error
42310
42317
  };
42311
42318
  });
42312
- return { ...record4, workers };
42319
+ return { ...record5, workers };
42313
42320
  };
42314
42321
  assertDesiredState = (value) => {
42315
42322
  if (!value || typeof value !== "object" || Array.isArray(value)) {
42316
42323
  throw new Error("Inference-host service desired state is invalid.");
42317
42324
  }
42318
- const record4 = value;
42319
- if (record4.schema_version !== "vtx_inference_service_desired_v1" || typeof record4.desired_running !== "boolean" || typeof record4.updated_at !== "string" || !Number.isFinite(Date.parse(record4.updated_at))) {
42325
+ const record5 = value;
42326
+ if (record5.schema_version !== "vtx_inference_service_desired_v1" || typeof record5.desired_running !== "boolean" || typeof record5.updated_at !== "string" || !Number.isFinite(Date.parse(record5.updated_at))) {
42320
42327
  throw new Error("Inference-host service desired state is invalid.");
42321
42328
  }
42322
- return record4;
42329
+ return record5;
42323
42330
  };
42324
42331
  readInferenceHostServiceManifest = async (path) => {
42325
42332
  const raw = await readInferencePrivateFile(path, "Inference-host service manifest");
@@ -43406,10 +43413,10 @@ ${result2.stderr}`)) {
43406
43413
  manifest_generation: appliedManifest.generation,
43407
43414
  rejected_manifest_generation: rejectedManifestGeneration,
43408
43415
  updated_at: (/* @__PURE__ */ new Date()).toISOString(),
43409
- workers: [...workers.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([instanceName, record4]) => ({
43416
+ workers: [...workers.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([instanceName, record5]) => ({
43410
43417
  instance_name: instanceName,
43411
- state: record4.state,
43412
- error: record4.error
43418
+ state: record5.state,
43419
+ error: record5.error
43413
43420
  }))
43414
43421
  };
43415
43422
  runtimeWriteChain = runtimeWriteChain.then(async () => {
@@ -43418,10 +43425,10 @@ ${result2.stderr}`)) {
43418
43425
  });
43419
43426
  await runtimeWriteChain;
43420
43427
  };
43421
- const updateRecord = async (record4, state, error48 = null) => {
43422
- if (workers.get(record4.worker.instance_name) !== record4) return;
43423
- record4.state = state;
43424
- record4.error = error48;
43428
+ const updateRecord = async (record5, state, error48 = null) => {
43429
+ if (workers.get(record5.worker.instance_name) !== record5) return;
43430
+ record5.state = state;
43431
+ record5.error = error48;
43425
43432
  await persistRuntime();
43426
43433
  };
43427
43434
  const waitRetry = async (milliseconds, controller) => {
@@ -43439,15 +43446,15 @@ ${result2.stderr}`)) {
43439
43446
  signal.removeEventListener("abort", finishAbort);
43440
43447
  }
43441
43448
  };
43442
- const superviseWorker = async (serviceManifest, record4) => {
43449
+ const superviseWorker = async (serviceManifest, record5) => {
43443
43450
  let failures = 0;
43444
- while (!signal.aborted && !quiesceSignal.aborted && !record4.controller.signal.aborted && await readDesiredAcrossAtomicReplacement(desiredPath)) {
43451
+ while (!signal.aborted && !quiesceSignal.aborted && !record5.controller.signal.aborted && await readDesiredAcrossAtomicReplacement(desiredPath)) {
43445
43452
  try {
43446
- await updateRecord(record4, "starting");
43453
+ await updateRecord(record5, "starting");
43447
43454
  const attemptController = new AbortController();
43448
43455
  const forwardAbort = () => attemptController.abort();
43449
43456
  signal.addEventListener("abort", forwardAbort, { once: true });
43450
- record4.controller.signal.addEventListener("abort", forwardAbort, { once: true });
43457
+ record5.controller.signal.addEventListener("abort", forwardAbort, { once: true });
43451
43458
  let result2;
43452
43459
  let launchSettled = false;
43453
43460
  let readinessTask = Promise.resolve();
@@ -43455,15 +43462,15 @@ ${result2.stderr}`)) {
43455
43462
  try {
43456
43463
  result2 = await launch(
43457
43464
  serviceManifest,
43458
- record4.worker,
43465
+ record5.worker,
43459
43466
  attemptController.signal,
43460
43467
  () => {
43461
43468
  if (readinessSignalled) return;
43462
43469
  readinessSignalled = true;
43463
43470
  readinessTask = (async () => {
43464
43471
  await sleep4(500);
43465
- if (!launchSettled && !attemptController.signal.aborted && !record4.controller.signal.aborted && !signal.aborted) {
43466
- await updateRecord(record4, "running");
43472
+ if (!launchSettled && !attemptController.signal.aborted && !record5.controller.signal.aborted && !signal.aborted) {
43473
+ await updateRecord(record5, "running");
43467
43474
  }
43468
43475
  })();
43469
43476
  },
@@ -43473,70 +43480,70 @@ ${result2.stderr}`)) {
43473
43480
  launchSettled = true;
43474
43481
  attemptController.abort();
43475
43482
  signal.removeEventListener("abort", forwardAbort);
43476
- record4.controller.signal.removeEventListener("abort", forwardAbort);
43483
+ record5.controller.signal.removeEventListener("abort", forwardAbort);
43477
43484
  await readinessTask;
43478
43485
  }
43479
43486
  if (result2.cooperativeStopTimedOut) {
43480
- await updateRecord(record4, "failed", "worker_cooperative_stop_timeout");
43487
+ await updateRecord(record5, "failed", "worker_cooperative_stop_timeout");
43481
43488
  await appendServiceLog(serviceManifest.log_path, "worker_cooperative_stop_timeout", {
43482
- instance_name: record4.worker.instance_name
43489
+ instance_name: record5.worker.instance_name
43483
43490
  });
43484
43491
  throw new Error("worker_cooperative_stop_timeout");
43485
43492
  }
43486
- if (signal.aborted || quiesceSignal.aborted || record4.controller.signal.aborted || !await readDesiredAcrossAtomicReplacement(desiredPath)) break;
43493
+ if (signal.aborted || quiesceSignal.aborted || record5.controller.signal.aborted || !await readDesiredAcrossAtomicReplacement(desiredPath)) break;
43487
43494
  failures = result2.uptimeMs >= runtime_policy_generated_default.external_inference.service.restart_stable_uptime_ms ? 0 : failures + 1;
43488
43495
  const retryAfterMs = Math.min(runtime_policy_generated_default.external_inference.service.restart_backoff_base_ms * 2 ** Math.min(failures, runtime_policy_generated_default.external_inference.service.restart_exponent_max), runtime_policy_generated_default.external_inference.service.restart_backoff_max_ms);
43489
- await updateRecord(record4, "failed", "worker_exited");
43496
+ await updateRecord(record5, "failed", "worker_exited");
43490
43497
  await appendServiceLog(serviceManifest.log_path, "worker_exited", {
43491
- instance_name: record4.worker.instance_name,
43498
+ instance_name: record5.worker.instance_name,
43492
43499
  exit_code: result2.exitCode,
43493
43500
  uptime_ms: result2.uptimeMs,
43494
43501
  drain_reason: result2.drainReason ?? null,
43495
43502
  retry_after_ms: retryAfterMs
43496
43503
  });
43497
- await waitRetry(retryAfterMs, record4.controller);
43504
+ await waitRetry(retryAfterMs, record5.controller);
43498
43505
  } catch (error48) {
43499
43506
  if (error48 instanceof Error && error48.message === "worker_cooperative_stop_timeout") throw error48;
43500
- if (signal.aborted || quiesceSignal.aborted || record4.controller.signal.aborted) break;
43507
+ if (signal.aborted || quiesceSignal.aborted || record5.controller.signal.aborted) break;
43501
43508
  failures += 1;
43502
43509
  const retryAfterMs = Math.min(runtime_policy_generated_default.external_inference.service.restart_backoff_base_ms * 2 ** Math.min(failures, runtime_policy_generated_default.external_inference.service.restart_exponent_max), runtime_policy_generated_default.external_inference.service.restart_backoff_max_ms);
43503
- await updateRecord(record4, "failed", "worker_launch_failed");
43510
+ await updateRecord(record5, "failed", "worker_launch_failed");
43504
43511
  await appendServiceLog(serviceManifest.log_path, "worker_launch_failed", {
43505
- instance_name: record4.worker.instance_name,
43512
+ instance_name: record5.worker.instance_name,
43506
43513
  error: error48 instanceof Error ? error48.message : "unknown",
43507
43514
  retry_after_ms: retryAfterMs
43508
43515
  });
43509
- await waitRetry(retryAfterMs, record4.controller);
43516
+ await waitRetry(retryAfterMs, record5.controller);
43510
43517
  }
43511
43518
  }
43512
43519
  };
43513
43520
  const startWorker = (serviceManifest, worker) => {
43514
- const record4 = {
43521
+ const record5 = {
43515
43522
  worker,
43516
43523
  controller: new AbortController(),
43517
43524
  promise: Promise.resolve(),
43518
43525
  state: "starting",
43519
43526
  error: null
43520
43527
  };
43521
- workers.set(worker.instance_name, record4);
43522
- record4.promise = superviseWorker(serviceManifest, record4);
43528
+ workers.set(worker.instance_name, record5);
43529
+ record5.promise = superviseWorker(serviceManifest, record5);
43523
43530
  };
43524
43531
  const reconcile = async (next) => {
43525
43532
  const nextByName = new Map(next.workers.map((worker) => [worker.instance_name, worker]));
43526
- const retiring = [...workers.values()].filter((record4) => {
43527
- const nextWorker = nextByName.get(record4.worker.instance_name);
43528
- return !nextWorker || !sameWorker(record4.worker, nextWorker);
43533
+ const retiring = [...workers.values()].filter((record5) => {
43534
+ const nextWorker = nextByName.get(record5.worker.instance_name);
43535
+ return !nextWorker || !sameWorker(record5.worker, nextWorker);
43529
43536
  });
43530
- for (const record4 of retiring) {
43531
- record4.controller.abort();
43532
- await updateRecord(record4, "draining");
43537
+ for (const record5 of retiring) {
43538
+ record5.controller.abort();
43539
+ await updateRecord(record5, "draining");
43533
43540
  }
43534
- const settled = await Promise.allSettled(retiring.map((record4) => record4.promise));
43541
+ const settled = await Promise.allSettled(retiring.map((record5) => record5.promise));
43535
43542
  const failedDrain = settled.find(
43536
43543
  (result2) => result2.status === "rejected"
43537
43544
  );
43538
43545
  if (failedDrain) {
43539
- for (const record4 of retiring) workers.delete(record4.worker.instance_name);
43546
+ for (const record5 of retiring) workers.delete(record5.worker.instance_name);
43540
43547
  for (const worker of appliedManifest.workers) {
43541
43548
  if (!workers.has(worker.instance_name)) startWorker(appliedManifest, worker);
43542
43549
  }
@@ -43548,7 +43555,7 @@ ${result2.stderr}`)) {
43548
43555
  });
43549
43556
  return;
43550
43557
  }
43551
- for (const record4 of retiring) workers.delete(record4.worker.instance_name);
43558
+ for (const record5 of retiring) workers.delete(record5.worker.instance_name);
43552
43559
  for (const worker of next.workers) {
43553
43560
  if (!workers.has(worker.instance_name)) startWorker(next, worker);
43554
43561
  }
@@ -43562,18 +43569,18 @@ ${result2.stderr}`)) {
43562
43569
  };
43563
43570
  const drainWorkers = async () => {
43564
43571
  const draining = [...workers.values()];
43565
- for (const record4 of draining) {
43566
- record4.controller.abort();
43567
- await updateRecord(record4, "draining");
43572
+ for (const record5 of draining) {
43573
+ record5.controller.abort();
43574
+ await updateRecord(record5, "draining");
43568
43575
  }
43569
- const settled = await Promise.allSettled(draining.map((record4) => record4.promise));
43576
+ const settled = await Promise.allSettled(draining.map((record5) => record5.promise));
43570
43577
  const failedDrain = settled.find(
43571
43578
  (result2) => result2.status === "rejected"
43572
43579
  );
43573
43580
  if (failedDrain) throw failedDrain.reason;
43574
- for (const record4 of draining) {
43575
- if (workers.get(record4.worker.instance_name) === record4) {
43576
- workers.delete(record4.worker.instance_name);
43581
+ for (const record5 of draining) {
43582
+ if (workers.get(record5.worker.instance_name) === record5) {
43583
+ workers.delete(record5.worker.instance_name);
43577
43584
  }
43578
43585
  }
43579
43586
  await persistRuntime();
@@ -43599,7 +43606,7 @@ ${result2.stderr}`)) {
43599
43606
  }
43600
43607
  if (quiesceSignal.aborted && !signal.aborted) {
43601
43608
  let finished = false;
43602
- const completion = Promise.allSettled([...workers.values()].map((record4) => record4.promise)).then((results) => {
43609
+ const completion = Promise.allSettled([...workers.values()].map((record5) => record5.promise)).then((results) => {
43603
43610
  finished = true;
43604
43611
  return results;
43605
43612
  });
@@ -43862,7 +43869,7 @@ var init_cli = __esm({
43862
43869
  if (!value || typeof value !== "object" || Array.isArray(value)) {
43863
43870
  throw new Error("Inference host revocation checkpoint is invalid.");
43864
43871
  }
43865
- const record4 = value;
43872
+ const record5 = value;
43866
43873
  const exactKeys = [
43867
43874
  "schema_version",
43868
43875
  "account_key",
@@ -43873,11 +43880,11 @@ var init_cli = __esm({
43873
43880
  "remove_credential_recovery",
43874
43881
  "remote_revoked_at"
43875
43882
  ];
43876
- const revokedAt = String(record4.remote_revoked_at || "");
43877
- if (Object.keys(record4).sort().join("\0") !== exactKeys.slice().sort().join("\0") || record4.schema_version !== "vtx_inference_revocation_v1" || typeof record4.account_key !== "string" || !record4.account_key || record4.account_key.length > 512 || typeof record4.credential_store_identity !== "string" || !record4.credential_store_identity || record4.credential_store_identity.length > 4096 || typeof record4.issuer !== "string" || !record4.issuer || record4.issuer.length > 2048 || typeof record4.client_id !== "string" || !record4.client_id || record4.client_id.length > 512 || typeof record4.host_id !== "string" || !record4.host_id || record4.host_id.length > 512 || typeof record4.remove_credential_recovery !== "boolean" || typeof record4.remote_revoked_at !== "string" || !Number.isFinite(Date.parse(revokedAt)) || new Date(revokedAt).toISOString() !== revokedAt) {
43883
+ const revokedAt = String(record5.remote_revoked_at || "");
43884
+ if (Object.keys(record5).sort().join("\0") !== exactKeys.slice().sort().join("\0") || record5.schema_version !== "vtx_inference_revocation_v1" || typeof record5.account_key !== "string" || !record5.account_key || record5.account_key.length > 512 || typeof record5.credential_store_identity !== "string" || !record5.credential_store_identity || record5.credential_store_identity.length > 4096 || typeof record5.issuer !== "string" || !record5.issuer || record5.issuer.length > 2048 || typeof record5.client_id !== "string" || !record5.client_id || record5.client_id.length > 512 || typeof record5.host_id !== "string" || !record5.host_id || record5.host_id.length > 512 || typeof record5.remove_credential_recovery !== "boolean" || typeof record5.remote_revoked_at !== "string" || !Number.isFinite(Date.parse(revokedAt)) || new Date(revokedAt).toISOString() !== revokedAt) {
43878
43885
  throw new Error("Inference host revocation checkpoint is invalid.");
43879
43886
  }
43880
- return record4;
43887
+ return record5;
43881
43888
  };
43882
43889
  readRevocationCheckpoint = async (config2) => {
43883
43890
  const raw = await readInferencePrivateFile(
@@ -45399,12 +45406,12 @@ Waiting for approval...
45399
45406
  if (!value || typeof value !== "object" || Array.isArray(value)) {
45400
45407
  throw new Error("Agent-driven inference stdin must be one JSON object.");
45401
45408
  }
45402
- const record4 = value;
45403
- const unexpected = Object.keys(record4).filter((key) => !allowedKeys.includes(key));
45409
+ const record5 = value;
45410
+ const unexpected = Object.keys(record5).filter((key) => !allowedKeys.includes(key));
45404
45411
  if (unexpected.length > 0) {
45405
45412
  throw new Error(`Unsupported agent-driven inference fields: ${unexpected.join(", ")}.`);
45406
45413
  }
45407
- return record4;
45414
+ return record5;
45408
45415
  };
45409
45416
  parseOptionalAgentStdin = async (dependencies, allowedKeys) => {
45410
45417
  if (!dependencies.readStdin && process.stdin.isTTY) return {};
@@ -45419,12 +45426,12 @@ Waiting for approval...
45419
45426
  if (!value || typeof value !== "object" || Array.isArray(value)) {
45420
45427
  throw new Error("Agent-driven inference stdin must be one JSON object.");
45421
45428
  }
45422
- const record4 = value;
45423
- const unexpected = Object.keys(record4).filter((key) => !allowedKeys.includes(key));
45429
+ const record5 = value;
45430
+ const unexpected = Object.keys(record5).filter((key) => !allowedKeys.includes(key));
45424
45431
  if (unexpected.length > 0) {
45425
45432
  throw new Error(`Unsupported agent-driven inference fields: ${unexpected.join(", ")}.`);
45426
45433
  }
45427
- return record4;
45434
+ return record5;
45428
45435
  };
45429
45436
  agentOperationId = (kind) => `${kind}-${randomUUID10()}`;
45430
45437
  agentSession = async (config2, dependencies, warnings, signal) => {
@@ -46384,7 +46391,7 @@ Waiting for approval...
46384
46391
  if (!value || typeof value !== "object" || Array.isArray(value)) {
46385
46392
  throw new Error("Inference-host service recovery transaction is invalid.");
46386
46393
  }
46387
- const record4 = value;
46394
+ const record5 = value;
46388
46395
  const exactKeys = [
46389
46396
  "schema_version",
46390
46397
  "phase",
@@ -46397,15 +46404,15 @@ Waiting for approval...
46397
46404
  "cleanup_confirmed_attempt_ids",
46398
46405
  "started_at"
46399
46406
  ];
46400
- if (Object.keys(record4).sort().join("\0") !== exactKeys.sort().join("\0") || record4.schema_version !== "vtx_inference_service_recovery_v1" || record4.phase !== "prepared" && record4.phase !== "reconciled" || typeof record4.transaction_id !== "string" || !/^[0-9a-f-]{36}$/u.test(record4.transaction_id) || typeof record4.instance_name !== "string" || typeof record4.manifest_generation !== "string" || typeof record4.restore_desired_running !== "boolean" || typeof record4.recovery_backup_path !== "string" || typeof record4.recovery_backup_sha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record4.recovery_backup_sha256) || !Array.isArray(record4.cleanup_confirmed_attempt_ids) || record4.cleanup_confirmed_attempt_ids.some(
46407
+ if (Object.keys(record5).sort().join("\0") !== exactKeys.sort().join("\0") || record5.schema_version !== "vtx_inference_service_recovery_v1" || record5.phase !== "prepared" && record5.phase !== "reconciled" || typeof record5.transaction_id !== "string" || !/^[0-9a-f-]{36}$/u.test(record5.transaction_id) || typeof record5.instance_name !== "string" || typeof record5.manifest_generation !== "string" || typeof record5.restore_desired_running !== "boolean" || typeof record5.recovery_backup_path !== "string" || typeof record5.recovery_backup_sha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record5.recovery_backup_sha256) || !Array.isArray(record5.cleanup_confirmed_attempt_ids) || record5.cleanup_confirmed_attempt_ids.some(
46401
46408
  (attemptId) => typeof attemptId !== "string" || attemptId.length < 1 || attemptId.length > 256
46402
- ) || new Set(record4.cleanup_confirmed_attempt_ids).size !== record4.cleanup_confirmed_attempt_ids.length || [...record4.cleanup_confirmed_attempt_ids].sort().join("\0") !== record4.cleanup_confirmed_attempt_ids.join("\0") || typeof record4.started_at !== "string" || !Number.isFinite(Date.parse(record4.started_at)) || new Date(record4.started_at).toISOString() !== record4.started_at) {
46409
+ ) || new Set(record5.cleanup_confirmed_attempt_ids).size !== record5.cleanup_confirmed_attempt_ids.length || [...record5.cleanup_confirmed_attempt_ids].sort().join("\0") !== record5.cleanup_confirmed_attempt_ids.join("\0") || typeof record5.started_at !== "string" || !Number.isFinite(Date.parse(record5.started_at)) || new Date(record5.started_at).toISOString() !== record5.started_at) {
46403
46410
  throw new Error("Inference-host service recovery transaction is invalid.");
46404
46411
  }
46405
- if (resolve11(record4.recovery_backup_path) !== resolve11(recoveryBackupPath(config2, record4.transaction_id))) {
46412
+ if (resolve11(record5.recovery_backup_path) !== resolve11(recoveryBackupPath(config2, record5.transaction_id))) {
46406
46413
  throw new Error("Inference-host service recovery backup path is invalid.");
46407
46414
  }
46408
- return record4;
46415
+ return record5;
46409
46416
  };
46410
46417
  assertResumableCodexRecoveryEvidence = (backupAttempts, currentAttempts, cleanupConfirmedAttemptIds, phase) => {
46411
46418
  const backupIds = Object.keys(backupAttempts).sort();
@@ -48964,7 +48971,7 @@ var init_network_debug = __esm({
48964
48971
  });
48965
48972
 
48966
48973
  // lib/runtime/hyperliquid-account-state-adapter.ts
48967
- var unsupportedUserActiveAssetCache, MAX_UNSUPPORTED_USER_ACTIVE_ASSET_CACHE_KEYS, UNSUPPORTED_USER_ACTIVE_ASSET_STORAGE_KEY, USER_FILLS_CACHE_STORAGE_PREFIX, ACCOUNT_STATE_CACHE_STORAGE_PREFIX, INFO_RATE_LIMIT_COOLDOWN_STORAGE_PREFIX, INFO_RATE_LIMIT_COOLDOWN_MIN_MS, INFO_RATE_LIMIT_COOLDOWN_MAX_MS, browserUserFillsCache, browserUserFillsInFlight, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP, browserAccountStateCache, browserAccountStateInFlight, browserInfoRateLimitCooldowns, UNSUPPORTED_USER_ACTIVE_ASSET_DETAIL_PATTERNS, unsupportedUserActiveAssetCacheHydrated, hydrateUnsupportedUserActiveAssetCache, persistUnsupportedUserActiveAssetCache, toPositiveFinite, toFinite, firstFiniteNumber, parseFundingUsdcFromInfoPosition, buildActiveAssetCacheKey, buildUserFillsCacheKey, buildUserFillsStorageKey, buildAccountStateCacheKey, buildAccountStateStorageKey, normalizeInfoRateLimitApiUrl, normalizeInfoRequestType, buildInfoRateLimitCooldownKey, buildInfoRateLimitCooldownStorageKey, readInfoRateLimitCooldownUntilMs, hasActiveInfoRateLimitCooldown, writeInfoRateLimitCooldown, extractInfoRequestTypeFromRateLimitError, recordInfoRateLimitCooldownFromError, requireNonNegativeConfigSeconds, requireAccountStateCacheConfig, requireUserFillsCacheConfig, normalizeFillSymbol, buildSymbolFilter, filterFillsBySymbols, readBrowserUserFillsCache, writeBrowserUserFillsCache, cloneBrowserAccountStateResult, withAccountStateEvidence, readBrowserAccountStateCache, writeBrowserAccountStateCache, isRateLimitError, createAbortError, waitForSharedBrowserRequest, waitForSharedBrowserUserFills, getBrowserActiveAssetTypeCandidates, normalizeHyperliquidErrorDetail, isUnsupportedUserActiveAssetError, rememberUnsupportedUserActiveAssetKey, parseInfoPositions, requireFinitePromptMetric, requirePromptClearinghouseState, requirePromptSpotState, normalizePerpDexName, listConfiguredPerpDexs, listPerpDexsForAccountState, prefixHip3PositionCoins, aggregateClearinghouseResponses, normalizeBrowserFillToTradeHistory, isPerpFill, fetchHyperliquidInfoPayload, requireHyperliquidApiUrl, requireWalletAddress, parseInfoPositionSnapshot, fetchBrowserAccountState, fetchBrowserAccountStateUncached, fetchBrowserUserFills, fetchBrowserPositionSnapshot;
48974
+ var unsupportedUserActiveAssetCache, MAX_UNSUPPORTED_USER_ACTIVE_ASSET_CACHE_KEYS, UNSUPPORTED_USER_ACTIVE_ASSET_STORAGE_KEY, USER_FILLS_CACHE_STORAGE_PREFIX, ACCOUNT_STATE_CACHE_STORAGE_PREFIX, INFO_RATE_LIMIT_COOLDOWN_STORAGE_PREFIX, INFO_RATE_LIMIT_COOLDOWN_MIN_MS, INFO_RATE_LIMIT_COOLDOWN_MAX_MS, browserUserFillsCache, browserUserFillsInFlight, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP, browserAccountStateCache, browserAccountStateInFlight, browserInfoRateLimitCooldowns, UNSUPPORTED_USER_ACTIVE_ASSET_DETAIL_PATTERNS, unsupportedUserActiveAssetCacheHydrated, hydrateUnsupportedUserActiveAssetCache, persistUnsupportedUserActiveAssetCache, toPositiveFinite, toFinite, firstFiniteNumber, parseFundingUsdcFromInfoPosition, buildActiveAssetCacheKey, buildUserFillsCacheKey, buildUserFillsStorageKey, buildAccountStateCacheKey, buildAccountStateStorageKey, normalizeInfoRateLimitApiUrl, normalizeInfoRequestType, buildInfoRateLimitCooldownKey, buildInfoRateLimitCooldownStorageKey, readInfoRateLimitCooldownUntilMs, hasActiveInfoRateLimitCooldown, writeInfoRateLimitCooldown, extractInfoRequestTypeFromRateLimitError, recordInfoRateLimitCooldownFromError, requireNonNegativeConfigSeconds, requireAccountStateCacheConfig, requireUserFillsCacheConfig, normalizeFillSymbol, buildSymbolFilter, filterFillsBySymbols, readBrowserUserFillsCache, writeBrowserUserFillsCache, cloneBrowserAccountStateResult, withAccountStateEvidence, readBrowserAccountStateCache, writeBrowserAccountStateCache, isRateLimitError, createAbortError, waitForSharedBrowserRequest, waitForSharedBrowserUserFills, getBrowserActiveAssetTypeCandidates, normalizeHyperliquidErrorDetail, isUnsupportedUserActiveAssetError, rememberUnsupportedUserActiveAssetKey, parseInfoPositions, requireFinitePromptMetric, requirePromptClearinghouseState, requirePromptSpotState, normalizePerpDexName, listConfiguredPerpDexs, listPerpDexsForAccountState, prefixHip3PositionCoins, aggregateClearinghouseResponses, hasCompletePerpDexAccountMetrics, normalizeBrowserFillToTradeHistory, isPerpFill, fetchHyperliquidInfoPayload, requireHyperliquidApiUrl, requireWalletAddress, parseInfoPositionSnapshot, fetchBrowserAccountState, fetchBrowserAccountStateUncached, fetchBrowserUserFills, fetchBrowserPositionSnapshot;
48968
48975
  var init_hyperliquid_account_state_adapter = __esm({
48969
48976
  "lib/runtime/hyperliquid-account-state-adapter.ts"() {
48970
48977
  "use strict";
@@ -49652,6 +49659,20 @@ var init_hyperliquid_account_state_adapter = __esm({
49652
49659
  assetPositions
49653
49660
  };
49654
49661
  };
49662
+ hasCompletePerpDexAccountMetrics = (response) => {
49663
+ const isFiniteMetric = (value) => (typeof value === "number" || typeof value === "string" && value.trim() !== "") && Number.isFinite(Number(value));
49664
+ if (!response || typeof response !== "object" || Array.isArray(response)) return false;
49665
+ const margin = response.marginSummary;
49666
+ if (!margin || typeof margin !== "object" || Array.isArray(margin)) return false;
49667
+ if (![margin.accountValue, margin.totalMarginUsed, response.withdrawable].every(isFiniteMetric)) return false;
49668
+ const maintenanceValues = [response.crossMaintenanceMarginUsed, margin.crossMaintenanceMarginUsed, margin.totalMaintenanceMargin].filter((value) => value != null);
49669
+ if (maintenanceValues.length === 0 || !maintenanceValues.every(isFiniteMetric)) return false;
49670
+ if (!Array.isArray(response.assetPositions)) return false;
49671
+ return response.assetPositions.every((entry) => {
49672
+ const position = entry?.position;
49673
+ return position && typeof position === "object" && !Array.isArray(position) && [position.szi, position.entryPx, position.unrealizedPnl].every(isFiniteMetric);
49674
+ });
49675
+ };
49655
49676
  normalizeBrowserFillToTradeHistory = (fill) => {
49656
49677
  if (!fill || typeof fill !== "object") {
49657
49678
  return null;
@@ -49889,7 +49910,8 @@ var init_hyperliquid_account_state_adapter = __esm({
49889
49910
  }
49890
49911
  return {
49891
49912
  dex: dexName,
49892
- payload: prefixHip3PositionCoins(response, dexName)
49913
+ payload: prefixHip3PositionCoins(response, dexName),
49914
+ rawPayload: response
49893
49915
  };
49894
49916
  })
49895
49917
  );
@@ -49903,6 +49925,10 @@ var init_hyperliquid_account_state_adapter = __esm({
49903
49925
  ...dexResponses.map((entry) => entry.payload)
49904
49926
  ]),
49905
49927
  selectedPayload,
49928
+ dexPayloads: [
49929
+ { dex: "", payload: defaultResponse },
49930
+ ...dexResponses.map(({ dex, rawPayload }) => ({ dex, payload: rawPayload }))
49931
+ ],
49906
49932
  capturedAt: (/* @__PURE__ */ new Date()).toISOString()
49907
49933
  };
49908
49934
  })();
@@ -50043,6 +50069,31 @@ var init_hyperliquid_account_state_adapter = __esm({
50043
50069
  );
50044
50070
  const accountSummary = {
50045
50071
  ...normalizedSummary,
50072
+ ...input.scopeAccountSummaryToSelectedDex === true ? {} : {
50073
+ perp_dex_accounts: perpsResult.dexPayloads.filter(({ payload }) => hasCompletePerpDexAccountMetrics(payload)).map(({ dex, payload }) => {
50074
+ const summary = buildServerPromptRescueAccountSummary({
50075
+ ...payload,
50076
+ crossMaintenanceMarginUsed: firstFiniteNumber([
50077
+ payload.crossMaintenanceMarginUsed,
50078
+ payload.marginSummary?.crossMaintenanceMarginUsed,
50079
+ payload.marginSummary?.totalMaintenanceMargin
50080
+ ])
50081
+ }, {}, "disabled", accountSummaryOptions);
50082
+ const accountValue = Number(payload.marginSummary.accountValue);
50083
+ const calculatedAvailable = accountValue - summary.total_margin_used;
50084
+ const availableMargin = summary.maintenance_margin > 0 ? Math.max(calculatedAvailable, Math.max(0, accountValue - 4 * summary.maintenance_margin), summary.withdrawable) : Math.max(calculatedAvailable, summary.withdrawable);
50085
+ return {
50086
+ dex,
50087
+ account_value: accountValue,
50088
+ total_margin_used: summary.total_margin_used,
50089
+ available_margin: availableMargin,
50090
+ withdrawable: summary.withdrawable,
50091
+ maintenance_margin: summary.maintenance_margin,
50092
+ cross_account_leverage: summary.cross_account_leverage,
50093
+ total_unrealized_pnl: summary.total_unrealized_pnl ?? 0
50094
+ };
50095
+ })
50096
+ },
50046
50097
  ...exactAccountMode == null ? {} : { account_mode: exactAccountMode.accountMode, mode_source: "canonical" },
50047
50098
  address: walletAddress,
50048
50099
  dex: input.scopeAccountSummaryToSelectedDex === true ? selectedDex : "all",
@@ -50560,11 +50611,11 @@ var init_local_breadcrumbs = __esm({
50560
50611
  if (!value || typeof value !== "object" || Array.isArray(value)) {
50561
50612
  return null;
50562
50613
  }
50563
- const record4 = value;
50564
- const id2 = sanitizeOptionalString(record4.id);
50565
- const createdAt = sanitizeOptionalString(record4.createdAt);
50566
- const scope = record4.scope === "engine" || record4.scope === "host" || record4.scope === "api" ? record4.scope : null;
50567
- const kind = sanitizeOptionalString(record4.kind);
50614
+ const record5 = value;
50615
+ const id2 = sanitizeOptionalString(record5.id);
50616
+ const createdAt = sanitizeOptionalString(record5.createdAt);
50617
+ const scope = record5.scope === "engine" || record5.scope === "host" || record5.scope === "api" ? record5.scope : null;
50618
+ const kind = sanitizeOptionalString(record5.kind);
50568
50619
  if (!id2 || !createdAt || !scope || !kind) {
50569
50620
  return null;
50570
50621
  }
@@ -50573,16 +50624,16 @@ var init_local_breadcrumbs = __esm({
50573
50624
  createdAt,
50574
50625
  scope,
50575
50626
  kind,
50576
- detail: sanitizeOptionalString(record4.detail),
50577
- profileId: sanitizeOptionalString(record4.profileId),
50578
- sessionId: sanitizeOptionalString(record4.sessionId),
50579
- deviceId: sanitizeOptionalString(record4.deviceId),
50580
- mode: record4.mode === "assistant" ? "assistant" : record4.mode === "trader" ? "trader" : null,
50581
- runtimeState: record4.runtimeState === "stopped" || record4.runtimeState === "running" || record4.runtimeState === "stale" || record4.runtimeState === "offline" || record4.runtimeState === "error" ? record4.runtimeState : null,
50582
- lastRunAt: sanitizeOptionalString(record4.lastRunAt),
50583
- visibilityState: sanitizeOptionalString(record4.visibilityState),
50584
- online: typeof record4.online === "boolean" ? record4.online : null,
50585
- payload: clonePayload(record4.payload ?? null)
50627
+ detail: sanitizeOptionalString(record5.detail),
50628
+ profileId: sanitizeOptionalString(record5.profileId),
50629
+ sessionId: sanitizeOptionalString(record5.sessionId),
50630
+ deviceId: sanitizeOptionalString(record5.deviceId),
50631
+ mode: record5.mode === "assistant" ? "assistant" : record5.mode === "trader" ? "trader" : null,
50632
+ runtimeState: record5.runtimeState === "stopped" || record5.runtimeState === "running" || record5.runtimeState === "stale" || record5.runtimeState === "offline" || record5.runtimeState === "error" ? record5.runtimeState : null,
50633
+ lastRunAt: sanitizeOptionalString(record5.lastRunAt),
50634
+ visibilityState: sanitizeOptionalString(record5.visibilityState),
50635
+ online: typeof record5.online === "boolean" ? record5.online : null,
50636
+ payload: clonePayload(record5.payload ?? null)
50586
50637
  };
50587
50638
  };
50588
50639
  readLocalRuntimeBreadcrumbs = () => {
@@ -50664,6 +50715,9 @@ var init_runtime_policy_generated2 = __esm({
50664
50715
  "lib/runtime-policy.generated.json"() {
50665
50716
  runtime_policy_generated_default2 = {
50666
50717
  ui: {
50718
+ performance_defaults: {
50719
+ default_timeframe: "30d"
50720
+ },
50667
50721
  auth_bootstrap_retry: {
50668
50722
  max_attempts: 3,
50669
50723
  jitter_milliseconds: 750,
@@ -50948,59 +51002,59 @@ var init_server_runtime_lease = __esm({
50948
51002
  if (!value || typeof value !== "object" || Array.isArray(value)) {
50949
51003
  return null;
50950
51004
  }
50951
- const record4 = value;
50952
- if (String(record4.profileId ?? "").trim() !== profileId) {
51005
+ const record5 = value;
51006
+ if (String(record5.profileId ?? "").trim() !== profileId) {
50953
51007
  return null;
50954
51008
  }
50955
- if (!String(record4.runtimeLeaseToken ?? "").trim()) {
51009
+ if (!String(record5.runtimeLeaseToken ?? "").trim()) {
50956
51010
  return null;
50957
51011
  }
50958
- if (!String(record4.leaseId ?? "").trim()) {
51012
+ if (!String(record5.leaseId ?? "").trim()) {
50959
51013
  return null;
50960
51014
  }
50961
- if (!String(record4.runtimeSessionId ?? "").trim()) {
51015
+ if (!String(record5.runtimeSessionId ?? "").trim()) {
50962
51016
  return null;
50963
51017
  }
50964
- if (!String(record4.deviceId ?? "").trim()) {
51018
+ if (!String(record5.deviceId ?? "").trim()) {
50965
51019
  return null;
50966
51020
  }
50967
- if (record4.mode !== "assistant" && record4.mode !== "trader") {
51021
+ if (record5.mode !== "assistant" && record5.mode !== "trader") {
50968
51022
  return null;
50969
51023
  }
50970
- if (record4.scope !== "trade-runtime") {
51024
+ if (record5.scope !== "trade-runtime") {
50971
51025
  return null;
50972
51026
  }
50973
- if (!String(record4.issuedAt ?? "").trim()) {
51027
+ if (!String(record5.issuedAt ?? "").trim()) {
50974
51028
  return null;
50975
51029
  }
50976
- if (!String(record4.expiresAt ?? "").trim()) {
51030
+ if (!String(record5.expiresAt ?? "").trim()) {
50977
51031
  return null;
50978
51032
  }
50979
- if (!String(record4.renewableUntil ?? "").trim()) {
51033
+ if (!String(record5.renewableUntil ?? "").trim()) {
50980
51034
  return null;
50981
51035
  }
50982
- if (!Number.isFinite(Number(record4.savedAt))) {
51036
+ if (!Number.isFinite(Number(record5.savedAt))) {
50983
51037
  return null;
50984
51038
  }
50985
51039
  return {
50986
51040
  profileId,
50987
- runtimeLeaseToken: String(record4.runtimeLeaseToken),
50988
- leaseId: String(record4.leaseId),
50989
- runtimeSessionId: String(record4.runtimeSessionId),
50990
- deviceId: String(record4.deviceId),
50991
- schedulerInstanceId: String(record4.schedulerInstanceId ?? "").trim() || null,
50992
- mode: record4.mode,
51041
+ runtimeLeaseToken: String(record5.runtimeLeaseToken),
51042
+ leaseId: String(record5.leaseId),
51043
+ runtimeSessionId: String(record5.runtimeSessionId),
51044
+ deviceId: String(record5.deviceId),
51045
+ schedulerInstanceId: String(record5.schedulerInstanceId ?? "").trim() || null,
51046
+ mode: record5.mode,
50993
51047
  scope: "trade-runtime",
50994
- leaseGeneration: normalizeLeaseGeneration(record4.leaseGeneration),
50995
- issuedAt: String(record4.issuedAt),
50996
- expiresAt: String(record4.expiresAt),
50997
- renewableUntil: String(record4.renewableUntil),
50998
- lastSeenAt: record4.lastSeenAt ?? null,
50999
- renewedAt: record4.renewedAt ?? null,
51000
- revokedAt: record4.revokedAt ?? null,
51001
- transport: typeof record4.transport === "object" && record4.transport != null ? record4.transport : {},
51002
- runtimeContractIdentity: record4.runtimeContractIdentity ?? null,
51003
- savedAt: Number(record4.savedAt)
51048
+ leaseGeneration: normalizeLeaseGeneration(record5.leaseGeneration),
51049
+ issuedAt: String(record5.issuedAt),
51050
+ expiresAt: String(record5.expiresAt),
51051
+ renewableUntil: String(record5.renewableUntil),
51052
+ lastSeenAt: record5.lastSeenAt ?? null,
51053
+ renewedAt: record5.renewedAt ?? null,
51054
+ revokedAt: record5.revokedAt ?? null,
51055
+ transport: typeof record5.transport === "object" && record5.transport != null ? record5.transport : {},
51056
+ runtimeContractIdentity: record5.runtimeContractIdentity ?? null,
51057
+ savedAt: Number(record5.savedAt)
51004
51058
  };
51005
51059
  };
51006
51060
  readPersistedLeaseMap = () => {
@@ -51088,7 +51142,7 @@ var init_server_runtime_lease = __esm({
51088
51142
  if (!profileId || !runtimeLeaseToken) {
51089
51143
  return null;
51090
51144
  }
51091
- const record4 = {
51145
+ const record5 = {
51092
51146
  profileId,
51093
51147
  runtimeLeaseToken,
51094
51148
  leaseId: String(lease.lease_id),
@@ -51110,23 +51164,23 @@ var init_server_runtime_lease = __esm({
51110
51164
  };
51111
51165
  const leaseMap = readPersistedLeaseMap();
51112
51166
  const existingLease = leaseMap[profileId] ?? null;
51113
- if (existingLease && record4.leaseId !== existingLease.leaseId) {
51114
- const incomingGeneration = record4.leaseGeneration ?? null;
51167
+ if (existingLease && record5.leaseId !== existingLease.leaseId) {
51168
+ const incomingGeneration = record5.leaseGeneration ?? null;
51115
51169
  const existingGeneration = existingLease.leaseGeneration ?? null;
51116
51170
  if (existingGeneration !== null && incomingGeneration === null || existingGeneration !== null && incomingGeneration !== null && incomingGeneration <= existingGeneration) {
51117
51171
  return existingLease;
51118
51172
  }
51119
51173
  if (existingGeneration === null && incomingGeneration === null) {
51120
- const incomingIssuedAtMs = Date.parse(record4.issuedAt);
51174
+ const incomingIssuedAtMs = Date.parse(record5.issuedAt);
51121
51175
  const existingIssuedAtMs = Date.parse(existingLease.issuedAt);
51122
51176
  if (Number.isFinite(incomingIssuedAtMs) && Number.isFinite(existingIssuedAtMs) && incomingIssuedAtMs < existingIssuedAtMs) {
51123
51177
  return existingLease;
51124
51178
  }
51125
51179
  }
51126
51180
  }
51127
- leaseMap[profileId] = record4;
51181
+ leaseMap[profileId] = record5;
51128
51182
  writePersistedLeaseMap(leaseMap);
51129
- return record4;
51183
+ return record5;
51130
51184
  };
51131
51185
  clearPersistedClientRuntimeServerLease = (profileId) => {
51132
51186
  const normalizedProfileId = normalizeProfileId(profileId);
@@ -52527,19 +52581,19 @@ function assert2(check2, message, code, info) {
52527
52581
  function assertArgument(check2, message, name, value) {
52528
52582
  assert2(check2, message, "INVALID_ARGUMENT", { argument: name, value });
52529
52583
  }
52530
- function assertArgumentCount(count3, expectedCount, message) {
52584
+ function assertArgumentCount(count4, expectedCount, message) {
52531
52585
  if (message == null) {
52532
52586
  message = "";
52533
52587
  }
52534
52588
  if (message) {
52535
52589
  message = ": " + message;
52536
52590
  }
52537
- assert2(count3 >= expectedCount, "missing argument" + message, "MISSING_ARGUMENT", {
52538
- count: count3,
52591
+ assert2(count4 >= expectedCount, "missing argument" + message, "MISSING_ARGUMENT", {
52592
+ count: count4,
52539
52593
  expectedCount
52540
52594
  });
52541
- assert2(count3 <= expectedCount, "too many arguments" + message, "UNEXPECTED_ARGUMENT", {
52542
- count: count3,
52595
+ assert2(count4 <= expectedCount, "too many arguments" + message, "UNEXPECTED_ARGUMENT", {
52596
+ count: count4,
52543
52597
  expectedCount
52544
52598
  });
52545
52599
  }
@@ -55182,15 +55236,15 @@ var init_abstract_coder = __esm({
55182
55236
  get bytes() {
55183
55237
  return new Uint8Array(this.#data);
55184
55238
  }
55185
- #incrementBytesRead(count3) {
55239
+ #incrementBytesRead(count4) {
55186
55240
  if (this.#parent) {
55187
- return this.#parent.#incrementBytesRead(count3);
55241
+ return this.#parent.#incrementBytesRead(count4);
55188
55242
  }
55189
- this.#bytesRead += count3;
55243
+ this.#bytesRead += count4;
55190
55244
  assert2(this.#maxInflation < 1 || this.#bytesRead <= this.#maxInflation * this.dataLength, `compressed ABI data exceeds inflation ratio of ${this.#maxInflation} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`, "BUFFER_OVERRUN", {
55191
55245
  buffer: getBytesCopy(this.#data),
55192
55246
  offset: this.#offset,
55193
- length: count3,
55247
+ length: count4,
55194
55248
  info: {
55195
55249
  bytesRead: this.#bytesRead,
55196
55250
  dataLength: this.dataLength
@@ -60301,12 +60355,12 @@ var init_array = __esm({
60301
60355
  if (!Array.isArray(value)) {
60302
60356
  this._throwError("expected array value", value);
60303
60357
  }
60304
- let count3 = this.length;
60305
- if (count3 === -1) {
60306
- count3 = value.length;
60358
+ let count4 = this.length;
60359
+ if (count4 === -1) {
60360
+ count4 = value.length;
60307
60361
  writer.writeValue(value.length);
60308
60362
  }
60309
- assertArgumentCount(value.length, count3, "coder array" + (this.localName ? " " + this.localName : ""));
60363
+ assertArgumentCount(value.length, count4, "coder array" + (this.localName ? " " + this.localName : ""));
60310
60364
  let coders = [];
60311
60365
  for (let i = 0; i < value.length; i++) {
60312
60366
  coders.push(this.coder);
@@ -60314,13 +60368,13 @@ var init_array = __esm({
60314
60368
  return pack(writer, coders, value);
60315
60369
  }
60316
60370
  decode(reader) {
60317
- let count3 = this.length;
60318
- if (count3 === -1) {
60319
- count3 = reader.readIndex();
60320
- assert2(count3 * WordSize <= reader.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: reader.bytes, offset: count3 * WordSize, length: reader.dataLength });
60371
+ let count4 = this.length;
60372
+ if (count4 === -1) {
60373
+ count4 = reader.readIndex();
60374
+ assert2(count4 * WordSize <= reader.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: reader.bytes, offset: count4 * WordSize, length: reader.dataLength });
60321
60375
  }
60322
60376
  let coders = [];
60323
- for (let i = 0; i < count3; i++) {
60377
+ for (let i = 0; i < count4; i++) {
60324
60378
  coders.push(new AnonymousCoder(this.coder));
60325
60379
  }
60326
60380
  return unpack(reader, coders);
@@ -62887,8 +62941,8 @@ function _pack(type, value, isArray) {
62887
62941
  match = type.match(regexArray);
62888
62942
  if (match && Array.isArray(value)) {
62889
62943
  const baseType = match[1];
62890
- const count3 = parseInt(match[2] || String(value.length));
62891
- assertArgument(count3 === value.length, `invalid array length for ${type}`, "value", value);
62944
+ const count4 = parseInt(match[2] || String(value.length));
62945
+ assertArgument(count4 === value.length, `invalid array length for ${type}`, "value", value);
62892
62946
  const result2 = [];
62893
62947
  value.forEach(function(value2) {
62894
62948
  result2.push(_pack(baseType, value2, true));
@@ -67790,7 +67844,7 @@ async function _emit(contract, event, args, payloadFunc) {
67790
67844
  if (!sub) {
67791
67845
  return false;
67792
67846
  }
67793
- const count3 = sub.listeners.length;
67847
+ const count4 = sub.listeners.length;
67794
67848
  sub.listeners = sub.listeners.filter(({ listener, once: once2 }) => {
67795
67849
  const passArgs = Array.from(args);
67796
67850
  if (payloadFunc) {
@@ -67806,7 +67860,7 @@ async function _emit(contract, event, args, payloadFunc) {
67806
67860
  sub.stop();
67807
67861
  getInternal(contract).subs.delete(sub.tag);
67808
67862
  }
67809
- return count3 > 0;
67863
+ return count4 > 0;
67810
67864
  }
67811
67865
  async function emit(contract, event, args, payloadFunc) {
67812
67866
  try {
@@ -71025,7 +71079,7 @@ var init_abstract_provider = __esm({
71025
71079
  return false;
71026
71080
  }
71027
71081
  ;
71028
- const count3 = sub.listeners.length;
71082
+ const count4 = sub.listeners.length;
71029
71083
  sub.listeners = sub.listeners.filter(({ listener, once: once2 }) => {
71030
71084
  const payload = new EventPayload(this, once2 ? null : listener, event);
71031
71085
  try {
@@ -71040,7 +71094,7 @@ var init_abstract_provider = __esm({
71040
71094
  }
71041
71095
  this.#subs.delete(sub.tag);
71042
71096
  }
71043
- return count3 > 0;
71097
+ return count4 > 0;
71044
71098
  }
71045
71099
  async listenerCount(event) {
71046
71100
  if (event) {
@@ -80020,10 +80074,10 @@ function getDecryptKdfParams(data4) {
80020
80074
  const prf = spelunk(data4, "crypto.kdfparams.prf:string!");
80021
80075
  const algorithm = prf.split("-").pop();
80022
80076
  assertArgument(algorithm === "sha256" || algorithm === "sha512", "invalid kdf.pdf", "kdf.pdf", prf);
80023
- const count3 = spelunk(data4, "crypto.kdfparams.c:int!");
80077
+ const count4 = spelunk(data4, "crypto.kdfparams.c:int!");
80024
80078
  const dkLen = spelunk(data4, "crypto.kdfparams.dklen:int!");
80025
80079
  assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dklen", dkLen);
80026
- return { name: "pbkdf2", salt, count: count3, dkLen, algorithm };
80080
+ return { name: "pbkdf2", salt, count: count4, dkLen, algorithm };
80027
80081
  }
80028
80082
  }
80029
80083
  assertArgument(false, "unsupported key-derivation function", "kdf", kdf);
@@ -80033,8 +80087,8 @@ function decryptKeystoreJsonSync(json2, _password) {
80033
80087
  const password = getPassword(_password);
80034
80088
  const params = getDecryptKdfParams(data4);
80035
80089
  if (params.name === "pbkdf2") {
80036
- const { salt: salt2, count: count3, dkLen: dkLen2, algorithm } = params;
80037
- const key2 = pbkdf2(password, salt2, count3, dkLen2, algorithm);
80090
+ const { salt: salt2, count: count4, dkLen: dkLen2, algorithm } = params;
80091
+ const key2 = pbkdf2(password, salt2, count4, dkLen2, algorithm);
80038
80092
  return getAccount(data4, key2);
80039
80093
  }
80040
80094
  assert2(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params });
@@ -80058,8 +80112,8 @@ async function decryptKeystoreJson(json2, _password, progress) {
80058
80112
  progress(0);
80059
80113
  await stall3(0);
80060
80114
  }
80061
- const { salt: salt2, count: count3, dkLen: dkLen2, algorithm } = params;
80062
- const key2 = pbkdf2(password, salt2, count3, dkLen2, algorithm);
80115
+ const { salt: salt2, count: count4, dkLen: dkLen2, algorithm } = params;
80116
+ const key2 = pbkdf2(password, salt2, count4, dkLen2, algorithm);
80063
80117
  if (progress) {
80064
80118
  progress(1);
80065
80119
  await stall3(0);
@@ -84390,8 +84444,8 @@ var init_hyperliquid_client = __esm({
84390
84444
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
84391
84445
  return { referenceSourceKind: "l2_unavailable" };
84392
84446
  }
84393
- const record4 = payload;
84394
- const observedMs = Number(record4.time);
84447
+ const record5 = payload;
84448
+ const observedMs = Number(record5.time);
84395
84449
  const nowMs = Date.now();
84396
84450
  const referenceAgeMs = Number.isFinite(observedMs) ? Math.max(0, nowMs - observedMs) : null;
84397
84451
  const referenceObservedAt = Number.isFinite(observedMs) ? new Date(observedMs).toISOString() : null;
@@ -84402,7 +84456,7 @@ var init_hyperliquid_client = __esm({
84402
84456
  referenceAgeMs
84403
84457
  };
84404
84458
  }
84405
- const levels = Array.isArray(record4.levels) ? record4.levels : [];
84459
+ const levels = Array.isArray(record5.levels) ? record5.levels : [];
84406
84460
  const bids = Array.isArray(levels[0]) ? levels[0] : [];
84407
84461
  const asks = Array.isArray(levels[1]) ? levels[1] : [];
84408
84462
  const levelPrice = (value) => {
@@ -85024,12 +85078,12 @@ function validateDeviceSecrets(value, options) {
85024
85078
  missing: missing3
85025
85079
  };
85026
85080
  }
85027
- const record4 = value;
85028
- const rawProviderKeys = record4.providerKeys && typeof record4.providerKeys === "object" ? record4.providerKeys : {};
85081
+ const record5 = value;
85082
+ const rawProviderKeys = record5.providerKeys && typeof record5.providerKeys === "object" ? record5.providerKeys : {};
85029
85083
  const providerKeys = Object.fromEntries(
85030
85084
  Object.entries(rawProviderKeys).map(([provider, key]) => [provider, typeof key === "string" ? key.trim() : ""]).filter(([, key]) => Boolean(key))
85031
85085
  );
85032
- const rawProviderKeySlots = record4.providerKeySlots && typeof record4.providerKeySlots === "object" ? record4.providerKeySlots : {};
85086
+ const rawProviderKeySlots = record5.providerKeySlots && typeof record5.providerKeySlots === "object" ? record5.providerKeySlots : {};
85033
85087
  const providerKeySlots = Object.fromEntries(
85034
85088
  Object.entries(rawProviderKeySlots).map(([provider, value2]) => {
85035
85089
  const slots = Array.isArray(value2) ? value2.map((key) => typeof key === "string" ? key.trim() : "").filter(Boolean) : [];
@@ -85042,27 +85096,27 @@ function validateDeviceSecrets(value, options) {
85042
85096
  Object.entries(providerKeySlots).map(([provider, slots]) => [provider, slots[0]]).filter(([, key]) => Boolean(key))
85043
85097
  )
85044
85098
  };
85045
- const rawProviderBaseUrls = record4.providerBaseUrls && typeof record4.providerBaseUrls === "object" ? record4.providerBaseUrls : {};
85099
+ const rawProviderBaseUrls = record5.providerBaseUrls && typeof record5.providerBaseUrls === "object" ? record5.providerBaseUrls : {};
85046
85100
  const providerBaseUrls = Object.fromEntries(
85047
85101
  Object.entries(rawProviderBaseUrls).map(([provider, baseUrl]) => [provider, typeof baseUrl === "string" ? baseUrl.trim() : ""]).filter(([, baseUrl]) => Boolean(baseUrl))
85048
85102
  );
85049
- const rawProviderBaseUrlSlots = record4.providerBaseUrlSlots && typeof record4.providerBaseUrlSlots === "object" ? record4.providerBaseUrlSlots : {};
85103
+ const rawProviderBaseUrlSlots = record5.providerBaseUrlSlots && typeof record5.providerBaseUrlSlots === "object" ? record5.providerBaseUrlSlots : {};
85050
85104
  const providerBaseUrlSlots = Object.fromEntries(
85051
85105
  Object.entries(rawProviderBaseUrlSlots).map(([provider, value2]) => {
85052
85106
  const slots = Array.isArray(value2) ? value2.map((baseUrl) => typeof baseUrl === "string" ? baseUrl.trim() : "") : [];
85053
85107
  return [provider, slots];
85054
85108
  }).filter(([, slots]) => slots.some(Boolean))
85055
85109
  );
85056
- const storage = normalizeDeviceSecretStorage(record4.storage);
85057
- const hyperliquidSigningKey = typeof record4.hyperliquidSigningKey === "string" ? record4.hyperliquidSigningKey.trim() || void 0 : void 0;
85058
- const rawLocalAi = record4.localAi && typeof record4.localAi === "object" ? record4.localAi : {};
85110
+ const storage = normalizeDeviceSecretStorage(record5.storage);
85111
+ const hyperliquidSigningKey = typeof record5.hyperliquidSigningKey === "string" ? record5.hyperliquidSigningKey.trim() || void 0 : void 0;
85112
+ const rawLocalAi = record5.localAi && typeof record5.localAi === "object" ? record5.localAi : {};
85059
85113
  const localAi = normalizeLocalAiSecrets({
85060
85114
  baseUrl: typeof rawLocalAi.baseUrl === "string" ? rawLocalAi.baseUrl : "",
85061
85115
  modelName: typeof rawLocalAi.modelName === "string" ? rawLocalAi.modelName : "",
85062
85116
  apiKey: typeof rawLocalAi.apiKey === "string" ? rawLocalAi.apiKey : "",
85063
85117
  serverType: rawLocalAi.serverType === "ollama-native" ? "ollama-native" : rawLocalAi.serverType === "openai-compatible" ? "openai-compatible" : void 0
85064
85118
  });
85065
- const rawOpenAiCompatible = record4.openaiCompatible && typeof record4.openaiCompatible === "object" ? record4.openaiCompatible : {};
85119
+ const rawOpenAiCompatible = record5.openaiCompatible && typeof record5.openaiCompatible === "object" ? record5.openaiCompatible : {};
85066
85120
  const openaiCompatible = normalizeOpenAiCompatibleSecrets({
85067
85121
  baseUrl: typeof rawOpenAiCompatible.baseUrl === "string" ? rawOpenAiCompatible.baseUrl : "",
85068
85122
  modelName: typeof rawOpenAiCompatible.modelName === "string" ? rawOpenAiCompatible.modelName : "",
@@ -85312,10 +85366,10 @@ var init_vault = __esm({
85312
85366
  };
85313
85367
  };
85314
85368
  normalizeDeviceSecretStorage = (value) => {
85315
- const record4 = value && typeof value === "object" ? value : {};
85369
+ const record5 = value && typeof value === "object" ? value : {};
85316
85370
  return {
85317
- byok: record4.byok === "device" ? "device" : "server",
85318
- hyperliquid: record4.hyperliquid === "device" ? "device" : "server"
85371
+ byok: record5.byok === "device" ? "device" : "server",
85372
+ hyperliquid: record5.hyperliquid === "device" ? "device" : "server"
85319
85373
  };
85320
85374
  };
85321
85375
  normalizeLocalAiSecrets = (value) => {
@@ -86318,15 +86372,15 @@ var init_runtime_execution = __esm({
86318
86372
  }
86319
86373
  return null;
86320
86374
  }
86321
- const record4 = node;
86322
- const direct = record4.oid ?? record4.orderId ?? record4.order_id;
86375
+ const record5 = node;
86376
+ const direct = record5.oid ?? record5.orderId ?? record5.order_id;
86323
86377
  if (direct != null) {
86324
86378
  const parsed = String(direct).trim();
86325
86379
  if (parsed.length > 0) {
86326
86380
  return parsed;
86327
86381
  }
86328
86382
  }
86329
- for (const child of Object.values(record4)) {
86383
+ for (const child of Object.values(record5)) {
86330
86384
  const found = walk(child);
86331
86385
  if (found) {
86332
86386
  return found;
@@ -86402,19 +86456,19 @@ var init_runtime_execution = __esm({
86402
86456
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
86403
86457
  return [];
86404
86458
  }
86405
- const record4 = entry;
86406
- const orderId = Math.trunc(Number(record4.orderId));
86407
- const triggerPrice = Number(record4.triggerPrice);
86408
- const size = Number(record4.size);
86409
- if (!Number.isSafeInteger(orderId) || orderId <= 0 || !Number.isFinite(triggerPrice) || triggerPrice <= 0 || !Number.isFinite(size) || size <= 0 || typeof record4.isLong !== "boolean") {
86459
+ const record5 = entry;
86460
+ const orderId = Math.trunc(Number(record5.orderId));
86461
+ const triggerPrice = Number(record5.triggerPrice);
86462
+ const size = Number(record5.size);
86463
+ if (!Number.isSafeInteger(orderId) || orderId <= 0 || !Number.isFinite(triggerPrice) || triggerPrice <= 0 || !Number.isFinite(size) || size <= 0 || typeof record5.isLong !== "boolean") {
86410
86464
  return [];
86411
86465
  }
86412
86466
  return [{
86413
86467
  orderId,
86414
86468
  triggerPrice,
86415
86469
  size,
86416
- isLong: record4.isLong,
86417
- positionTpsl: record4.positionTpsl === true
86470
+ isLong: record5.isLong,
86471
+ positionTpsl: record5.positionTpsl === true
86418
86472
  }];
86419
86473
  });
86420
86474
  };
@@ -86440,11 +86494,11 @@ var init_runtime_execution = __esm({
86440
86494
  }
86441
86495
  }
86442
86496
  };
86443
- rememberTrailingStop = (profileId, symbol2, record4) => {
86497
+ rememberTrailingStop = (profileId, symbol2, record5) => {
86444
86498
  const records = readTrackedTrailingStops(profileId, symbol2);
86445
86499
  writeTrackedTrailingStops(profileId, symbol2, [
86446
- ...records.filter((candidate) => candidate.orderId !== record4.orderId),
86447
- record4
86500
+ ...records.filter((candidate) => candidate.orderId !== record5.orderId),
86501
+ record5
86448
86502
  ]);
86449
86503
  };
86450
86504
  protectiveGroupStorageKey = (profileId, symbol2) => `vtx:auto-protective-group:${profileId}:${symbol2}`;
@@ -86472,16 +86526,16 @@ var init_runtime_execution = __esm({
86472
86526
  protectiveGroupReadFailures.add(key);
86473
86527
  return [];
86474
86528
  }
86475
- const record4 = entry;
86476
- const entryOrderId = String(record4.entryOrderId ?? "").trim();
86477
- const storedProfileId = String(record4.profileId ?? "").trim();
86478
- const storedSymbol = String(record4.symbol ?? "").trim().toUpperCase();
86479
- const walletAddress = String(record4.walletAddress ?? "").trim().toLowerCase();
86480
- if (record4.version !== 1 && record4.version !== 2 || storedProfileId !== profileId || storedSymbol !== symbol2.trim().toUpperCase() || !walletAddress || !entryOrderId || typeof record4.isLong !== "boolean" || !Array.isArray(record4.legs)) {
86529
+ const record5 = entry;
86530
+ const entryOrderId = String(record5.entryOrderId ?? "").trim();
86531
+ const storedProfileId = String(record5.profileId ?? "").trim();
86532
+ const storedSymbol = String(record5.symbol ?? "").trim().toUpperCase();
86533
+ const walletAddress = String(record5.walletAddress ?? "").trim().toLowerCase();
86534
+ if (record5.version !== 1 && record5.version !== 2 || storedProfileId !== profileId || storedSymbol !== symbol2.trim().toUpperCase() || !walletAddress || !entryOrderId || typeof record5.isLong !== "boolean" || !Array.isArray(record5.legs)) {
86481
86535
  protectiveGroupReadFailures.add(key);
86482
86536
  return [];
86483
86537
  }
86484
- const legs = record4.legs.flatMap((leg) => {
86538
+ const legs = record5.legs.flatMap((leg) => {
86485
86539
  if (leg == null || typeof leg !== "object" || Array.isArray(leg)) {
86486
86540
  protectiveGroupReadFailures.add(key);
86487
86541
  return [];
@@ -86531,7 +86585,7 @@ var init_runtime_execution = __esm({
86531
86585
  ...replacement ? { replacement } : {}
86532
86586
  }];
86533
86587
  });
86534
- const pendingRecord = record4.pendingEntry;
86588
+ const pendingRecord = record5.pendingEntry;
86535
86589
  let pendingEntry;
86536
86590
  if (pendingRecord != null) {
86537
86591
  if (pendingRecord == null || typeof pendingRecord !== "object" || Array.isArray(pendingRecord)) {
@@ -86569,7 +86623,7 @@ var init_runtime_execution = __esm({
86569
86623
  }
86570
86624
  };
86571
86625
  }
86572
- const attachmentRecord = record4.attachmentJournal;
86626
+ const attachmentRecord = record5.attachmentJournal;
86573
86627
  let attachmentJournal;
86574
86628
  if (attachmentRecord != null) {
86575
86629
  if (attachmentRecord == null || typeof attachmentRecord !== "object" || Array.isArray(attachmentRecord)) {
@@ -86628,8 +86682,8 @@ var init_runtime_execution = __esm({
86628
86682
  symbol: storedSymbol,
86629
86683
  walletAddress,
86630
86684
  entryOrderId,
86631
- isLong: record4.isLong,
86632
- cleanupRequired: record4.cleanupRequired === true,
86685
+ isLong: record5.isLong,
86686
+ cleanupRequired: record5.cleanupRequired === true,
86633
86687
  legs,
86634
86688
  ...pendingEntry ? { pendingEntry } : {},
86635
86689
  ...attachmentJournal ? { attachmentJournal } : {}
@@ -86909,11 +86963,11 @@ var init_runtime_execution = __esm({
86909
86963
  writeTrackedTrailingStops(
86910
86964
  profileId,
86911
86965
  symbol2,
86912
- readTrackedTrailingStops(profileId, symbol2).filter((record4) => record4.orderId !== orderId)
86966
+ readTrackedTrailingStops(profileId, symbol2).filter((record5) => record5.orderId !== orderId)
86913
86967
  );
86914
86968
  };
86915
86969
  replaceTrackedTrailingStop = (profileId, symbol2, previousOrderId, replacement) => {
86916
- const retained = readTrackedTrailingStops(profileId, symbol2).filter((record4) => record4.orderId !== previousOrderId);
86970
+ const retained = readTrackedTrailingStops(profileId, symbol2).filter((record5) => record5.orderId !== previousOrderId);
86917
86971
  writeTrackedTrailingStops(
86918
86972
  profileId,
86919
86973
  symbol2,
@@ -89698,49 +89752,49 @@ var init_runtime_execution = __esm({
89698
89752
  }
89699
89753
  liveOrders = fetchedOrders;
89700
89754
  } catch (error48) {
89701
- return tracked.map((record4) => ({
89702
- order_id: String(record4.orderId),
89755
+ return tracked.map((record5) => ({
89756
+ order_id: String(record5.orderId),
89703
89757
  symbol: symbol2,
89704
89758
  action: "AUTO_TRAILING_SL",
89705
89759
  status: "failed",
89706
89760
  execution_metadata: {
89707
- trigger_price: record4.triggerPrice,
89761
+ trigger_price: record5.triggerPrice,
89708
89762
  error: `Unable to verify the tracked exchange stop: ${error48 instanceof Error ? error48.message : String(error48)}`
89709
89763
  }
89710
89764
  }));
89711
89765
  }
89712
89766
  const eligible = [];
89713
89767
  const retained = [];
89714
- for (const record4 of tracked) {
89715
- if (record4.isLong !== isLong) {
89768
+ for (const record5 of tracked) {
89769
+ if (record5.isLong !== isLong) {
89716
89770
  continue;
89717
89771
  }
89718
- const liveOrder = liveOrders.find((order) => order.oid === record4.orderId);
89772
+ const liveOrder = liveOrders.find((order) => order.oid === record5.orderId);
89719
89773
  if (!liveOrder) {
89720
- retained.push(record4);
89774
+ retained.push(record5);
89721
89775
  continue;
89722
89776
  }
89723
89777
  const triggerPrice = Number(liveOrder.trigger_px);
89724
89778
  const size = Number(liveOrder.sz);
89725
89779
  const liveSide = String(liveOrder.side).trim().toLowerCase();
89726
- const isTrustedProtectiveOrder = String(liveOrder.coin).trim().toUpperCase() === symbol2.trim().toUpperCase() && (isLong ? liveSide === "a" || liveSide === "sell" : liveSide === "b" || liveSide === "buy") && liveOrder.reduce_only && liveOrder.is_trigger && liveOrder.trigger_kind === "sl" && liveOrder.is_position_tpsl === record4.positionTpsl && Number.isFinite(size) && size > 0 && Number.isFinite(triggerPrice) && triggerPrice > 0;
89727
- if (isTrustedProtectiveOrder && triggerPrice === record4.triggerPrice && size === record4.size) {
89728
- eligible.push(record4);
89780
+ const isTrustedProtectiveOrder = String(liveOrder.coin).trim().toUpperCase() === symbol2.trim().toUpperCase() && (isLong ? liveSide === "a" || liveSide === "sell" : liveSide === "b" || liveSide === "buy") && liveOrder.reduce_only && liveOrder.is_trigger && liveOrder.trigger_kind === "sl" && liveOrder.is_position_tpsl === record5.positionTpsl && Number.isFinite(size) && size > 0 && Number.isFinite(triggerPrice) && triggerPrice > 0;
89781
+ if (isTrustedProtectiveOrder && triggerPrice === record5.triggerPrice && size === record5.size) {
89782
+ eligible.push(record5);
89729
89783
  } else {
89730
- retained.push(record4);
89784
+ retained.push(record5);
89731
89785
  }
89732
89786
  }
89733
89787
  const reports = [];
89734
89788
  const updated = [...retained];
89735
89789
  let remainingExposure = Math.abs(currentPositionSize);
89736
- for (const record4 of eligible) {
89790
+ for (const record5 of eligible) {
89737
89791
  const effectiveSize = roundAssetSize(
89738
- Math.min(record4.size, remainingExposure),
89792
+ Math.min(record5.size, remainingExposure),
89739
89793
  request.executionContext.sizeDecimals
89740
89794
  );
89741
89795
  remainingExposure = Math.max(0, remainingExposure - effectiveSize);
89742
89796
  if (!Number.isFinite(effectiveSize) || effectiveSize <= 0) {
89743
- const trackedLeg = readClientProtectiveGroups(profileId, symbol2).flatMap((group) => group.legs).find((leg) => leg.orderId === record4.orderId);
89797
+ const trackedLeg = readClientProtectiveGroups(profileId, symbol2).flatMap((group) => group.legs).find((leg) => leg.orderId === record5.orderId);
89744
89798
  if (trackedLeg) {
89745
89799
  const report = await cancelClientProtectiveLeg(
89746
89800
  request,
@@ -89750,19 +89804,19 @@ var init_runtime_execution = __esm({
89750
89804
  );
89751
89805
  reports.push(report);
89752
89806
  if (report.status === "executed") {
89753
- replaceProtectiveLeg(profileId, symbol2, record4.orderId, null);
89807
+ replaceProtectiveLeg(profileId, symbol2, record5.orderId, null);
89754
89808
  } else {
89755
- updated.push(record4);
89809
+ updated.push(record5);
89756
89810
  }
89757
89811
  } else {
89758
- updated.push(record4);
89812
+ updated.push(record5);
89759
89813
  reports.push({
89760
- order_id: String(record4.orderId),
89814
+ order_id: String(record5.orderId),
89761
89815
  symbol: symbol2,
89762
89816
  action: "AUTO_TRAILING_SL",
89763
89817
  status: "failed",
89764
89818
  execution_metadata: {
89765
- trigger_price: record4.triggerPrice,
89819
+ trigger_price: record5.triggerPrice,
89766
89820
  reason_code: "protective_order_shape_unresolved"
89767
89821
  }
89768
89822
  });
@@ -89780,42 +89834,42 @@ var init_runtime_execution = __esm({
89780
89834
  rawCandidatePrice,
89781
89835
  request.executionContext.sizeDecimals
89782
89836
  )) : 0;
89783
- const tightens = candidatePrice > 0 && (isLong ? candidatePrice > record4.triggerPrice : candidatePrice < record4.triggerPrice);
89837
+ const tightens = candidatePrice > 0 && (isLong ? candidatePrice > record5.triggerPrice : candidatePrice < record5.triggerPrice);
89784
89838
  const canonicalRecordSize = roundAssetSize(
89785
- record4.size,
89839
+ record5.size,
89786
89840
  request.executionContext.sizeDecimals
89787
89841
  );
89788
89842
  const resizes = effectiveSize !== canonicalRecordSize;
89789
89843
  if (!tightens && !resizes) {
89790
- updated.push(record4);
89844
+ updated.push(record5);
89791
89845
  continue;
89792
89846
  }
89793
- const replacementTriggerPrice = tightens ? candidatePrice : record4.triggerPrice;
89847
+ const replacementTriggerPrice = tightens ? candidatePrice : record5.triggerPrice;
89794
89848
  if (!canPersistClientProtectiveGroups(profileId, symbol2)) {
89795
- updated.push(record4);
89849
+ updated.push(record5);
89796
89850
  reports.push({
89797
- order_id: String(record4.orderId),
89851
+ order_id: String(record5.orderId),
89798
89852
  symbol: symbol2,
89799
89853
  action: "AUTO_TRAILING_SL",
89800
89854
  status: "failed",
89801
89855
  execution_metadata: {
89802
89856
  trigger_price: replacementTriggerPrice,
89803
- previous_trigger_price: record4.triggerPrice,
89857
+ previous_trigger_price: record5.triggerPrice,
89804
89858
  reason_code: "protective_lifecycle_storage_unavailable"
89805
89859
  }
89806
89860
  });
89807
89861
  continue;
89808
89862
  }
89809
89863
  const currentGroups = readFreshClientProtectiveGroups(profileId, symbol2);
89810
- const sourceGroups = currentGroups.filter((group) => group.legs.some((leg) => leg.orderId === record4.orderId));
89864
+ const sourceGroups = currentGroups.filter((group) => group.legs.some((leg) => leg.orderId === record5.orderId));
89811
89865
  const sourceGroup = sourceGroups.length === 1 ? sourceGroups[0] : null;
89812
- const previousLeg = sourceGroup?.legs.filter((leg) => leg.orderId === record4.orderId);
89866
+ const previousLeg = sourceGroup?.legs.filter((leg) => leg.orderId === record5.orderId);
89813
89867
  const replacementMutationId = createRuntimeId().toLowerCase();
89814
89868
  const replacementClientOrderId = `0x${replacementMutationId.replaceAll("-", "")}`;
89815
89869
  const replacementIntent = {
89816
89870
  mutationId: replacementMutationId,
89817
89871
  clientOrderId: replacementClientOrderId,
89818
- previousOrderId: record4.orderId,
89872
+ previousOrderId: record5.orderId,
89819
89873
  triggerPrice: replacementTriggerPrice,
89820
89874
  size: effectiveSize
89821
89875
  };
@@ -89828,15 +89882,15 @@ var init_runtime_execution = __esm({
89828
89882
  replacement: replacementIntent
89829
89883
  });
89830
89884
  if (reservation == null) {
89831
- updated.push(record4);
89885
+ updated.push(record5);
89832
89886
  reports.push({
89833
- order_id: String(record4.orderId),
89887
+ order_id: String(record5.orderId),
89834
89888
  symbol: symbol2,
89835
89889
  action: "AUTO_TRAILING_SL",
89836
89890
  status: "failed",
89837
89891
  execution_metadata: {
89838
89892
  trigger_price: replacementTriggerPrice,
89839
- previous_trigger_price: record4.triggerPrice,
89893
+ previous_trigger_price: record5.triggerPrice,
89840
89894
  reason_code: "protective_replacement_reservation_failed"
89841
89895
  }
89842
89896
  });
@@ -89869,7 +89923,7 @@ var init_runtime_execution = __esm({
89869
89923
  replacementDispatchBoundaryCompleted = true;
89870
89924
  },
89871
89925
  symbol: symbol2,
89872
- orderId: record4.orderId,
89926
+ orderId: record5.orderId,
89873
89927
  side: isLong ? "sell" : "buy",
89874
89928
  size: effectiveSize,
89875
89929
  limitPrice: replacementTriggerPrice,
@@ -89884,7 +89938,7 @@ var init_runtime_execution = __esm({
89884
89938
  const modificationAcknowledgement = extractCanonicalHyperliquidOrderStateAcknowledgement(modifyResponse);
89885
89939
  const replacementOrderId = Number(modificationAcknowledgement?.orderId);
89886
89940
  if (!Number.isSafeInteger(replacementOrderId) || replacementOrderId <= 0) {
89887
- updated.push(record4);
89941
+ updated.push(record5);
89888
89942
  reports.push({
89889
89943
  order_id: null,
89890
89944
  symbol: symbol2,
@@ -89892,7 +89946,7 @@ var init_runtime_execution = __esm({
89892
89946
  status: "failed",
89893
89947
  execution_metadata: {
89894
89948
  trigger_price: replacementTriggerPrice,
89895
- previous_trigger_price: record4.triggerPrice,
89949
+ previous_trigger_price: record5.triggerPrice,
89896
89950
  error: "Trailing stop replacement did not return a trackable order id."
89897
89951
  }
89898
89952
  });
@@ -89942,11 +89996,11 @@ var init_runtime_execution = __esm({
89942
89996
  triggerPrice: replacementTriggerPrice,
89943
89997
  size: effectiveSize,
89944
89998
  isLong,
89945
- positionTpsl: record4.positionTpsl
89999
+ positionTpsl: record5.positionTpsl
89946
90000
  };
89947
90001
  updated.push(replacementTrailingStop);
89948
90002
  } else {
89949
- removeTrackedTrailingStop(profileId, symbol2, record4.orderId);
90003
+ removeTrackedTrailingStop(profileId, symbol2, record5.orderId);
89950
90004
  reports.push({
89951
90005
  order_id: String(replacementOrderId),
89952
90006
  symbol: symbol2,
@@ -89966,8 +90020,8 @@ var init_runtime_execution = __esm({
89966
90020
  status: "executed",
89967
90021
  execution_metadata: {
89968
90022
  trigger_price: replacementTriggerPrice,
89969
- previous_trigger_price: record4.triggerPrice,
89970
- previous_order_id: record4.orderId
90023
+ previous_trigger_price: record5.triggerPrice,
90024
+ previous_order_id: record5.orderId
89971
90025
  }
89972
90026
  });
89973
90027
  } catch (error48) {
@@ -89983,16 +90037,16 @@ var init_runtime_execution = __esm({
89983
90037
  throw error48;
89984
90038
  }
89985
90039
  if (!canonicalCleanupRetained) {
89986
- updated.push(record4);
90040
+ updated.push(record5);
89987
90041
  }
89988
90042
  reports.push({
89989
- order_id: String(record4.orderId),
90043
+ order_id: String(record5.orderId),
89990
90044
  symbol: symbol2,
89991
90045
  action: "AUTO_TRAILING_SL",
89992
90046
  status: "failed",
89993
90047
  execution_metadata: {
89994
90048
  trigger_price: candidatePrice,
89995
- previous_trigger_price: record4.triggerPrice,
90049
+ previous_trigger_price: record5.triggerPrice,
89996
90050
  error: error48 instanceof Error ? error48.message : String(error48)
89997
90051
  }
89998
90052
  });
@@ -91332,6 +91386,54 @@ var init_runtime_execution = __esm({
91332
91386
  }
91333
91387
  });
91334
91388
 
91389
+ // lib/runtime/provider-observability.ts
91390
+ var record4, identifier, count3, normalizeProviderDiagnostics;
91391
+ var init_provider_observability = __esm({
91392
+ "lib/runtime/provider-observability.ts"() {
91393
+ "use strict";
91394
+ init_define_VTX_EXO_POLICY();
91395
+ init_define_VTX_GROK_POLICY();
91396
+ init_define_VTX_PI_MODEL_POLICY();
91397
+ record4 = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
91398
+ identifier = (v) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}$/.test(v) ? v : void 0;
91399
+ count3 = (v) => {
91400
+ if (typeof v !== "number" && (typeof v !== "string" || !v.trim())) return void 0;
91401
+ const n2 = Number(v);
91402
+ return Number.isFinite(n2) && n2 >= 0 && n2 <= Number.MAX_SAFE_INTEGER ? n2 : void 0;
91403
+ };
91404
+ normalizeProviderDiagnostics = (value) => {
91405
+ const raw = record4(value);
91406
+ const result2 = {};
91407
+ for (const key of ["retry_after_seconds", "retry_delay_seconds"]) {
91408
+ const n2 = count3(raw[key]);
91409
+ if (n2 !== void 0) result2[key] = n2;
91410
+ }
91411
+ if (typeof raw.credential_ref === "string" && /^[a-f0-9]{64}$/.test(raw.credential_ref)) result2.credential_ref = raw.credential_ref;
91412
+ if (raw.execution_mode === "client" || raw.execution_mode === "server") result2.execution_mode = raw.execution_mode;
91413
+ if (typeof raw.quota_project_ref === "string" && /^[a-f0-9]{64}$/.test(raw.quota_project_ref) && raw.quota_project_source === "provider_quota_subject") {
91414
+ result2.quota_project_ref = raw.quota_project_ref;
91415
+ result2.quota_project_source = "provider_quota_subject";
91416
+ }
91417
+ if (Array.isArray(raw.quota_violations)) {
91418
+ const violations = raw.quota_violations.slice(0, 16).map((item) => {
91419
+ const v = record4(item);
91420
+ const out = {};
91421
+ const metric = identifier(v.metric), id2 = identifier(v.id), value2 = count3(v.value);
91422
+ if (metric) out.metric = metric;
91423
+ if (id2) out.id = id2;
91424
+ if (value2 !== void 0) out.value = value2;
91425
+ const dims = record4(v.dimensions);
91426
+ const model = identifier(dims.model), location = identifier(dims.location);
91427
+ if (model || location) out.dimensions = { ...model ? { model } : {}, ...location ? { location } : {} };
91428
+ return out;
91429
+ }).filter((v) => Object.keys(v).length > 0);
91430
+ if (violations.length) result2.quota_violations = violations;
91431
+ }
91432
+ return result2;
91433
+ };
91434
+ }
91435
+ });
91436
+
91335
91437
  // lib/runtime/usage-contract.ts
91336
91438
  var PROMPT_TOKEN_KEYS, COMPLETION_TOKEN_KEYS, TOTAL_TOKEN_KEYS, REASONING_TOKEN_KEYS, CACHED_INPUT_TOKEN_KEYS, CACHE_CREATION_INPUT_TOKEN_KEYS, TOOL_USE_TOKEN_KEYS, AUDIO_INPUT_TOKEN_KEYS, AUDIO_OUTPUT_TOKEN_KEYS, BILLABLE_INPUT_TOKEN_KEYS, BILLABLE_OUTPUT_TOKEN_KEYS, BILLABLE_CACHED_INPUT_TOKEN_KEYS, BILLABLE_CACHE_CREATION_INPUT_TOKEN_KEYS, BILLABLE_TOOL_USE_TOKEN_KEYS, MAX_RUNTIME_USAGE_COUNT, PROVIDER_USAGE_DETAIL_KEYS, PROVIDER_USAGE_DETAIL_COUNT_KEY_PATTERN, PROVIDER_USAGE_DETAIL_TEXT_KEYS, MAX_PROVIDER_USAGE_DETAIL_ITEMS, isRecord, coerceOptionalRuntimeUsageCount, readOptionalRuntimeUsageCount, readNestedUsageDetailCount, sanitizeProviderUsageDetail, normalizeUsageProvenance, normalizeRuntimeUsageDetails;
91337
91439
  var init_usage_contract = __esm({
@@ -91437,8 +91539,8 @@ var init_usage_contract = __esm({
91437
91539
  continue;
91438
91540
  }
91439
91541
  if (PROVIDER_USAGE_DETAIL_COUNT_KEY_PATTERN.test(key)) {
91440
- const count3 = coerceOptionalRuntimeUsageCount(rawValue);
91441
- if (count3 !== null) result2[key] = count3;
91542
+ const count4 = coerceOptionalRuntimeUsageCount(rawValue);
91543
+ if (count4 !== null) result2[key] = count4;
91442
91544
  }
91443
91545
  }
91444
91546
  return result2;
@@ -91650,6 +91752,7 @@ var init_inference_observability = __esm({
91650
91752
  init_define_VTX_EXO_POLICY();
91651
91753
  init_define_VTX_GROK_POLICY();
91652
91754
  init_define_VTX_PI_MODEL_POLICY();
91755
+ init_provider_observability();
91653
91756
  init_usage_contract();
91654
91757
  init_reasoning_observability();
91655
91758
  AI_INVOCATION_CONTRACT_VERSION = 2;
@@ -91791,6 +91894,9 @@ var init_inference_observability = __esm({
91791
91894
  const useCase = enumValue(source.use_case, USE_CASES, "trader");
91792
91895
  const role = enumValue(source.role, ROLES_BY_USE_CASE[useCase], DEFAULT_ROLE[useCase]);
91793
91896
  const reasoningContent = safeText(source.reasoning_content);
91897
+ const providerStatus = safeNonNegativeInt(source.provider_status_code);
91898
+ const requestTokensSource = source.request_input_tokens_source === "estimated_chars_v1" || source.request_input_tokens_source === "provider_count" ? source.request_input_tokens_source : null;
91899
+ const requestTokens = requestTokensSource ? safeNonNegativeInt(source.request_input_tokens) : null;
91794
91900
  const traceStatus = enumValue(
91795
91901
  source.reasoning_trace_status,
91796
91902
  TRACE_STATUSES,
@@ -91852,7 +91958,10 @@ var init_inference_observability = __esm({
91852
91958
  used_for_final_decision: source.used_for_final_decision === true,
91853
91959
  failure_category: safeCode3(source.failure_category),
91854
91960
  failure_code: safeCode3(source.failure_code),
91855
- provider_status_code: safeNonNegativeInt(source.provider_status_code),
91961
+ provider_status_code: providerStatus !== null && providerStatus >= 100 && providerStatus <= 599 ? providerStatus : null,
91962
+ request_input_tokens: requestTokens,
91963
+ request_input_tokens_source: requestTokens !== null ? requestTokensSource : null,
91964
+ provider_diagnostics: normalizeProviderDiagnostics(source.provider_diagnostics),
91856
91965
  retryable: typeof source.retryable === "boolean" ? source.retryable : null,
91857
91966
  fallback_from_provider: safeIdentifier(source.fallback_from_provider),
91858
91967
  fallback_from_model: safeIdentifier(source.fallback_from_model),
@@ -91991,6 +92100,7 @@ function buildClientExchangeSnapshot(input) {
91991
92100
  mark_price: input.accountState.availableToTrade.mark_price ?? null,
91992
92101
  account_summary: {
91993
92102
  account_value: accountSummary.account_value ?? null,
92103
+ ...accountSummary.perp_dex_accounts == null ? {} : { perp_dex_accounts: accountSummary.perp_dex_accounts },
91994
92104
  total_margin_used: accountSummary.total_margin_used ?? null,
91995
92105
  available_margin: accountSummary.available_margin ?? null,
91996
92106
  withdrawable: accountSummary.withdrawable ?? null,