@vtxmacro/cli 2026.10.22 → 2026.10.24

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
@@ -113,7 +113,7 @@ var init_routing = __esm({
113
113
  var agent_cli_release_default;
114
114
  var init_agent_cli_release = __esm({
115
115
  "agent-cli-release.json"() {
116
- agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.22", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
116
+ agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.24", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
117
117
  }
118
118
  });
119
119
 
@@ -1273,6 +1273,10 @@ var init_runtime_policy_generated = __esm({
1273
1273
  recovery_queue_wait_seconds: 10,
1274
1274
  recovery_quiet_seconds: 30
1275
1275
  },
1276
+ acknowledgement_lookup: {
1277
+ window_milliseconds: 1e4,
1278
+ poll_milliseconds: 1e3
1279
+ },
1276
1280
  http: {
1277
1281
  exchange: {
1278
1282
  request_timeout_seconds: 10,
@@ -3163,13 +3167,13 @@ async function replaceAtomicInferencePrivateFile(temporaryPath, destinationPath,
3163
3167
  const sleep4 = options.sleep ?? ((milliseconds) => new Promise((resolve14) => setTimeout(resolve14, milliseconds)));
3164
3168
  const maxAttempts = Math.max(1, options.maxAttempts ?? HOST_CORE_POLICY.private_file_replace_attempts);
3165
3169
  const retryDelayMs = Math.max(0, options.retryDelayMs ?? HOST_CORE_POLICY.private_file_replace_retry_delay_ms);
3166
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
3170
+ for (let attempt2 = 0; attempt2 < maxAttempts; attempt2 += 1) {
3167
3171
  try {
3168
3172
  await renameFile(temporaryPath, destinationPath);
3169
3173
  return;
3170
3174
  } catch (error48) {
3171
3175
  const code = String(error48.code ?? "");
3172
- if (platform !== "win32" || !WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES.has(code) || attempt === maxAttempts - 1) {
3176
+ if (platform !== "win32" || !WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES.has(code) || attempt2 === maxAttempts - 1) {
3173
3177
  throw error48;
3174
3178
  }
3175
3179
  await sleep4(retryDelayMs);
@@ -4203,11 +4207,11 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
4203
4207
  const directory2 = dirname2(lockPath);
4204
4208
  const prefix = `${basename(lockPath)}.reclaim-ballot.`;
4205
4209
  try {
4206
- for (let attempt = 0; attempt < PROCESS_LOCK_GUARD_ELECTION_ATTEMPTS; attempt += 1) {
4207
- if (attempt > 0) {
4210
+ for (let attempt2 = 0; attempt2 < PROCESS_LOCK_GUARD_ELECTION_ATTEMPTS; attempt2 += 1) {
4211
+ if (attempt2 > 0) {
4208
4212
  await new Promise((resolvePromise) => setTimeout(
4209
4213
  resolvePromise,
4210
- Math.floor(Math.random() * PROCESS_LOCK_GUARD_ELECTION_BACKOFF_MS * BACKOFF_GROWTH_FACTOR ** Math.min(attempt, HOST_CORE_POLICY.process_lock_guard_election_backoff_exponent_max))
4214
+ Math.floor(Math.random() * PROCESS_LOCK_GUARD_ELECTION_BACKOFF_MS * BACKOFF_GROWTH_FACTOR ** Math.min(attempt2, HOST_CORE_POLICY.process_lock_guard_election_backoff_exponent_max))
4211
4215
  ));
4212
4216
  let current;
4213
4217
  try {
@@ -4261,7 +4265,7 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
4261
4265
  acquireProcessLockReclaimGuard = async (lockPath, ownerRecord, probes) => {
4262
4266
  const guardPath = `${lockPath}.reclaim`;
4263
4267
  const guardToken = randomBytes(INFERENCE_HOST_RANDOM_BYTES.LOCK_TOKEN).toString("base64url");
4264
- for (let attempt = 0; attempt < INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES; attempt += 1) {
4268
+ for (let attempt2 = 0; attempt2 < INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES; attempt2 += 1) {
4265
4269
  const handle = await openExclusiveProcessLockFile(guardPath);
4266
4270
  if (handle) {
4267
4271
  try {
@@ -4311,7 +4315,7 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
4311
4315
  }
4312
4316
  };
4313
4317
  }
4314
- if (attempt > 0) break;
4318
+ if (attempt2 > 0) break;
4315
4319
  const inspection = await inspectProcessLockFile(guardPath, PROCESS_LOCK_GUARD_LABEL, probes);
4316
4320
  if (inspection.state === "busy") break;
4317
4321
  if (inspection.state === "stale") {
@@ -5248,7 +5252,7 @@ var init_updater = __esm({
5248
5252
  const paths = resolveCliUpdatePaths(env);
5249
5253
  const now = dependencies.now ?? (() => /* @__PURE__ */ new Date());
5250
5254
  const current = dependencies.currentVersion ?? agent_cli_release_default.package_version;
5251
- for (let attempt = 0; attempt < runtime_policy_generated_default.agent_cli.update_plan_max_attempts; attempt += 1) {
5255
+ for (let attempt2 = 0; attempt2 < runtime_policy_generated_default.agent_cli.update_plan_max_attempts; attempt2 += 1) {
5252
5256
  const plan = await planCliEntryUpdate(entry, argv2, env, script, dependencies);
5253
5257
  if (plan.kind === "refuse") {
5254
5258
  stderr.write(`${plan.message}
@@ -21093,6 +21097,10 @@ var init_runtime_policy_generated2 = __esm({
21093
21097
  recovery_queue_wait_seconds: 10,
21094
21098
  recovery_quiet_seconds: 30
21095
21099
  },
21100
+ acknowledgement_lookup: {
21101
+ window_milliseconds: 1e4,
21102
+ poll_milliseconds: 1e3
21103
+ },
21096
21104
  http: {
21097
21105
  exchange: {
21098
21106
  request_timeout_seconds: 10,
@@ -25968,25 +25976,25 @@ var init_mcp_client = __esm({
25968
25976
  structuredContent: external_exports.unknown()
25969
25977
  }).passthrough().parse(rawResult);
25970
25978
  if (callResult.isError === true) {
25971
- const errorText = (callResult.content ?? []).filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n");
25979
+ const errorText2 = (callResult.content ?? []).filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n");
25972
25980
  const structuredPublicToolError = structuredPublicToolErrorSchema.safeParse(
25973
25981
  callResult.structuredContent
25974
25982
  );
25975
25983
  const structuredDocument = callResult.structuredContent !== null && typeof callResult.structuredContent === "object" && !Array.isArray(callResult.structuredContent) ? callResult.structuredContent : null;
25976
25984
  const hasStructuredPublicToolErrorMarker = structuredDocument?.schema_version === "vtx_insights_tool_error_v1";
25977
- const publicToolError = structuredPublicToolError.success ? structuredPublicToolError.data : hasStructuredPublicToolErrorMarker ? null : parsePublicToolError(errorText);
25978
- const hasPublicToolErrorMarker = hasStructuredPublicToolErrorMarker || errorText.includes(PUBLIC_TOOL_ERROR_PREFIX);
25979
- const completionEvidenceExpired = name === "inference.job.complete" && (publicToolError ? publicToolError.failure_code === "completion_evidence_expired" && publicToolError.phase === "validation" && publicToolError.retryable === false && publicToolError.terminal_before_execution === true : !hasPublicToolErrorMarker && errorText.includes("External inference completion evidence window expired"));
25985
+ const publicToolError = structuredPublicToolError.success ? structuredPublicToolError.data : hasStructuredPublicToolErrorMarker ? null : parsePublicToolError(errorText2);
25986
+ const hasPublicToolErrorMarker = hasStructuredPublicToolErrorMarker || errorText2.includes(PUBLIC_TOOL_ERROR_PREFIX);
25987
+ const completionEvidenceExpired = name === "inference.job.complete" && (publicToolError ? publicToolError.failure_code === "completion_evidence_expired" && publicToolError.phase === "validation" && publicToolError.retryable === false && publicToolError.terminal_before_execution === true : !hasPublicToolErrorMarker && errorText2.includes("External inference completion evidence window expired"));
25980
25988
  const hostNotClaimable = name === "inference.job.claim" && publicToolError?.failure_code === "host_not_claimable" && publicToolError.phase === "admission" && publicToolError.retryable === true && publicToolError.terminal_before_execution === true;
25981
- const definitivelyNotApplied = (name === "inference.agent.decision.submit" || name === "inference.agent.data.call") && publicToolError?.phase === "validation" && publicToolError.retryable === false && publicToolError.terminal_before_execution === true && (name === "inference.agent.decision.submit" && publicToolError.failure_code === "agent_decision_schema_invalid" || publicToolError.failure_code === "invalid_arguments" && publicToolError.reason_code === "schema_validation") || (name === "inference.host.register" || name === "inference.host.advertise") && (errorText.includes("Advertisement time is outside the allowed clock skew.") || errorText.includes("Advertisement is already expired.")) || (name === "inference.agent.next" || name === "inference.agent.heartbeat") && (errorText.includes("Advertisement time is outside the allowed clock skew.") || errorText.includes("Advertisement is already expired.") || errorText.includes("Heartbeat time is outside the allowed clock skew.")) || name === "inference.host.heartbeat" && errorText.includes("Heartbeat time is outside the allowed clock skew.") || name === "inference.job.claim" && (errorText.includes(
25989
+ const definitivelyNotApplied = (name === "inference.agent.decision.submit" || name === "inference.agent.data.call") && publicToolError?.phase === "validation" && publicToolError.retryable === false && publicToolError.terminal_before_execution === true && (name === "inference.agent.decision.submit" && publicToolError.failure_code === "agent_decision_schema_invalid" || publicToolError.failure_code === "invalid_arguments" && publicToolError.reason_code === "schema_validation") || (name === "inference.host.register" || name === "inference.host.advertise") && (errorText2.includes("Advertisement time is outside the allowed clock skew.") || errorText2.includes("Advertisement is already expired.")) || (name === "inference.agent.next" || name === "inference.agent.heartbeat") && (errorText2.includes("Advertisement time is outside the allowed clock skew.") || errorText2.includes("Advertisement is already expired.") || errorText2.includes("Heartbeat time is outside the allowed clock skew.")) || name === "inference.host.heartbeat" && errorText2.includes("Heartbeat time is outside the allowed clock skew.") || name === "inference.job.claim" && (errorText2.includes(
25982
25990
  "External inference claim request was not applied before its generation became stale"
25983
- ) || errorText.includes("External inference host advertisement is expired or superseded")) || name === "inference.job.complete" && completionEvidenceExpired;
25984
- const retryableInfrastructureRejection = EXTERNAL_INFERENCE_AUTOMATED_HOST_TOOLS.includes(name) && (errorText.includes("External inference polling is at its configured concurrency limit") || errorText.includes("The Insights action reached the response timeout") || errorText.includes("Insights capability failed without exposing private runtime details"));
25985
- const retryableClaimRejection = name === "inference.job.claim" && !definitivelyNotApplied && (retryableInfrastructureRejection || hostNotClaimable || errorText.includes("External inference host is not live enough to claim work") || errorText.includes("External inference host request generation is stale") || errorText.includes("External inference claim runtime fence is stale"));
25991
+ ) || errorText2.includes("External inference host advertisement is expired or superseded")) || name === "inference.job.complete" && completionEvidenceExpired;
25992
+ const retryableInfrastructureRejection = EXTERNAL_INFERENCE_AUTOMATED_HOST_TOOLS.includes(name) && (errorText2.includes("External inference polling is at its configured concurrency limit") || errorText2.includes("The Insights action reached the response timeout") || errorText2.includes("Insights capability failed without exposing private runtime details"));
25993
+ const retryableClaimRejection = name === "inference.job.claim" && !definitivelyNotApplied && (retryableInfrastructureRejection || hostNotClaimable || errorText2.includes("External inference host is not live enough to claim work") || errorText2.includes("External inference host request generation is stale") || errorText2.includes("External inference claim runtime fence is stale"));
25986
25994
  const retryableHeartbeatClockSkew = name === "inference.host.heartbeat" && definitivelyNotApplied;
25987
25995
  const retryableAdvertisementClockSkew = (name === "inference.host.register" || name === "inference.host.advertise") && definitivelyNotApplied;
25988
- const staleHostHeartbeatGeneration = name === "inference.host.heartbeat" && errorText.includes("Heartbeat generations do not match the current host authority.");
25989
- const obsoleteClaimReplay = name === "inference.job.claim" && errorText.includes(
25996
+ const staleHostHeartbeatGeneration = name === "inference.host.heartbeat" && errorText2.includes("Heartbeat generations do not match the current host authority.");
25997
+ const obsoleteClaimReplay = name === "inference.job.claim" && errorText2.includes(
25990
25998
  "External inference claim replay is no longer dispatchable"
25991
25999
  );
25992
26000
  throw new ExternalInferenceMcpError(
@@ -33318,13 +33326,13 @@ child.once('close', async (code, signal) => {
33318
33326
  const sleep4 = options.sleep ?? ((milliseconds) => new Promise((resolve14) => setTimeout(resolve14, milliseconds)));
33319
33327
  const maxAttempts = Math.max(1, options.maxAttempts ?? HOST_RUNTIME_POLICY.codex_guardian_receipt_replace_attempts);
33320
33328
  const retryDelayMs = Math.max(0, options.retryDelayMs ?? HOST_RUNTIME_POLICY.codex_guardian_receipt_replace_retry_ms);
33321
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
33329
+ for (let attempt2 = 0; attempt2 < maxAttempts; attempt2 += 1) {
33322
33330
  try {
33323
33331
  await renameFile(temporaryPath, receiptPath);
33324
33332
  return;
33325
33333
  } catch (error48) {
33326
33334
  const code = String(error48.code ?? "");
33327
- if (platform !== "win32" || !WINDOWS_RECEIPT_REPLACE_ERROR_CODES.has(code) || attempt === maxAttempts - 1) {
33335
+ if (platform !== "win32" || !WINDOWS_RECEIPT_REPLACE_ERROR_CODES.has(code) || attempt2 === maxAttempts - 1) {
33328
33336
  throw error48;
33329
33337
  }
33330
33338
  try {
@@ -35649,14 +35657,14 @@ var init_runner = __esm({
35649
35657
  terminal_pending: 0
35650
35658
  };
35651
35659
  const terminalOperations = [];
35652
- for (const attempt of Object.values(receipt.attempts)) {
35653
- phaseCounts[attempt.phase] += 1;
35654
- const terminal = attempt.terminal_request;
35660
+ for (const attempt2 of Object.values(receipt.attempts)) {
35661
+ phaseCounts[attempt2.phase] += 1;
35662
+ const terminal = attempt2.terminal_request;
35655
35663
  if (!terminal) continue;
35656
35664
  const failed = terminal.schema_version === "external_inference_job_fail_v1";
35657
35665
  terminalOperations.push({
35658
- job_id: attempt.job_id,
35659
- attempt_id: attempt.attempt_id,
35666
+ job_id: attempt2.job_id,
35667
+ attempt_id: attempt2.attempt_id,
35660
35668
  operation_kind: failed ? "fail" : "complete",
35661
35669
  dispatch_outcome: terminal.outcome.dispatch_outcome,
35662
35670
  failure_category: failed ? terminal.failure_category : null,
@@ -35678,7 +35686,7 @@ var init_runner = __esm({
35678
35686
  async read() {
35679
35687
  let raw = null;
35680
35688
  const attempts = runtime_policy_generated_default.external_inference.host_core.atomic_replacement_read_attempts;
35681
- for (let attempt = 0; attempt < attempts; attempt += 1) {
35689
+ for (let attempt2 = 0; attempt2 < attempts; attempt2 += 1) {
35682
35690
  try {
35683
35691
  raw = await this.readPrivateFile(
35684
35692
  this.path,
@@ -35687,7 +35695,7 @@ var init_runner = __esm({
35687
35695
  break;
35688
35696
  } catch (error48) {
35689
35697
  const changedDuringRead = error48 instanceof Error && error48.message === "Inference host runtime receipt file changed while it was opened.";
35690
- if (!changedDuringRead || attempt === attempts - 1) throw error48;
35698
+ if (!changedDuringRead || attempt2 === attempts - 1) throw error48;
35691
35699
  }
35692
35700
  }
35693
35701
  if (raw === null) return null;
@@ -35858,8 +35866,8 @@ var init_runner = __esm({
35858
35866
  throw new Error("Inference host pending claim receipt is invalid.");
35859
35867
  }
35860
35868
  const attempts = Object.fromEntries(
35861
- Object.entries(record5.attempts).map(([key, attempt]) => {
35862
- const validated = validateAttemptReceipt(attempt);
35869
+ Object.entries(record5.attempts).map(([key, attempt2]) => {
35870
+ const validated = validateAttemptReceipt(attempt2);
35863
35871
  if (key !== validated.attempt_id) {
35864
35872
  throw new Error("Inference host attempt receipt key is invalid.");
35865
35873
  }
@@ -36746,7 +36754,7 @@ var init_runner = __esm({
36746
36754
  const envelopePublicKey = await this.dependencies.envelopePublicKey(credential);
36747
36755
  const retryExact = async (operation, boundary = {}) => {
36748
36756
  let lastError;
36749
- for (let attempt = 1; attempt <= settings.remoteRetryLimit; attempt += 1) {
36757
+ for (let attempt2 = 1; attempt2 <= settings.remoteRetryLimit; attempt2 += 1) {
36750
36758
  if (boundary.signal?.aborted) {
36751
36759
  throw new ExternalInferenceMcpError(
36752
36760
  "request_aborted",
@@ -36764,10 +36772,10 @@ var init_runner = __esm({
36764
36772
  return await operation();
36765
36773
  } catch (error48) {
36766
36774
  lastError = error48;
36767
- if (!retryableRemoteError(error48) || error48 instanceof ExternalInferenceMcpError && error48.definitivelyNotApplied || attempt === settings.remoteRetryLimit) throw error48;
36775
+ if (!retryableRemoteError(error48) || error48 instanceof ExternalInferenceMcpError && error48.definitivelyNotApplied || attempt2 === settings.remoteRetryLimit) throw error48;
36768
36776
  const requestedRetryDelay = remoteRetryAfterMs(
36769
36777
  error48,
36770
- Math.min(HOST_RUNTIME_POLICY2.remote_retry_backoff_step_ms * attempt, HOST_RUNTIME_POLICY2.remote_retry_backoff_max_ms)
36778
+ Math.min(HOST_RUNTIME_POLICY2.remote_retry_backoff_step_ms * attempt2, HOST_RUNTIME_POLICY2.remote_retry_backoff_max_ms)
36771
36779
  );
36772
36780
  const remaining = boundary.deadlineAtMs === void 0 ? Number.POSITIVE_INFINITY : Math.max(0, boundary.deadlineAtMs - now());
36773
36781
  if (requestedRetryDelay < 1 || requestedRetryDelay >= remaining) {
@@ -36795,7 +36803,7 @@ var init_runner = __esm({
36795
36803
  const retained = /* @__PURE__ */ new Set([
36796
36804
  receipt.advertisement_generation,
36797
36805
  receipt.pending_claim_request?.advertisement_generation,
36798
- ...Object.values(receipt.attempts).map((attempt) => attempt.claim.advertisement_generation)
36806
+ ...Object.values(receipt.attempts).map((attempt2) => attempt2.claim.advertisement_generation)
36799
36807
  ]);
36800
36808
  for (const generation of modelSnapshots.keys()) {
36801
36809
  if (!retained.has(generation)) modelSnapshots.delete(generation);
@@ -37868,11 +37876,11 @@ var init_runner = __esm({
37868
37876
  const batchReceiptDurability = mutateReceipt((current) => {
37869
37877
  if (current.pending_claim_request?.claim_request_id !== request.claim_request_id) runnerIdentityMismatch("Batched claim receipt");
37870
37878
  const attempts = { ...current.attempts };
37871
- for (const attempt of prepared) {
37872
- if (attempts[attempt.attempt_id]) {
37879
+ for (const attempt2 of prepared) {
37880
+ if (attempts[attempt2.attempt_id]) {
37873
37881
  runnerIdentityMismatch("Batched attempt receipt");
37874
37882
  }
37875
- attempts[attempt.attempt_id] = attempt;
37883
+ attempts[attempt2.attempt_id] = attempt2;
37876
37884
  }
37877
37885
  const promoted = {
37878
37886
  ...current,
@@ -40153,14 +40161,14 @@ var init_owned_directory_removal = __esm({
40153
40161
  }));
40154
40162
  const maxAttempts = Math.max(1, options.maxAttempts ?? runtime_policy_generated_default.external_inference.host_core.owned_directory_removal_attempts);
40155
40163
  const retryDelayMs = Math.max(0, options.retryDelayMs ?? runtime_policy_generated_default.external_inference.host_core.owned_directory_removal_retry_step_ms);
40156
- for (let attempt = 1; ; attempt += 1) {
40164
+ for (let attempt2 = 1; ; attempt2 += 1) {
40157
40165
  try {
40158
40166
  await removeDirectory(path, { recursive: true, force: options.force ?? true });
40159
40167
  return;
40160
40168
  } catch (error48) {
40161
40169
  const code = String(error48?.code ?? "");
40162
- if (attempt >= maxAttempts || !TRANSIENT_REMOVAL_ERROR_CODES.has(code)) throw error48;
40163
- await sleep4(retryDelayMs * attempt);
40170
+ if (attempt2 >= maxAttempts || !TRANSIENT_REMOVAL_ERROR_CODES.has(code)) throw error48;
40171
+ await sleep4(retryDelayMs * attempt2);
40164
40172
  }
40165
40173
  }
40166
40174
  };
@@ -41389,7 +41397,7 @@ var init_codex_adapter = __esm({
41389
41397
  [...sessions].map((session) => this.invalidateDurableSession(session))
41390
41398
  );
41391
41399
  await Promise.allSettled(
41392
- [...this.inFlightAttempts.values()].map((attempt) => attempt.promise)
41400
+ [...this.inFlightAttempts.values()].map((attempt2) => attempt2.promise)
41393
41401
  );
41394
41402
  await Promise.allSettled(
41395
41403
  [...this.attemptCleanups.values()]
@@ -45809,9 +45817,9 @@ var init_grok_adapter = __esm({
45809
45817
  if (existing.inputSha256 !== input.inputSha256) return Promise.reject(new Error("grok_attempt_input_mismatch"));
45810
45818
  return existing.promise;
45811
45819
  }
45812
- const attempt = this.track(this.run(input, null).then((result) => result.turn).finally(() => this.attempts.delete(input.attemptId)));
45813
- this.attempts.set(input.attemptId, { inputSha256: input.inputSha256, promise: attempt });
45814
- return attempt;
45820
+ const attempt2 = this.track(this.run(input, null).then((result) => result.turn).finally(() => this.attempts.delete(input.attemptId)));
45821
+ this.attempts.set(input.attemptId, { inputSha256: input.inputSha256, promise: attempt2 });
45822
+ return attempt2;
45815
45823
  }
45816
45824
  runTurn(input) {
45817
45825
  return this.track(this.run(null, input));
@@ -46417,9 +46425,9 @@ var init_exo_adapter = __esm({
46417
46425
  if (request.url === "/dispatch") {
46418
46426
  if (body.model !== providerModel || body.reasoningEffort !== input.requestedReasoningEffort) throw failure("exo_dispatch_identity_mismatch");
46419
46427
  if (!agent) {
46420
- const attempt = input;
46421
- if (!dispatched && Date.now() >= (attempt.providerDispatchNotAfterMs ?? input.deadlineAtMs)) throw failure("exo_dispatch_freshness_expired");
46422
- if (!dispatched) attempt.onProviderDispatch?.();
46428
+ const attempt2 = input;
46429
+ if (!dispatched && Date.now() >= (attempt2.providerDispatchNotAfterMs ?? input.deadlineAtMs)) throw failure("exo_dispatch_freshness_expired");
46430
+ if (!dispatched) attempt2.onProviderDispatch?.();
46423
46431
  }
46424
46432
  dispatched = true;
46425
46433
  reply(HTTP_STATUS.OK, { ok: true });
@@ -47503,7 +47511,7 @@ var init_service = __esm({
47503
47511
  }
47504
47512
  };
47505
47513
  readManifestAcrossAtomicReplacement = async (path) => {
47506
- for (let attempt = 0; attempt < ATOMIC_REPLACEMENT_READ_ATTEMPTS; attempt += 1) {
47514
+ for (let attempt2 = 0; attempt2 < ATOMIC_REPLACEMENT_READ_ATTEMPTS; attempt2 += 1) {
47507
47515
  try {
47508
47516
  return await readInferenceHostServiceManifest(path);
47509
47517
  } catch (error48) {
@@ -47527,7 +47535,7 @@ var init_service = __esm({
47527
47535
  }
47528
47536
  };
47529
47537
  readRuntimeAcrossAtomicReplacement = async (path) => {
47530
- for (let attempt = 0; attempt < ATOMIC_REPLACEMENT_READ_ATTEMPTS; attempt += 1) {
47538
+ for (let attempt2 = 0; attempt2 < ATOMIC_REPLACEMENT_READ_ATTEMPTS; attempt2 += 1) {
47531
47539
  try {
47532
47540
  return await readInferenceHostServiceRuntime(path);
47533
47541
  } catch (error48) {
@@ -47549,7 +47557,7 @@ var init_service = __esm({
47549
47557
  }
47550
47558
  };
47551
47559
  readDesiredAcrossAtomicReplacement = async (path) => {
47552
- for (let attempt = 0; attempt < ATOMIC_REPLACEMENT_READ_ATTEMPTS; attempt += 1) {
47560
+ for (let attempt2 = 0; attempt2 < ATOMIC_REPLACEMENT_READ_ATTEMPTS; attempt2 += 1) {
47553
47561
  try {
47554
47562
  return await readInferenceHostServiceDesired(path);
47555
47563
  } catch (error48) {
@@ -47727,7 +47735,7 @@ WantedBy=default.target
47727
47735
  }
47728
47736
  async withControlLock(operation) {
47729
47737
  let lock2 = null;
47730
- for (let attempt = 0; attempt < SERVICE_POLICY.control_lock_wait_attempts; attempt += 1) {
47738
+ for (let attempt2 = 0; attempt2 < SERVICE_POLICY.control_lock_wait_attempts; attempt2 += 1) {
47731
47739
  try {
47732
47740
  lock2 = await this.acquireProcessLock(this.controlLockPath());
47733
47741
  break;
@@ -47812,7 +47820,7 @@ WantedBy=default.target
47812
47820
  return await this.runCommand("systemctl", ["--user", "disable", "--now", SYSTEMD_UNIT]);
47813
47821
  }
47814
47822
  async waitForManagerActive() {
47815
- for (let attempt = 0; attempt < this.startWaitAttempts; attempt += 1) {
47823
+ for (let attempt2 = 0; attempt2 < this.startWaitAttempts; attempt2 += 1) {
47816
47824
  const status = await this.status();
47817
47825
  if (status.manager_active) return status;
47818
47826
  await this.sleep(SERVICE_POLICY.startup_poll_interval_ms);
@@ -47860,7 +47868,7 @@ ${result.stderr}`)) {
47860
47868
  }
47861
47869
  async waitForManifestApplied(manifest, targetInstanceName, maxAttempts = this.reconcileWaitAttempts, minimumRuntimeUpdatedAtExclusive) {
47862
47870
  let consecutiveReadyObservations = 0;
47863
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
47871
+ for (let attempt2 = 0; attempt2 < maxAttempts; attempt2 += 1) {
47864
47872
  let runtime = null;
47865
47873
  try {
47866
47874
  runtime = await readRuntimeAcrossAtomicReplacement(this.runtimePath());
@@ -48256,7 +48264,7 @@ ${result.stderr}`)) {
48256
48264
  this.serviceBootstrapLockPath()
48257
48265
  ];
48258
48266
  let serviceReleased = false;
48259
- for (let attempt = 0; attempt < this.stopWaitAttempts; attempt += 1) {
48267
+ for (let attempt2 = 0; attempt2 < this.stopWaitAttempts; attempt2 += 1) {
48260
48268
  let allReleased = true;
48261
48269
  for (const serviceLockPath of serviceLockPaths) {
48262
48270
  try {
@@ -55621,19 +55629,19 @@ var init_shared = __esm({
55621
55629
  if (Number.isFinite(retryAtMs)) return Math.max(0, retryAtMs - Date.now());
55622
55630
  return null;
55623
55631
  };
55624
- resolveAuthBootstrapRetryDelayMs = (response, attempt) => {
55632
+ resolveAuthBootstrapRetryDelayMs = (response, attempt2) => {
55625
55633
  const retryAfterMs = parseRetryAfterMs2(response.headers.get("Retry-After"));
55626
- const baseDelayMs = retryAfterMs ?? runtime_policy_generated_default2.ui.auth_bootstrap_retry.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (attempt - 1);
55634
+ const baseDelayMs = retryAfterMs ?? runtime_policy_generated_default2.ui.auth_bootstrap_retry.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (attempt2 - 1);
55627
55635
  const jitterMs = Math.floor(Math.random() * AUTH_BOOTSTRAP_RETRY_JITTER_MS);
55628
55636
  return Math.min(runtime_policy_generated_default2.ui.auth_bootstrap_retry.max_delay_milliseconds, Math.max(runtime_policy_generated_default2.ui.auth_bootstrap_retry.min_delay_milliseconds, baseDelayMs + jitterMs));
55629
55637
  };
55630
55638
  fetchAuthBootstrapGetWithRetry = async (input, init2) => {
55631
- for (let attempt = 1; attempt <= AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS; attempt += 1) {
55639
+ for (let attempt2 = 1; attempt2 <= AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS; attempt2 += 1) {
55632
55640
  const response = await apiFetch(input, init2);
55633
- if (response.ok || attempt >= AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS || response.status !== HTTP_STATUS.TOO_MANY_REQUESTS && response.status !== HTTP_STATUS.SERVICE_UNAVAILABLE) {
55641
+ if (response.ok || attempt2 >= AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS || response.status !== HTTP_STATUS.TOO_MANY_REQUESTS && response.status !== HTTP_STATUS.SERVICE_UNAVAILABLE) {
55634
55642
  return response;
55635
55643
  }
55636
- await sleep(resolveAuthBootstrapRetryDelayMs(response, attempt));
55644
+ await sleep(resolveAuthBootstrapRetryDelayMs(response, attempt2));
55637
55645
  }
55638
55646
  return apiFetch(input, init2);
55639
55647
  };
@@ -56491,7 +56499,7 @@ var init_network_debug = __esm({
56491
56499
  const attempts = [];
56492
56500
  for (const candidate of buildLocalProviderProbeUrls(entry)) {
56493
56501
  const startedAt = Date.now();
56494
- const attempt = {
56502
+ const attempt2 = {
56495
56503
  path: candidate.path,
56496
56504
  startedAt,
56497
56505
  completedAt: null,
@@ -56500,7 +56508,7 @@ var init_network_debug = __esm({
56500
56508
  error: null,
56501
56509
  elapsedMs: null
56502
56510
  };
56503
- attempts.push(attempt);
56511
+ attempts.push(attempt2);
56504
56512
  patchRuntimeProviderFailureDebugEntry(entry.id, (current) => ({
56505
56513
  ...current,
56506
56514
  healthProbe: {
@@ -56516,17 +56524,17 @@ var init_network_debug = __esm({
56516
56524
  signal: controller?.signal
56517
56525
  });
56518
56526
  const completedAt2 = Date.now();
56519
- attempt.completedAt = completedAt2;
56520
- attempt.outcome = response.ok ? "ok" : "error";
56521
- attempt.status = response.status;
56522
- attempt.error = response.ok ? null : `HTTP ${response.status}`;
56523
- attempt.elapsedMs = Math.max(0, completedAt2 - startedAt);
56527
+ attempt2.completedAt = completedAt2;
56528
+ attempt2.outcome = response.ok ? "ok" : "error";
56529
+ attempt2.status = response.status;
56530
+ attempt2.error = response.ok ? null : `HTTP ${response.status}`;
56531
+ attempt2.elapsedMs = Math.max(0, completedAt2 - startedAt);
56524
56532
  } catch (error48) {
56525
56533
  const completedAt2 = Date.now();
56526
- attempt.completedAt = completedAt2;
56527
- attempt.outcome = "error";
56528
- attempt.error = getSanitizedRuntimeErrorMessage(error48) || "health probe failed";
56529
- attempt.elapsedMs = Math.max(0, completedAt2 - startedAt);
56534
+ attempt2.completedAt = completedAt2;
56535
+ attempt2.outcome = "error";
56536
+ attempt2.error = getSanitizedRuntimeErrorMessage(error48) || "health probe failed";
56537
+ attempt2.elapsedMs = Math.max(0, completedAt2 - startedAt);
56530
56538
  } finally {
56531
56539
  if (timeoutId) {
56532
56540
  clearTimeout(timeoutId);
@@ -56539,7 +56547,7 @@ var init_network_debug = __esm({
56539
56547
  attempts: attempts.slice()
56540
56548
  }
56541
56549
  }));
56542
- if (attempt.outcome === "ok") {
56550
+ if (attempt2.outcome === "ok") {
56543
56551
  break;
56544
56552
  }
56545
56553
  }
@@ -61221,8 +61229,8 @@ var init_fetch = __esm({
61221
61229
  this.#throttle.maxAttempts = params.maxAttempts;
61222
61230
  }
61223
61231
  }
61224
- async #send(attempt, expires, delay3, _request, _response) {
61225
- if (attempt >= this.#throttle.maxAttempts) {
61232
+ async #send(attempt2, expires, delay3, _request, _response) {
61233
+ if (attempt2 >= this.#throttle.maxAttempts) {
61226
61234
  return _response.makeServerError("exceeded maximum retry limit");
61227
61235
  }
61228
61236
  assert2(getTime() <= expires, "timeout", "TIMEOUT", {
@@ -61261,18 +61269,18 @@ var init_fetch = __esm({
61261
61269
  if (response.statusCode === 301 || response.statusCode === 302) {
61262
61270
  try {
61263
61271
  const location2 = response.headers.location || "";
61264
- return req.redirect(location2).#send(attempt + 1, expires, 0, _request, response);
61272
+ return req.redirect(location2).#send(attempt2 + 1, expires, 0, _request, response);
61265
61273
  } catch (error48) {
61266
61274
  }
61267
61275
  return response;
61268
61276
  } else if (response.statusCode === 429) {
61269
- if (this.retryFunc == null || await this.retryFunc(req, response, attempt)) {
61277
+ if (this.retryFunc == null || await this.retryFunc(req, response, attempt2)) {
61270
61278
  const retryAfter = response.headers["retry-after"];
61271
- let delay4 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));
61279
+ let delay4 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt2));
61272
61280
  if (typeof retryAfter === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
61273
61281
  delay4 = parseInt(retryAfter);
61274
61282
  }
61275
- return req.clone().#send(attempt + 1, expires, delay4, _request, response);
61283
+ return req.clone().#send(attempt2 + 1, expires, delay4, _request, response);
61276
61284
  }
61277
61285
  }
61278
61286
  if (this.processFunc) {
@@ -61283,12 +61291,12 @@ var init_fetch = __esm({
61283
61291
  if (error48.throttle == null || typeof error48.stall !== "number") {
61284
61292
  response.makeServerError("error in post-processing function", error48).assertOk();
61285
61293
  }
61286
- let delay4 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));
61294
+ let delay4 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt2));
61287
61295
  ;
61288
61296
  if (error48.stall >= 0) {
61289
61297
  delay4 = error48.stall;
61290
61298
  }
61291
- return req.clone().#send(attempt + 1, expires, delay4, _request, response);
61299
+ return req.clone().#send(attempt2 + 1, expires, delay4, _request, response);
61292
61300
  }
61293
61301
  }
61294
61302
  return response;
@@ -78149,8 +78157,8 @@ var init_abstract_provider = __esm({
78149
78157
  transaction: tx
78150
78158
  }), "%response");
78151
78159
  }
78152
- async #call(tx, blockTag, attempt) {
78153
- assert2(attempt < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", {
78160
+ async #call(tx, blockTag, attempt2) {
78161
+ assert2(attempt2 < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", {
78154
78162
  reason: "TOO_MANY_REDIRECTS",
78155
78163
  transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true })
78156
78164
  });
@@ -78158,7 +78166,7 @@ var init_abstract_provider = __esm({
78158
78166
  try {
78159
78167
  return hexlify(await this._perform({ method: "call", transaction, blockTag }));
78160
78168
  } catch (error48) {
78161
- if (!this.disableCcipRead && isCallException(error48) && error48.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error48.data, 0, 4) === "0x556f1830") {
78169
+ if (!this.disableCcipRead && isCallException(error48) && error48.data && attempt2 >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error48.data, 0, 4) === "0x556f1830") {
78162
78170
  const data4 = error48.data;
78163
78171
  const txSender = await resolveAddress(transaction.to, this);
78164
78172
  let ccipArgs;
@@ -78195,7 +78203,7 @@ var init_abstract_provider = __esm({
78195
78203
  };
78196
78204
  this.emit("debug", { action: "sendCcipReadCall", transaction: tx2 });
78197
78205
  try {
78198
- const result = await this.#call(tx2, blockTag, attempt + 1);
78206
+ const result = await this.#call(tx2, blockTag, attempt2 + 1);
78199
78207
  this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({}, tx2), result });
78200
78208
  return result;
78201
78209
  } catch (error49) {
@@ -80120,7 +80128,7 @@ var init_provider_ankr = __esm({
80120
80128
  const request = new FetchRequest(`https://${getHost(network.name)}/${apiKey}`);
80121
80129
  request.allowGzip = true;
80122
80130
  if (apiKey === defaultApiKey) {
80123
- request.retryFunc = async (request2, response, attempt) => {
80131
+ request.retryFunc = async (request2, response, attempt2) => {
80124
80132
  showThrottleMessage("AnkrProvider");
80125
80133
  return true;
80126
80134
  };
@@ -80252,7 +80260,7 @@ var init_provider_alchemy = __esm({
80252
80260
  const request = new FetchRequest(`https://${getHost2(network.name)}/v2/${apiKey}`);
80253
80261
  request.allowGzip = true;
80254
80262
  if (apiKey === defaultApiKey2) {
80255
- request.retryFunc = async (request2, response, attempt) => {
80263
+ request.retryFunc = async (request2, response, attempt2) => {
80256
80264
  showThrottleMessage("alchemy");
80257
80265
  return true;
80258
80266
  };
@@ -80341,7 +80349,7 @@ var init_provider_chainstack = __esm({
80341
80349
  const request = new FetchRequest(`https://${getHost3(network.name)}/${apiKey}`);
80342
80350
  request.allowGzip = true;
80343
80351
  if (apiKey === getApiKey(network.name)) {
80344
- request.retryFunc = async (request2, response, attempt) => {
80352
+ request.retryFunc = async (request2, response, attempt2) => {
80345
80353
  showThrottleMessage("ChainstackProvider");
80346
80354
  return true;
80347
80355
  };
@@ -80533,7 +80541,7 @@ var init_provider_etherscan = __esm({
80533
80541
  this.emit("debug", { action: "sendRequest", id: id2, url: url2, payload });
80534
80542
  const request = new FetchRequest(url2);
80535
80543
  request.setThrottleParams({ slotInterval: 1e3 });
80536
- request.retryFunc = (req, resp, attempt) => {
80544
+ request.retryFunc = (req, resp, attempt2) => {
80537
80545
  if (this.isCommunityResource()) {
80538
80546
  showThrottleMessage("Etherscan");
80539
80547
  }
@@ -85137,7 +85145,7 @@ var init_provider_infura = __esm({
85137
85145
  request.setCredentials("", projectSecret);
85138
85146
  }
85139
85147
  if (projectId === defaultProjectId) {
85140
- request.retryFunc = async (request2, response, attempt) => {
85148
+ request.retryFunc = async (request2, response, attempt2) => {
85141
85149
  showThrottleMessage("InfuraProvider");
85142
85150
  return true;
85143
85151
  };
@@ -85242,7 +85250,7 @@ var init_provider_quicknode = __esm({
85242
85250
  const request = new FetchRequest(`https://${getHost5(network.name)}/${token}`);
85243
85251
  request.allowGzip = true;
85244
85252
  if (token === defaultToken) {
85245
- request.retryFunc = async (request2, response, attempt) => {
85253
+ request.retryFunc = async (request2, response, attempt2) => {
85246
85254
  showThrottleMessage("QuickNodeProvider");
85247
85255
  return true;
85248
85256
  };
@@ -86395,7 +86403,7 @@ var init_provider_pocket = __esm({
86395
86403
  request.setCredentials("", applicationSecret);
86396
86404
  }
86397
86405
  if (applicationId === defaultApplicationId) {
86398
- request.retryFunc = async (request2, response, attempt) => {
86406
+ request.retryFunc = async (request2, response, attempt2) => {
86399
86407
  showThrottleMessage("PocketProvider");
86400
86408
  return true;
86401
86409
  };
@@ -90355,7 +90363,7 @@ var init_hyperliquid_signer = __esm({
90355
90363
  });
90356
90364
 
90357
90365
  // lib/runtime/hyperliquid-client.ts
90358
- var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, coerceMarketMaxLeverage, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, NATIVE_FIRED_TRIGGER_CONDITION, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, extractHyperliquidExchangeError, resolveHyperliquidTriggerAcknowledgements, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
90366
+ var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, coerceMarketMaxLeverage, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, NATIVE_FIRED_TRIGGER_CONDITION, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, extractHyperliquidExchangeError, acknowledgementLookupPacing, lookupUntilListed, resolveHyperliquidTriggerAcknowledgements, resolveHyperliquidModifyAcknowledgement, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
90359
90367
  var init_hyperliquid_client = __esm({
90360
90368
  "lib/runtime/hyperliquid-client.ts"() {
90361
90369
  "use strict";
@@ -91861,7 +91869,24 @@ var init_hyperliquid_client = __esm({
91861
91869
  }
91862
91870
  return null;
91863
91871
  };
91864
- resolveHyperliquidTriggerAcknowledgements = async (payload, action, lookup) => {
91872
+ acknowledgementLookupPacing = () => ({
91873
+ windowMs: runtime_policy_generated_default2.exchange.hyperliquid.acknowledgement_lookup.window_milliseconds,
91874
+ pollMs: runtime_policy_generated_default2.exchange.hyperliquid.acknowledgement_lookup.poll_milliseconds,
91875
+ sleep: (ms) => new Promise((resolve14) => {
91876
+ globalThis.setTimeout(resolve14, ms);
91877
+ }),
91878
+ // Monotonic: a wall-clock step must not stretch or cut the window.
91879
+ nowMs: () => globalThis.performance.now()
91880
+ });
91881
+ lookupUntilListed = async (lookup, clientOrderId, pacing) => {
91882
+ const deadline = pacing.nowMs() + pacing.windowMs;
91883
+ for (; ; ) {
91884
+ const evidence = await lookup(clientOrderId);
91885
+ if (evidence.responseStatus !== "unknownOid" || pacing.nowMs() + pacing.pollMs > deadline) return evidence;
91886
+ await pacing.sleep(pacing.pollMs);
91887
+ }
91888
+ };
91889
+ resolveHyperliquidTriggerAcknowledgements = async (payload, action, lookup, pacing = acknowledgementLookupPacing()) => {
91865
91890
  if (action.type !== "order" || action.grouping !== "normalTpsl" && action.grouping !== "positionTpsl" || !Array.isArray(action.orders) || payload == null || typeof payload !== "object" || Array.isArray(payload)) {
91866
91891
  return payload;
91867
91892
  }
@@ -91883,7 +91908,7 @@ var init_hyperliquid_client = __esm({
91883
91908
  }
91884
91909
  let evidence;
91885
91910
  try {
91886
- evidence = await lookup(clientOrderId);
91911
+ evidence = await lookupUntilListed(lookup, clientOrderId, pacing);
91887
91912
  } catch {
91888
91913
  return payload;
91889
91914
  }
@@ -91895,6 +91920,36 @@ var init_hyperliquid_client = __esm({
91895
91920
  }
91896
91921
  return { ...root, response: { ...response, data: { ...data4, statuses: resolved } } };
91897
91922
  };
91923
+ resolveHyperliquidModifyAcknowledgement = async (payload, action, lookup, pacing = acknowledgementLookupPacing()) => {
91924
+ if (action.type !== "modify" || payload == null || typeof payload !== "object" || Array.isArray(payload)) {
91925
+ return payload;
91926
+ }
91927
+ const root = payload;
91928
+ const response = root.response;
91929
+ const order = action.order;
91930
+ const clientOrderId = String(order?.c ?? "").trim().toLowerCase();
91931
+ if (root.status !== "ok" || response?.type !== "default" || !/^0x[0-9a-f]{32}$/.test(clientOrderId)) {
91932
+ return payload;
91933
+ }
91934
+ let evidence;
91935
+ try {
91936
+ evidence = await lookupUntilListed(lookup, clientOrderId, pacing);
91937
+ } catch {
91938
+ return payload;
91939
+ }
91940
+ const orderId = Number(evidence.orderId);
91941
+ const state2 = classifyHyperliquidOrderStatus(evidence.orderStatus);
91942
+ if (!evidence.responseValid || !evidence.orderMatches || !Number.isSafeInteger(orderId) || orderId <= 0 || state2 !== "open" && state2 !== "filled") {
91943
+ return payload;
91944
+ }
91945
+ return {
91946
+ ...root,
91947
+ response: {
91948
+ type: "order",
91949
+ data: { statuses: [state2 === "open" ? { resting: { oid: orderId, cloid: clientOrderId } } : { filled: { oid: orderId } }] }
91950
+ }
91951
+ };
91952
+ };
91898
91953
  isDefinitiveHyperliquidExchangeResponse = (payload, action) => {
91899
91954
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
91900
91955
  return false;
@@ -92641,7 +92696,17 @@ var init_hyperliquid_client = __esm({
92641
92696
  );
92642
92697
  }
92643
92698
  const triggerWallet = String(input.triggerAcknowledgementWalletAddress ?? "").trim();
92644
- if (triggerWallet) {
92699
+ if (triggerWallet && input.payload.action.type === "modify") {
92700
+ payload = await resolveHyperliquidModifyAcknowledgement(
92701
+ payload,
92702
+ input.payload.action,
92703
+ (clientOrderId) => fetchBrowserOrderStatusEvidence({
92704
+ ...input,
92705
+ walletAddress: triggerWallet,
92706
+ orderId: clientOrderId
92707
+ })
92708
+ );
92709
+ } else if (triggerWallet) {
92645
92710
  payload = await resolveHyperliquidTriggerAcknowledgements(
92646
92711
  payload,
92647
92712
  input.payload.action,
@@ -93164,7 +93229,7 @@ async function postClientRuntime(path, profileId, body, options) {
93164
93229
  let lastNetworkError = null;
93165
93230
  let replacementLeaseRetryUsed = false;
93166
93231
  let lastRequestId = null;
93167
- const deadlineError = (attempt, cause) => annotateRuntimeRequestError(
93232
+ const deadlineError = (attempt2, cause) => annotateRuntimeRequestError(
93168
93233
  Object.assign(
93169
93234
  new Error("Client runtime decision persistence deadline exceeded after the AI run completed."),
93170
93235
  cause && (typeof cause === "object" || typeof cause === "function") ? { cause } : {}
@@ -93172,7 +93237,7 @@ async function postClientRuntime(path, profileId, body, options) {
93172
93237
  {
93173
93238
  path,
93174
93239
  method: "POST",
93175
- attempt,
93240
+ attempt: attempt2,
93176
93241
  maxAttempts: null,
93177
93242
  status: Number.isFinite(Number(cause?.status)) ? Number(cause.status) : null,
93178
93243
  keepalive,
@@ -93182,21 +93247,21 @@ async function postClientRuntime(path, profileId, body, options) {
93182
93247
  requestId: lastRequestId
93183
93248
  }
93184
93249
  );
93185
- const waitBeforeRetry = async (delayMs, attempt, cause) => {
93250
+ const waitBeforeRetry = async (delayMs, attempt2, cause) => {
93186
93251
  if (deadlineAtMs === null) {
93187
93252
  await sleep(delayMs);
93188
93253
  return;
93189
93254
  }
93190
93255
  const remainingMs = deadlineAtMs - Date.now();
93191
93256
  if (remainingMs <= delayMs) {
93192
- throw deadlineError(attempt, cause);
93257
+ throw deadlineError(attempt2, cause);
93193
93258
  }
93194
93259
  await sleep(delayMs);
93195
93260
  };
93196
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
93261
+ for (let attempt2 = 1; attempt2 <= maxAttempts; attempt2 += 1) {
93197
93262
  const deadlineRemainingMs = deadlineAtMs === null ? null : deadlineAtMs - Date.now();
93198
93263
  if (deadlineRemainingMs !== null && deadlineRemainingMs <= 0) {
93199
- throw deadlineError(Math.max(0, attempt - 1), lastNetworkError);
93264
+ throw deadlineError(Math.max(0, attempt2 - 1), lastNetworkError);
93200
93265
  }
93201
93266
  let response = null;
93202
93267
  let requestTimedOut = false;
@@ -93224,7 +93289,7 @@ async function postClientRuntime(path, profileId, body, options) {
93224
93289
  label: "client_runtime_api",
93225
93290
  method: "POST",
93226
93291
  url: requestUrl2,
93227
- note: `path=${path} attempt=${attempt}/${maxAttempts}${lastRequestId ? ` reconcile_only=${options?.reconcileOnly === true} request_id=${lastRequestId}` : ""}`
93292
+ note: `path=${path} attempt=${attempt2}/${maxAttempts}${lastRequestId ? ` reconcile_only=${options?.reconcileOnly === true} request_id=${lastRequestId}` : ""}`
93228
93293
  });
93229
93294
  try {
93230
93295
  response = await apiFetch(requestUrl2, {
@@ -93250,11 +93315,11 @@ async function postClientRuntime(path, profileId, body, options) {
93250
93315
  if (replacementLeaseToken) {
93251
93316
  resolvedRuntimeLeaseToken = replacementLeaseToken;
93252
93317
  attachRuntimeLeaseHeader(requestHeaders, resolvedRuntimeLeaseToken);
93253
- if (attempt >= maxAttempts && !replacementLeaseRetryUsed) {
93318
+ if (attempt2 >= maxAttempts && !replacementLeaseRetryUsed) {
93254
93319
  replacementLeaseRetryUsed = true;
93255
93320
  maxAttempts += 1;
93256
93321
  }
93257
- if (attempt >= maxAttempts) {
93322
+ if (attempt2 >= maxAttempts) {
93258
93323
  throw error48;
93259
93324
  }
93260
93325
  continue;
@@ -93269,10 +93334,10 @@ async function postClientRuntime(path, profileId, body, options) {
93269
93334
  hadRuntimeLeaseToken: Boolean(resolvedRuntimeLeaseToken),
93270
93335
  leaseCleared
93271
93336
  });
93272
- if (!keepalive && attempt < maxAttempts && !leaseInvalidatingError && (shouldRetryClientRuntimeHttpStatus(path, response.status) || isRuntimeIdempotencyInProgressError(response.status, error48.message) || Boolean(idempotencyKey) && isRetryableRuntimeConflictError(response.status, error48))) {
93337
+ if (!keepalive && attempt2 < maxAttempts && !leaseInvalidatingError && (shouldRetryClientRuntimeHttpStatus(path, response.status) || isRuntimeIdempotencyInProgressError(response.status, error48.message) || Boolean(idempotencyKey) && isRetryableRuntimeConflictError(response.status, error48))) {
93273
93338
  await waitBeforeRetry(
93274
- resolveClientRuntimeRetryDelayMs(attempt, response.headers.get("Retry-After")),
93275
- attempt,
93339
+ resolveClientRuntimeRetryDelayMs(attempt2, response.headers.get("Retry-After")),
93340
+ attempt2,
93276
93341
  error48
93277
93342
  );
93278
93343
  continue;
@@ -93293,13 +93358,13 @@ async function postClientRuntime(path, profileId, body, options) {
93293
93358
  lastNetworkError = requestError;
93294
93359
  trace.completeError(requestError, response?.status ?? null);
93295
93360
  if (deadlineAtMs !== null && Date.now() >= deadlineAtMs) {
93296
- throw deadlineError(attempt, requestError);
93361
+ throw deadlineError(attempt2, requestError);
93297
93362
  }
93298
- if (signal?.aborted || !requestTimedOut && !isTransientNetworkFetchError(requestError) || attempt >= maxAttempts) {
93363
+ if (signal?.aborted || !requestTimedOut && !isTransientNetworkFetchError(requestError) || attempt2 >= maxAttempts) {
93299
93364
  throw annotateRuntimeRequestError(requestError, {
93300
93365
  path,
93301
93366
  method: "POST",
93302
- attempt,
93367
+ attempt: attempt2,
93303
93368
  maxAttempts: deadlineAtMs === null ? maxAttempts : null,
93304
93369
  status: response?.status ?? null,
93305
93370
  keepalive,
@@ -93309,8 +93374,8 @@ async function postClientRuntime(path, profileId, body, options) {
93309
93374
  });
93310
93375
  }
93311
93376
  await waitBeforeRetry(
93312
- resolveClientRuntimeRetryDelayMs(attempt, null),
93313
- attempt,
93377
+ resolveClientRuntimeRetryDelayMs(attempt2, null),
93378
+ attempt2,
93314
93379
  requestError
93315
93380
  );
93316
93381
  continue;
@@ -94722,13 +94787,13 @@ var init_api2 = __esm({
94722
94787
  };
94723
94788
  isRuntimeIdempotencyInProgressError = (status, message) => status === HTTP_STATUS.CONFLICT && (message.toLowerCase().includes("duplicate request already in progress") || message.toLowerCase().includes("duplicate request in-flight"));
94724
94789
  isRetryableRuntimeConflictError = (status, error48) => status === HTTP_STATUS.CONFLICT && error48.retryable === true && (error48.code === "profile_runtime_contract_busy" || error48.code === "runtime_decision_finalizing" || error48.code === "runtime_trade_sync_finalizing" || error48.code === "runtime_decision_unconfirmed");
94725
- resolveClientRuntimeRetryDelayMs = (attempt, retryAfterHeader) => {
94790
+ resolveClientRuntimeRetryDelayMs = (attempt2, retryAfterHeader) => {
94726
94791
  const policy2 = runtime_policy_generated_default2.trading.engine.client_runtime.request_retry;
94727
94792
  const retryAfterMs = parseRetryAfterMs2(retryAfterHeader);
94728
94793
  if (retryAfterMs != null) {
94729
94794
  return Math.min(policy2.max_delay_milliseconds, Math.max(policy2.min_retry_after_milliseconds, retryAfterMs));
94730
94795
  }
94731
- return Math.min(policy2.max_delay_milliseconds, policy2.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (attempt - 1));
94796
+ return Math.min(policy2.max_delay_milliseconds, policy2.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (attempt2 - 1));
94732
94797
  };
94733
94798
  reconcilePendingClientExchangeMutation = async (profileId, requestOptions) => {
94734
94799
  let reconciliation;
@@ -96263,7 +96328,7 @@ var init_browser_trading = __esm({
96263
96328
  };
96264
96329
  executeClientMarketOrder = async (input) => {
96265
96330
  input = { ...input, publicRequestPriority: input.reduceOnly === true ? "trading_reduce" : "trading_execute" };
96266
- if ((input.positionChildren?.length ?? 0) > 0 && input.protection) {
96331
+ if ((input.positionChildren?.length ?? 0) > 0 && input.protection && !input.protection.native) {
96267
96332
  throw new Error("An entry carries either native position children or server-owned protection, not both.");
96268
96333
  }
96269
96334
  throwIfAborted(input.signal);
@@ -96483,6 +96548,7 @@ var init_browser_trading = __esm({
96483
96548
  triggerPrice: input.triggerPrice,
96484
96549
  triggerKind: input.triggerKind,
96485
96550
  triggerIsMarket: input.triggerIsMarket,
96551
+ ...input.positionOrder === true ? { positionOrder: true } : {},
96486
96552
  clientOrderId: mutation.clientOrderId,
96487
96553
  expiresAfterSeconds: requireClientExchangeExpiresAfterSeconds(input.config)
96488
96554
  });
@@ -96502,7 +96568,10 @@ var init_browser_trading = __esm({
96502
96568
  operationKind: "order",
96503
96569
  symbol: input.symbol,
96504
96570
  onExchangeOrderDispatched: input.onExchangeOrderDispatched
96505
- }
96571
+ },
96572
+ // A modify's answer names no order; its status read by the new client
96573
+ // order id does (resolveHyperliquidModifyAcknowledgement).
96574
+ triggerAcknowledgementWalletAddress: input.walletAddress ?? null
96506
96575
  });
96507
96576
  };
96508
96577
  executeClientCancelOrder = async (input) => {
@@ -98304,7 +98373,7 @@ var init_protective_evidence = __esm({
98304
98373
  });
98305
98374
 
98306
98375
  // lib/runtime/protective-actions.ts
98307
- var DECIMAL, CLOID, fail2, exactKeys, nonNegativeInteger, decimalString, canonicalTriggerOrder, canonicalProtectiveWireAction, assertProtectiveActionLocallySafe, authorityArgs2, errorCode2, foreignClaimExpiresAtMs, drainLocks, refusedUntil, drainClientProtectiveActions, drainOnce;
98376
+ var DECIMAL, CLOID, fail2, exactKeys, nonNegativeInteger, decimalString, POSITION_ORDER_SIZE, orderSizeString, canonicalTriggerOrder, canonicalProtectiveWireAction, assertProtectiveActionLocallySafe, authorityArgs2, errorCode2, foreignClaimExpiresAtMs, drainLocks, refusedUntil, drainClientProtectiveActions, drainOnce;
98308
98377
  var init_protective_actions = __esm({
98309
98378
  "lib/runtime/protective-actions.ts"() {
98310
98379
  "use strict";
@@ -98343,6 +98412,8 @@ var init_protective_actions = __esm({
98343
98412
  if (typeof value !== "string" || !DECIMAL.test(value) || Number(value) <= 0) fail2(`${label2} is invalid.`);
98344
98413
  return value;
98345
98414
  };
98415
+ POSITION_ORDER_SIZE = "0";
98416
+ orderSizeString = (value) => value === POSITION_ORDER_SIZE ? POSITION_ORDER_SIZE : decimalString(value, "size");
98346
98417
  canonicalTriggerOrder = (value) => {
98347
98418
  const order = exactKeys(value, ["a", "b", "p", "s", "r", "t", "c"], "order");
98348
98419
  const type = exactKeys(order.t, ["trigger"], "order type");
@@ -98357,7 +98428,7 @@ var init_protective_actions = __esm({
98357
98428
  a: nonNegativeInteger(order.a, "asset"),
98358
98429
  b: order.b,
98359
98430
  p: decimalString(order.p, "price"),
98360
- s: decimalString(order.s, "size"),
98431
+ s: orderSizeString(order.s),
98361
98432
  r: true,
98362
98433
  t: {
98363
98434
  trigger: {
@@ -98375,9 +98446,12 @@ var init_protective_actions = __esm({
98375
98446
  const action = exactKeys(wire, ["type", "orders", "grouping"], "action");
98376
98447
  const orders = Array.isArray(action.orders) ? action.orders.map(canonicalTriggerOrder) : fail2("orders are missing.");
98377
98448
  const grouping = action.grouping;
98378
- if (!(orders.length === 1 && grouping === "na") && !(orders.length === HYPERLIQUID_EXCHANGE_SPECIFICATION.position_tpsl_order_count && grouping === "positionTpsl")) {
98449
+ const positionOrders = orders.filter((order) => order.s === POSITION_ORDER_SIZE);
98450
+ const kinds = orders.map((order) => order.t.trigger.tpsl);
98451
+ if (!(orders.length === 1 && grouping === "na" && positionOrders.length === 0) && !(orders.length === HYPERLIQUID_EXCHANGE_SPECIFICATION.position_tpsl_order_count && grouping === "positionTpsl" && (positionOrders.length === 0 || positionOrders.length === orders.length)) && !(grouping === "positionTpsl" && orders.length === 1 && positionOrders.length === 1)) {
98379
98452
  fail2("order grouping is invalid.");
98380
98453
  }
98454
+ if (positionOrders.length > 0 && new Set(kinds).size !== kinds.length) fail2("position orders repeat a kind.");
98381
98455
  return { type: "order", orders, grouping };
98382
98456
  }
98383
98457
  if (kind === "modify") {
@@ -99557,6 +99631,851 @@ var init_protective_entry_cover = __esm({
99557
99631
  }
99558
99632
  });
99559
99633
 
99634
+ // lib/runtime/native-position-protection.ts
99635
+ var nativeProtectionSettings, memberSetting, KINDS, formatTriggerOrNull, nativePositionTriggerPrice, nativeEntryRequest, HALF_UP_DIGIT, roundDecimalHalfUp, nativeTrailingRetracement, nativeAfterFillActions, classifyNativeOrderEnd, isOpenInDirection, nativePlacementGate, nativeStrayOrderDecision, explainAbsentProtectiveOrder, readServerNativeProtectionState;
99636
+ var init_native_position_protection = __esm({
99637
+ "lib/runtime/native-position-protection.ts"() {
99638
+ "use strict";
99639
+ init_define_VTX_EXO_POLICY();
99640
+ init_define_VTX_GROK_POLICY();
99641
+ init_define_VTX_PI_MODEL_POLICY();
99642
+ init_constants();
99643
+ init_hyperliquid_client();
99644
+ init_hyperliquid_order_status();
99645
+ init_protective_stop_replacement();
99646
+ nativeProtectionSettings = (resolved) => ({
99647
+ stopLoss: resolved.tpSlEnabled && resolved.stopLossEnabled ? {
99648
+ mode: resolved.stopLossMode,
99649
+ value: resolved.stopLossMode === "usdc" ? resolved.stopLossUsdc : resolved.stopLossPct,
99650
+ trailing: resolved.stopLossType === "trailing"
99651
+ } : null,
99652
+ takeProfit: resolved.tpSlEnabled && resolved.takeProfitEnabled ? {
99653
+ mode: resolved.takeProfitMode,
99654
+ value: resolved.takeProfitMode === "usdc" ? resolved.takeProfitUsdc : resolved.takeProfitPct
99655
+ } : null
99656
+ });
99657
+ memberSetting = (settings, kind) => kind === "sl" ? settings.stopLoss : settings.takeProfit;
99658
+ KINDS = ["sl", "tp"];
99659
+ formatTriggerOrNull = (raw, sizeDecimals) => {
99660
+ try {
99661
+ const wire = formatHyperliquidTriggerPriceWire(raw, sizeDecimals);
99662
+ return Number(wire) > 0 ? wire : null;
99663
+ } catch {
99664
+ return null;
99665
+ }
99666
+ };
99667
+ nativePositionTriggerPrice = (input) => {
99668
+ const size = Math.abs(input.positionSize);
99669
+ if (!(input.averageEntry > 0) || !(input.value > 0) || input.mode === "usdc" && !(size > 0)) return null;
99670
+ const away = input.kind === "tp" === input.isLong;
99671
+ const raw = input.mode === "percent" ? away ? input.averageEntry * (1 + input.value / PERCENT_SCALE) : input.averageEntry * (1 - input.value / PERCENT_SCALE) : away ? input.averageEntry + input.value / size : input.averageEntry - input.value / size;
99672
+ if (!Number.isFinite(raw) || raw <= 0) return null;
99673
+ return formatTriggerOrNull(raw, input.sizeDecimals);
99674
+ };
99675
+ nativeEntryRequest = (input) => {
99676
+ if (input.positionHasLegacyLegs) return { shape: "legacy_per_entry" };
99677
+ const alone = { shape: "entry_alone", grouping: "na", children: [] };
99678
+ if (input.positionBefore !== 0) return alone;
99679
+ const children = [];
99680
+ for (const kind of KINDS) {
99681
+ const setting = memberSetting(input.settings, kind);
99682
+ if (!setting) continue;
99683
+ const trigger = nativePositionTriggerPrice({
99684
+ averageEntry: input.referencePrice,
99685
+ positionSize: input.entrySize,
99686
+ isLong: input.isLong,
99687
+ kind,
99688
+ mode: setting.mode,
99689
+ value: setting.value,
99690
+ sizeDecimals: input.sizeDecimals
99691
+ });
99692
+ if (trigger !== null) children.push({ kind, trigger });
99693
+ }
99694
+ return children.length > 0 ? { shape: "entry_with_position_children", grouping: "normalTpsl", children } : alone;
99695
+ };
99696
+ HALF_UP_DIGIT = "5";
99697
+ roundDecimalHalfUp = (value, decimals) => {
99698
+ const text = String(value);
99699
+ if (text.includes("e")) return "0";
99700
+ const [integer3, fraction = ""] = text.split(".");
99701
+ if (fraction.length <= decimals) return fraction ? `${integer3}.${fraction}`.replace(/\.?0+$/, "") : integer3;
99702
+ let units = BigInt(`${integer3}${fraction.slice(0, decimals)}`);
99703
+ if (fraction[decimals] >= HALF_UP_DIGIT) units += BigInt(1);
99704
+ const digits = units.toString().padStart(decimals + 1, "0");
99705
+ const rounded = `${digits.slice(0, -decimals)}.${digits.slice(-decimals)}`;
99706
+ return rounded.replace(/\.?0+$/, "");
99707
+ };
99708
+ nativeTrailingRetracement = (input) => {
99709
+ if (!(input.value > 0) || !Number.isFinite(input.value)) return null;
99710
+ if (input.mode === "percent") {
99711
+ if (input.value >= PERCENT_SCALE) return null;
99712
+ const pct = roundDecimalHalfUp(
99713
+ input.value,
99714
+ HYPERLIQUID_EXCHANGE_SPECIFICATION.trailing_retracement_pct_max_decimals
99715
+ );
99716
+ return Number(pct) > 0 ? { pct: `${pct}%` } : null;
99717
+ }
99718
+ const size = Math.abs(input.lotSize);
99719
+ if (!(size > 0)) return null;
99720
+ const px = formatTriggerOrNull(input.value / size, input.sizeDecimals);
99721
+ return px === null ? null : { px };
99722
+ };
99723
+ nativeAfterFillActions = (input) => {
99724
+ const actions = [];
99725
+ for (const kind of KINDS) {
99726
+ const setting = memberSetting(input.settings, kind);
99727
+ if (!setting) continue;
99728
+ const trigger = nativePositionTriggerPrice({
99729
+ averageEntry: input.position.entryPrice,
99730
+ positionSize: input.position.size,
99731
+ isLong: input.isLong,
99732
+ kind,
99733
+ mode: setting.mode,
99734
+ value: setting.value,
99735
+ sizeDecimals: input.sizeDecimals
99736
+ });
99737
+ if (trigger === null) continue;
99738
+ const resting = input.resting[kind];
99739
+ if (resting === null) {
99740
+ actions.push({ action: "place_position", kind, trigger });
99741
+ } else if (Number(resting) !== Number(trigger)) {
99742
+ actions.push({ action: "modify", kind, trigger });
99743
+ }
99744
+ }
99745
+ const stopLoss = input.settings.stopLoss;
99746
+ if (stopLoss?.trailing) {
99747
+ const retracement = nativeTrailingRetracement({
99748
+ mode: stopLoss.mode,
99749
+ value: stopLoss.value,
99750
+ lotSize: Number(input.fillSize),
99751
+ sizeDecimals: input.sizeDecimals
99752
+ });
99753
+ if (retracement) actions.push({ action: "place_trailing", size: input.fillSize, retracement });
99754
+ }
99755
+ return actions;
99756
+ };
99757
+ classifyNativeOrderEnd = (input) => {
99758
+ const status = input.orderStatus;
99759
+ const state2 = classifyHyperliquidOrderStatus(status);
99760
+ if (state2 === "open") return "resting";
99761
+ if (state2 === "pending_trigger") return "pending";
99762
+ if (state2 === "filled") return "fired";
99763
+ if (state2 === null) return "unknown";
99764
+ if (status === "siblingFilledCanceled" || POSITION_ENDED_ORDER_STATUSES.has(status)) return "ended_with_position";
99765
+ if (status === "canceled") {
99766
+ if (input.replacedByOwnModify) return "superseded";
99767
+ return input.userCancelledThroughVtx ? "user_cancelled" : "lost";
99768
+ }
99769
+ return protectiveStopRejectionIsPermanent(status) ? "lost_permanent" : "lost";
99770
+ };
99771
+ isOpenInDirection = (position, isLong) => isLong ? position > 0 : position < 0;
99772
+ nativePlacementGate = (input) => {
99773
+ if (!(input.positionStateMs > input.eventMs)) return "need_reads";
99774
+ return isOpenInDirection(input.position, input.isLong) ? "place" : "not_required";
99775
+ };
99776
+ nativeStrayOrderDecision = (input) => {
99777
+ if (isOpenInDirection(input.position, input.isLong)) return "keep";
99778
+ return input.positionStateMs > input.placedMs ? "cancel" : "need_reads";
99779
+ };
99780
+ explainAbsentProtectiveOrder = (input) => {
99781
+ if (isOpenInDirection(input.position, input.isLong)) return "status_read";
99782
+ return input.positionStateMs > input.lastSeenRestingMs ? "ended_with_position" : "need_reads";
99783
+ };
99784
+ readServerNativeProtectionState = (listing) => {
99785
+ const raw = listing?.native_position_protection;
99786
+ if (!raw || typeof raw !== "object") return null;
99787
+ const record5 = raw;
99788
+ const symbols = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : null;
99789
+ const legacy = symbols(record5.legacy_symbols);
99790
+ const native = symbols(record5.native_symbols);
99791
+ if (typeof record5.enabled !== "boolean" || legacy == null || native == null) return null;
99792
+ return { enabled: record5.enabled, legacySymbols: new Set(legacy), nativeSymbols: new Set(native) };
99793
+ };
99794
+ }
99795
+ });
99796
+
99797
+ // lib/runtime/native-protection-device.ts
99798
+ var NATIVE_PROTECTION_RECORD_VERSION, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, isMember, readNativeProtectionRecord, writeNativeProtectionRecord, NativeOrderNotSentError, withDispatchBoundary, attempt, notSentRestores, errorText, actionOf, isOpenInDirection2, restingOrderIdAt, definitivelyRefused, planNativeOpen, recordEntryChildren, observeMembers, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, settleNativeProtectionAfterFill, reconcileNativeProtection;
99799
+ var init_native_protection_device = __esm({
99800
+ "lib/runtime/native-protection-device.ts"() {
99801
+ "use strict";
99802
+ init_define_VTX_EXO_POLICY();
99803
+ init_define_VTX_GROK_POLICY();
99804
+ init_define_VTX_PI_MODEL_POLICY();
99805
+ init_order_identity();
99806
+ init_native_position_protection();
99807
+ NATIVE_PROTECTION_RECORD_VERSION = 1;
99808
+ nativeProtectionStorage = null;
99809
+ resolveStorage = () => {
99810
+ if (nativeProtectionStorage) return nativeProtectionStorage;
99811
+ if (typeof window === "undefined") return null;
99812
+ try {
99813
+ return window.localStorage ?? null;
99814
+ } catch {
99815
+ return null;
99816
+ }
99817
+ };
99818
+ setNativeProtectionStorage = (storage3) => {
99819
+ nativeProtectionStorage = storage3;
99820
+ };
99821
+ recordKey = (profileId, symbol2) => `vtx:native-protection:${profileId}:${symbol2}`;
99822
+ isMember = (value) => {
99823
+ if (!value || typeof value !== "object") return false;
99824
+ const member = value;
99825
+ return (member.kind === "sl" || member.kind === "tp") && typeof member.clientOrderId === "string" && (member.orderId === null || typeof member.orderId === "number" && Number.isSafeInteger(member.orderId)) && typeof member.trigger === "string" && (member.placedAtMs === null || typeof member.placedAtMs === "number") && typeof member.sentAtMs === "number" && typeof member.replacedOnce === "boolean" && (member.pendingModify === void 0 || typeof member.pendingModify === "object" && member.pendingModify !== null && typeof member.pendingModify.clientOrderId === "string" && typeof member.pendingModify.trigger === "string" && typeof member.pendingModify.sentAtMs === "number");
99826
+ };
99827
+ readNativeProtectionRecord = (profileId, symbol2) => {
99828
+ const storage3 = resolveStorage();
99829
+ if (!storage3) return null;
99830
+ const raw = storage3.getItem(recordKey(profileId, symbol2));
99831
+ if (raw == null) return null;
99832
+ const parsed = JSON.parse(raw);
99833
+ if (parsed?.version !== NATIVE_PROTECTION_RECORD_VERSION || parsed.profileId !== profileId || parsed.symbol !== symbol2 || typeof parsed.walletAddress !== "string" || typeof parsed.isLong !== "boolean" || parsed.phase !== "entry_pending" && parsed.phase !== "active" || typeof parsed.entryMutationId !== "string" || typeof parsed.entryClientOrderId !== "string" || typeof parsed.createdAtMs !== "number" || !Array.isArray(parsed.members) || !parsed.members.every(isMember)) {
99834
+ throw new Error("Stored native protection record is invalid.");
99835
+ }
99836
+ return parsed;
99837
+ };
99838
+ writeNativeProtectionRecord = (profileId, symbol2, record5) => {
99839
+ const storage3 = resolveStorage();
99840
+ if (!storage3) return false;
99841
+ try {
99842
+ if (record5 == null) storage3.removeItem(recordKey(profileId, symbol2));
99843
+ else storage3.setItem(recordKey(profileId, symbol2), JSON.stringify(record5));
99844
+ return true;
99845
+ } catch {
99846
+ return false;
99847
+ }
99848
+ };
99849
+ NativeOrderNotSentError = class extends Error {
99850
+ constructor(cause) {
99851
+ super(cause instanceof Error ? cause.message : "The exchange call failed before dispatch.");
99852
+ this.name = "NativeOrderNotSentError";
99853
+ this.cause = cause;
99854
+ }
99855
+ };
99856
+ withDispatchBoundary = async (call) => {
99857
+ let dispatched = false;
99858
+ try {
99859
+ return await call(() => {
99860
+ dispatched = true;
99861
+ });
99862
+ } catch (error48) {
99863
+ throw dispatched ? error48 : new NativeOrderNotSentError(error48);
99864
+ }
99865
+ };
99866
+ attempt = async (io, call) => {
99867
+ try {
99868
+ const response = await call();
99869
+ return definitivelyRefused(response) ? { ok: false, refused: true, error: response } : { ok: true, response };
99870
+ } catch (error48) {
99871
+ if (io.endsPass?.(error48)) throw error48;
99872
+ return { ok: false, refused: io.isDefinitiveRefusal(error48), error: error48 };
99873
+ }
99874
+ };
99875
+ notSentRestores = async (send, restore) => {
99876
+ try {
99877
+ return await send();
99878
+ } catch (error48) {
99879
+ if (error48 instanceof NativeOrderNotSentError) restore();
99880
+ throw error48;
99881
+ }
99882
+ };
99883
+ errorText = (error48) => error48 instanceof Error ? error48.message : typeof error48 === "string" ? error48 : "Exchange call failed.";
99884
+ actionOf = (kind) => kind === "sl" ? "AUTO_SL" : "AUTO_TP";
99885
+ isOpenInDirection2 = (position, isLong) => isLong ? position > 0 : position < 0;
99886
+ restingOrderIdAt = (response, index) => {
99887
+ const statuses = response?.response?.data?.statuses;
99888
+ const status = Array.isArray(statuses) ? statuses[index] : void 0;
99889
+ const resting = status && typeof status === "object" ? status.resting : void 0;
99890
+ const orderId = Number(resting?.oid);
99891
+ return Number.isSafeInteger(orderId) && orderId > 0 ? orderId : null;
99892
+ };
99893
+ definitivelyRefused = (response) => {
99894
+ const root = response;
99895
+ if (root?.status === "err") return true;
99896
+ const statuses = root?.response?.data?.statuses;
99897
+ return Array.isArray(statuses) && statuses.length > 0 && statuses.every((status) => Boolean(status && typeof status === "object" && "error" in status));
99898
+ };
99899
+ planNativeOpen = (input) => {
99900
+ if (input.settings.stopLoss?.trailing) return null;
99901
+ const request = nativeEntryRequest({
99902
+ settings: input.settings,
99903
+ isLong: input.isLong,
99904
+ sizeDecimals: input.sizeDecimals,
99905
+ referencePrice: input.referencePrice,
99906
+ entrySize: input.entrySize,
99907
+ positionBefore: input.positionBefore,
99908
+ positionHasLegacyLegs: input.positionHasLegacyLegs
99909
+ });
99910
+ if (request.shape !== "entry_with_position_children") return null;
99911
+ const members = request.children.map((child) => ({
99912
+ kind: child.kind,
99913
+ clientOrderId: clientOrderIdForMutation(input.newMutationId()),
99914
+ orderId: null,
99915
+ trigger: child.trigger,
99916
+ placedAtMs: null,
99917
+ sentAtMs: input.nowMs,
99918
+ replacedOnce: false
99919
+ }));
99920
+ return {
99921
+ children: members.map((member) => ({
99922
+ kind: member.kind,
99923
+ triggerPrice: Number(member.trigger),
99924
+ clientOrderId: member.clientOrderId
99925
+ })),
99926
+ record: {
99927
+ version: NATIVE_PROTECTION_RECORD_VERSION,
99928
+ profileId: input.profileId,
99929
+ symbol: input.symbol,
99930
+ walletAddress: input.walletAddress.toLowerCase(),
99931
+ isLong: input.isLong,
99932
+ phase: "entry_pending",
99933
+ entryMutationId: input.entryMutationId,
99934
+ entryClientOrderId: input.entryClientOrderId,
99935
+ createdAtMs: input.nowMs,
99936
+ members
99937
+ }
99938
+ };
99939
+ };
99940
+ recordEntryChildren = (record5, entryResponse) => ({
99941
+ ...record5,
99942
+ phase: "active",
99943
+ members: record5.members.map((member, index) => ({
99944
+ ...member,
99945
+ // The entry is member 0 of the action; its children follow in order.
99946
+ orderId: member.orderId ?? restingOrderIdAt(entryResponse, index + 1)
99947
+ }))
99948
+ });
99949
+ observeMembers = (record5, page) => record5.members.map((member) => ({
99950
+ member,
99951
+ row: member.orderId == null ? null : page.find((order) => order.oid === member.orderId) ?? null
99952
+ }));
99953
+ UNKNOWN_ORDER_RESPONSE = "unknownOid";
99954
+ resolveUnknownOrderIds = async (record5, io, unknownClientOrderIds = /* @__PURE__ */ new Set()) => {
99955
+ const members = [];
99956
+ for (const member of record5.members) {
99957
+ if (member.pendingModify) {
99958
+ const pending3 = member.pendingModify;
99959
+ const evidence2 = await io.readOrderStatus(pending3.clientOrderId);
99960
+ const orderId2 = Number(evidence2.orderId);
99961
+ if (evidence2.responseValid && evidence2.orderMatches && Number.isSafeInteger(orderId2) && orderId2 > 0) {
99962
+ const { pendingModify: _settled, ...rest } = member;
99963
+ members.push({
99964
+ ...rest,
99965
+ clientOrderId: pending3.clientOrderId,
99966
+ orderId: orderId2,
99967
+ trigger: pending3.trigger,
99968
+ placedAtMs: evidence2.orderTimestampMs ?? null,
99969
+ sentAtMs: pending3.sentAtMs
99970
+ });
99971
+ } else if (evidence2.responseStatus === UNKNOWN_ORDER_RESPONSE && io.nowMs() > io.neverLandsAfterMs(pending3.sentAtMs)) {
99972
+ const { pendingModify: _neverLanded, ...rest } = member;
99973
+ members.push(rest);
99974
+ } else {
99975
+ members.push(member);
99976
+ }
99977
+ continue;
99978
+ }
99979
+ if (member.orderId != null || member.retiredReason) {
99980
+ members.push(member);
99981
+ continue;
99982
+ }
99983
+ const evidence = await io.readOrderStatus(member.clientOrderId);
99984
+ if (evidence.responseStatus === UNKNOWN_ORDER_RESPONSE) unknownClientOrderIds.add(member.clientOrderId);
99985
+ const orderId = Number(evidence.orderId);
99986
+ members.push(
99987
+ evidence.responseValid && evidence.orderMatches && Number.isSafeInteger(orderId) && orderId > 0 ? { ...member, orderId, placedAtMs: evidence.orderTimestampMs ?? member.placedAtMs } : member
99988
+ );
99989
+ }
99990
+ return { ...record5, members };
99991
+ };
99992
+ settleNativeProtectionAfterFill = async (input) => {
99993
+ const { io } = input;
99994
+ const reports = [];
99995
+ const unknownClientOrderIds = /* @__PURE__ */ new Set();
99996
+ let record5 = await resolveUnknownOrderIds(input.record, io, unknownClientOrderIds);
99997
+ const page = await io.readOpenOrders();
99998
+ const position = await io.readPosition();
99999
+ const symbol2 = record5.symbol;
100000
+ if (!isOpenInDirection2(position.size, record5.isLong)) {
100001
+ reports.push({
100002
+ order_id: input.entryOrderId,
100003
+ symbol: symbol2,
100004
+ action: "PROTECTIVE_RECONCILIATION",
100005
+ status: "blocked",
100006
+ execution_metadata: {
100007
+ reason_code: position.size === 0 ? "protective_position_flat" : "protective_position_drift",
100008
+ live_position_size: position.size
100009
+ }
100010
+ });
100011
+ return { record: { ...record5, phase: "active" }, reports };
100012
+ }
100013
+ const observations = observeMembers(record5, page);
100014
+ const restingTrigger = (kind) => {
100015
+ const observed = observations.find((entry) => entry.member.kind === kind);
100016
+ return observed?.row?.trigger_px != null ? String(observed.row.trigger_px) : null;
100017
+ };
100018
+ if (position.entryPrice == null) {
100019
+ reports.push({
100020
+ order_id: input.entryOrderId,
100021
+ symbol: symbol2,
100022
+ action: "PROTECTIVE_RECONCILIATION",
100023
+ status: "failed",
100024
+ execution_metadata: { reason_code: "protective_position_entry_unresolved" }
100025
+ });
100026
+ return { record: record5, reports };
100027
+ }
100028
+ const actions = nativeAfterFillActions({
100029
+ settings: { ...input.settings, stopLoss: input.settings.stopLoss && { ...input.settings.stopLoss, trailing: false } },
100030
+ isLong: record5.isLong,
100031
+ sizeDecimals: input.sizeDecimals,
100032
+ position: { size: position.size, entryPrice: position.entryPrice },
100033
+ fillSize: input.fillSize,
100034
+ resting: { sl: restingTrigger("sl"), tp: restingTrigger("tp") }
100035
+ });
100036
+ let eventMs = Math.max(
100037
+ 0,
100038
+ ...observations.map((entry) => entry.row?.timestamp ?? entry.member.placedAtMs ?? 0)
100039
+ );
100040
+ if (eventMs <= 0 && input.entryOrderId) {
100041
+ const entryStatus = await io.readOrderStatus(input.entryOrderId);
100042
+ eventMs = entryStatus.statusTimestampMs ?? 0;
100043
+ }
100044
+ const gate = nativePlacementGate({
100045
+ eventMs,
100046
+ position: position.size,
100047
+ positionStateMs: position.stateTimeMs ?? Number.NEGATIVE_INFINITY,
100048
+ isLong: record5.isLong
100049
+ });
100050
+ const members = [...record5.members];
100051
+ for (const step of actions) {
100052
+ if (step.action === "place_trailing") continue;
100053
+ const index = members.findIndex((member) => member.kind === step.kind);
100054
+ const existing = index >= 0 ? members[index] : null;
100055
+ if (existing?.userCancelledOrderId != null || existing?.retiredReason) continue;
100056
+ const clientOrderId = clientOrderIdForMutation(io.newMutationId());
100057
+ if (step.action === "modify") {
100058
+ const row = observations.find((entry) => entry.member.kind === step.kind)?.row;
100059
+ if (!row) continue;
100060
+ const sentAtMs2 = io.nowMs();
100061
+ members[index] = {
100062
+ ...members[index],
100063
+ orderId: row.oid,
100064
+ pendingModify: { clientOrderId, trigger: step.trigger, sentAtMs: sentAtMs2 }
100065
+ };
100066
+ if (!io.persist({ ...record5, phase: "active", members })) {
100067
+ members[index] = existing;
100068
+ reports.push({
100069
+ order_id: String(row.oid),
100070
+ symbol: symbol2,
100071
+ action: actionOf(step.kind),
100072
+ status: "failed",
100073
+ execution_metadata: { reason_code: "protective_lifecycle_persistence_failed", trigger_price: step.trigger }
100074
+ });
100075
+ continue;
100076
+ }
100077
+ const outcome2 = await attempt(io, () => io.modifyPositionOrder({
100078
+ orderId: row.oid,
100079
+ kind: step.kind,
100080
+ triggerPrice: Number(step.trigger),
100081
+ clientOrderId
100082
+ }));
100083
+ if (!outcome2.ok && outcome2.refused) {
100084
+ members[index] = { ...existing, orderId: row.oid };
100085
+ reports.push({
100086
+ order_id: String(row.oid),
100087
+ symbol: symbol2,
100088
+ action: actionOf(step.kind),
100089
+ status: "failed",
100090
+ execution_metadata: {
100091
+ reason_code: outcome2.error instanceof NativeOrderNotSentError ? "protective_modify_not_sent" : "protective_modify_rejected",
100092
+ trigger_price: step.trigger,
100093
+ error: errorText(outcome2.error)
100094
+ }
100095
+ });
100096
+ continue;
100097
+ }
100098
+ const newOrderId = outcome2.ok ? restingOrderIdAt(outcome2.response, 0) : null;
100099
+ if (newOrderId != null) {
100100
+ const { pendingModify: _applied, ...rest } = members[index];
100101
+ members[index] = { ...rest, clientOrderId, orderId: newOrderId, trigger: step.trigger, placedAtMs: null, sentAtMs: sentAtMs2 };
100102
+ }
100103
+ reports.push({
100104
+ order_id: String(newOrderId ?? row.oid),
100105
+ symbol: symbol2,
100106
+ action: actionOf(step.kind),
100107
+ status: newOrderId != null ? "executed" : "failed",
100108
+ execution_metadata: {
100109
+ reason_code: newOrderId != null ? "protective_native_moved_to_position_entry" : "protective_modify_outcome_unknown",
100110
+ trigger_price: step.trigger,
100111
+ position_tpsl: true,
100112
+ protected_size: Math.abs(position.size),
100113
+ ...newOrderId != null ? { replaced_order_id: String(row.oid) } : {}
100114
+ }
100115
+ });
100116
+ continue;
100117
+ }
100118
+ if (existing != null && existing.orderId == null && !unknownClientOrderIds.has(existing.clientOrderId)) {
100119
+ continue;
100120
+ }
100121
+ if (gate !== "place") {
100122
+ reports.push({
100123
+ order_id: input.entryOrderId,
100124
+ symbol: symbol2,
100125
+ action: actionOf(step.kind),
100126
+ status: "failed",
100127
+ execution_metadata: {
100128
+ reason_code: gate === "need_reads" ? "protective_position_evidence_stale" : "protective_position_flat"
100129
+ }
100130
+ });
100131
+ continue;
100132
+ }
100133
+ const sentAtMs = io.nowMs();
100134
+ const journaled = {
100135
+ kind: step.kind,
100136
+ clientOrderId,
100137
+ orderId: null,
100138
+ trigger: step.trigger,
100139
+ placedAtMs: null,
100140
+ sentAtMs,
100141
+ replacedOnce: existing?.replacedOnce ?? false
100142
+ };
100143
+ const before = [...members];
100144
+ if (index >= 0) members[index] = journaled;
100145
+ else members.push(journaled);
100146
+ if (!io.persist({ ...record5, phase: "active", members })) {
100147
+ members.splice(0, members.length, ...before);
100148
+ reports.push({
100149
+ order_id: null,
100150
+ symbol: symbol2,
100151
+ action: actionOf(step.kind),
100152
+ status: "failed",
100153
+ execution_metadata: { reason_code: "protective_lifecycle_persistence_failed", trigger_price: step.trigger }
100154
+ });
100155
+ continue;
100156
+ }
100157
+ const outcome = await notSentRestores(
100158
+ () => attempt(io, () => io.placePositionOrder({
100159
+ kind: step.kind,
100160
+ triggerPrice: Number(step.trigger),
100161
+ clientOrderId
100162
+ })),
100163
+ () => io.persist({ ...record5, phase: "active", members: before })
100164
+ );
100165
+ if (!outcome.ok && outcome.refused) {
100166
+ members.splice(0, members.length, ...before);
100167
+ reports.push({
100168
+ order_id: null,
100169
+ symbol: symbol2,
100170
+ action: actionOf(step.kind),
100171
+ status: "failed",
100172
+ execution_metadata: {
100173
+ reason_code: outcome.error instanceof NativeOrderNotSentError ? "protective_place_not_sent" : "protective_place_rejected",
100174
+ trigger_price: step.trigger,
100175
+ error: errorText(outcome.error)
100176
+ }
100177
+ });
100178
+ continue;
100179
+ }
100180
+ const placed = {
100181
+ ...journaled,
100182
+ orderId: outcome.ok ? restingOrderIdAt(outcome.response, 0) : null
100183
+ };
100184
+ if (index >= 0) members[index] = placed;
100185
+ else members[members.length - 1] = placed;
100186
+ reports.push({
100187
+ order_id: placed.orderId == null ? null : String(placed.orderId),
100188
+ symbol: symbol2,
100189
+ action: actionOf(step.kind),
100190
+ status: "executed",
100191
+ execution_metadata: {
100192
+ trigger_price: step.trigger,
100193
+ position_tpsl: true,
100194
+ protected_size: Math.abs(position.size)
100195
+ }
100196
+ });
100197
+ }
100198
+ for (const entry of observations) {
100199
+ if (!entry.row || reports.some((report) => report.order_id === String(entry.row?.oid))) continue;
100200
+ reports.push({
100201
+ order_id: String(entry.row.oid),
100202
+ symbol: symbol2,
100203
+ action: actionOf(entry.member.kind),
100204
+ status: "executed",
100205
+ execution_metadata: {
100206
+ trigger_price: entry.member.trigger,
100207
+ position_tpsl: true,
100208
+ protected_size: Math.abs(position.size)
100209
+ }
100210
+ });
100211
+ }
100212
+ record5 = { ...record5, phase: "active", members };
100213
+ return { record: record5, reports };
100214
+ };
100215
+ reconcileNativeProtection = async (input) => {
100216
+ const { io } = input;
100217
+ const reports = [];
100218
+ const unknownClientOrderIds = /* @__PURE__ */ new Set();
100219
+ let record5 = await resolveUnknownOrderIds(input.record, io, unknownClientOrderIds);
100220
+ const page = await io.readOpenOrders();
100221
+ const position = await io.readPosition();
100222
+ const symbol2 = record5.symbol;
100223
+ const stateMs = position.stateTimeMs ?? Number.NEGATIVE_INFINITY;
100224
+ const observations = observeMembers(record5, page).map((entry) => ({
100225
+ ...entry,
100226
+ member: entry.row ? { ...entry.member, placedAtMs: entry.row.timestamp || entry.member.placedAtMs } : entry.member
100227
+ }));
100228
+ const members = [];
100229
+ let anyResting = false;
100230
+ const positionOpen = isOpenInDirection2(position.size, record5.isLong);
100231
+ const currentTrigger = (member) => {
100232
+ const setting = member.kind === "sl" ? input.settings.stopLoss : input.settings.takeProfit;
100233
+ return setting && position.entryPrice != null ? nativePositionTriggerPrice({
100234
+ averageEntry: position.entryPrice,
100235
+ positionSize: position.size,
100236
+ isLong: record5.isLong,
100237
+ kind: member.kind,
100238
+ mode: setting.mode,
100239
+ value: setting.value,
100240
+ sizeDecimals: input.sizeDecimals
100241
+ }) : null;
100242
+ };
100243
+ const placeMember = async (args) => {
100244
+ const gate = nativePlacementGate({
100245
+ eventMs: args.eventMs,
100246
+ position: position.size,
100247
+ positionStateMs: stateMs,
100248
+ isLong: record5.isLong
100249
+ });
100250
+ if (gate !== "place") return args.member;
100251
+ const clientOrderId = clientOrderIdForMutation(io.newMutationId());
100252
+ const sentAtMs = io.nowMs();
100253
+ const journaled = {
100254
+ kind: args.member.kind,
100255
+ clientOrderId,
100256
+ orderId: null,
100257
+ trigger: args.trigger,
100258
+ placedAtMs: null,
100259
+ sentAtMs,
100260
+ replacedOnce: args.replacedOnce
100261
+ };
100262
+ if (!io.persist({
100263
+ ...record5,
100264
+ members: [
100265
+ ...members,
100266
+ journaled,
100267
+ ...observations.slice(args.observationIndex + 1).map((entry) => entry.member)
100268
+ ]
100269
+ })) {
100270
+ reports.push({
100271
+ order_id: args.member.orderId == null ? null : String(args.member.orderId),
100272
+ symbol: symbol2,
100273
+ action: actionOf(args.member.kind),
100274
+ status: "failed",
100275
+ execution_metadata: { reason_code: "protective_lifecycle_persistence_failed", trigger_price: args.trigger }
100276
+ });
100277
+ return args.member;
100278
+ }
100279
+ const outcome = await notSentRestores(
100280
+ () => attempt(io, () => io.placePositionOrder({
100281
+ kind: args.member.kind,
100282
+ triggerPrice: Number(args.trigger),
100283
+ clientOrderId
100284
+ })),
100285
+ () => io.persist({
100286
+ ...record5,
100287
+ members: [
100288
+ ...members,
100289
+ args.member,
100290
+ ...observations.slice(args.observationIndex + 1).map((entry) => entry.member)
100291
+ ]
100292
+ })
100293
+ );
100294
+ if (!outcome.ok && outcome.error instanceof NativeOrderNotSentError) {
100295
+ io.persist({
100296
+ ...record5,
100297
+ members: [
100298
+ ...members,
100299
+ args.member,
100300
+ ...observations.slice(args.observationIndex + 1).map((entry) => entry.member)
100301
+ ]
100302
+ });
100303
+ reports.push({
100304
+ order_id: args.member.orderId == null ? null : String(args.member.orderId),
100305
+ symbol: symbol2,
100306
+ action: actionOf(args.member.kind),
100307
+ status: "failed",
100308
+ execution_metadata: {
100309
+ reason_code: "protective_place_not_sent",
100310
+ trigger_price: args.trigger,
100311
+ error: errorText(outcome.error)
100312
+ }
100313
+ });
100314
+ return args.member;
100315
+ }
100316
+ const refused = !outcome.ok && outcome.refused;
100317
+ const placed = {
100318
+ kind: args.member.kind,
100319
+ clientOrderId: refused ? args.member.clientOrderId : clientOrderId,
100320
+ orderId: refused ? args.member.orderId : outcome.ok ? restingOrderIdAt(outcome.response, 0) : null,
100321
+ trigger: refused ? args.member.trigger : args.trigger,
100322
+ placedAtMs: null,
100323
+ sentAtMs: refused ? args.member.sentAtMs : sentAtMs,
100324
+ replacedOnce: args.replacedOnce,
100325
+ ...refused ? { retiredReason: "protective_replacement_rejected" } : {}
100326
+ };
100327
+ reports.push({
100328
+ order_id: placed.orderId == null ? null : String(placed.orderId),
100329
+ symbol: symbol2,
100330
+ action: actionOf(args.member.kind),
100331
+ status: refused ? "failed" : "executed",
100332
+ execution_metadata: {
100333
+ reason_code: refused ? "protective_replacement_rejected" : args.reasonCode,
100334
+ ...args.member.orderId != null ? { replaced_order_id: String(args.member.orderId) } : {},
100335
+ trigger_price: args.trigger,
100336
+ position_tpsl: true,
100337
+ protected_size: Math.abs(position.size),
100338
+ ...refused ? { error: errorText(outcome.error) } : {}
100339
+ }
100340
+ });
100341
+ return placed;
100342
+ };
100343
+ for (const [observationIndex, { member, row }] of observations.entries()) {
100344
+ if (row) {
100345
+ const stray = nativeStrayOrderDecision({
100346
+ placedMs: member.placedAtMs ?? Number.POSITIVE_INFINITY,
100347
+ position: position.size,
100348
+ positionStateMs: stateMs,
100349
+ isLong: record5.isLong
100350
+ });
100351
+ if (stray === "cancel") {
100352
+ const outcome = await attempt(io, () => io.cancelOrder(row.oid));
100353
+ reports.push({
100354
+ order_id: String(row.oid),
100355
+ symbol: symbol2,
100356
+ action: actionOf(member.kind),
100357
+ status: outcome.ok ? "executed" : "failed",
100358
+ execution_metadata: {
100359
+ reason_code: outcome.ok ? "protective_native_stray_cancelled" : "protective_native_stray_cancel_failed",
100360
+ live_position_size: position.size,
100361
+ ...outcome.ok ? {} : { error: errorText(outcome.error) }
100362
+ }
100363
+ });
100364
+ if (!outcome.ok) {
100365
+ anyResting = true;
100366
+ members.push(member);
100367
+ }
100368
+ continue;
100369
+ }
100370
+ anyResting = true;
100371
+ members.push(member);
100372
+ continue;
100373
+ }
100374
+ if (member.retiredReason || member.userCancelledOrderId != null) {
100375
+ members.push(member);
100376
+ continue;
100377
+ }
100378
+ if (member.pendingModify) {
100379
+ anyResting = true;
100380
+ members.push(member);
100381
+ continue;
100382
+ }
100383
+ if (member.orderId == null) {
100384
+ if (io.nowMs() <= io.neverLandsAfterMs(member.sentAtMs) || !unknownClientOrderIds.has(member.clientOrderId)) {
100385
+ anyResting = true;
100386
+ members.push(member);
100387
+ continue;
100388
+ }
100389
+ if (!positionOpen) continue;
100390
+ const placed = await placeMember({
100391
+ member,
100392
+ trigger: currentTrigger(member) ?? member.trigger,
100393
+ replacedOnce: member.replacedOnce,
100394
+ eventMs: Number.NEGATIVE_INFINITY,
100395
+ reasonCode: "protective_order_never_landed_placed",
100396
+ observationIndex
100397
+ });
100398
+ members.push(placed);
100399
+ if (!placed.retiredReason) anyResting = true;
100400
+ continue;
100401
+ }
100402
+ if (!positionOpen) {
100403
+ let explained;
100404
+ if (member.placedAtMs != null) {
100405
+ explained = explainAbsentProtectiveOrder({
100406
+ lastSeenRestingMs: member.placedAtMs,
100407
+ position: position.size,
100408
+ positionStateMs: stateMs,
100409
+ isLong: record5.isLong
100410
+ });
100411
+ } else {
100412
+ const evidence2 = await io.readOrderStatus(member.orderId);
100413
+ const end2 = classifyNativeOrderEnd({
100414
+ orderStatus: evidence2.responseValid ? String(evidence2.orderStatus ?? "") : "",
100415
+ replacedByOwnModify: false,
100416
+ userCancelledThroughVtx: false
100417
+ });
100418
+ explained = end2 === "resting" || end2 === "pending" || end2 === "unknown" ? "status_read" : "ended_with_position";
100419
+ }
100420
+ if (explained !== "ended_with_position") {
100421
+ anyResting = true;
100422
+ members.push(member);
100423
+ }
100424
+ continue;
100425
+ }
100426
+ const evidence = await io.readOrderStatus(member.orderId);
100427
+ const end = classifyNativeOrderEnd({
100428
+ orderStatus: evidence.responseValid ? String(evidence.orderStatus ?? "") : "",
100429
+ replacedByOwnModify: false,
100430
+ userCancelledThroughVtx: false
100431
+ });
100432
+ if (end === "resting" || end === "pending" || end === "unknown" || end === "superseded" || end === "user_cancelled") {
100433
+ members.push(member);
100434
+ continue;
100435
+ }
100436
+ if (end === "fired" || end === "ended_with_position") {
100437
+ continue;
100438
+ }
100439
+ if (end === "lost_permanent" || member.replacedOnce) {
100440
+ members.push({ ...member, retiredReason: end === "lost_permanent" ? "protective_stop_execution_rejected" : "protective_replacement_lost" });
100441
+ reports.push({
100442
+ order_id: String(member.orderId),
100443
+ symbol: symbol2,
100444
+ action: actionOf(member.kind),
100445
+ status: "failed",
100446
+ execution_metadata: {
100447
+ reason_code: end === "lost_permanent" ? "protective_stop_execution_rejected" : "protective_replacement_lost",
100448
+ order_status: evidence.orderStatus,
100449
+ manual_intervention: true
100450
+ }
100451
+ });
100452
+ continue;
100453
+ }
100454
+ if (member.kind === "tp") {
100455
+ members.push({ ...member, retiredReason: "protective_take_profit_lost" });
100456
+ continue;
100457
+ }
100458
+ const trigger = currentTrigger(member) ?? member.trigger;
100459
+ const replacement = await placeMember({
100460
+ member,
100461
+ trigger,
100462
+ replacedOnce: true,
100463
+ eventMs: evidence.statusTimestampMs ?? Number.POSITIVE_INFINITY,
100464
+ reasonCode: "protective_stop_replaced",
100465
+ observationIndex
100466
+ });
100467
+ members.push(replacement);
100468
+ if (replacement !== member && !replacement.retiredReason) anyResting = true;
100469
+ }
100470
+ if (!positionOpen && !anyResting) {
100471
+ return { record: null, reports };
100472
+ }
100473
+ record5 = { ...record5, members };
100474
+ return { record: record5, reports };
100475
+ };
100476
+ }
100477
+ });
100478
+
99560
100479
  // lib/runtime/runtime-execution.ts
99561
100480
  function capCopiedToActual(copied, actual) {
99562
100481
  if (Math.abs(copied) <= COPY_TRADING_SIZE_EPSILON) return 0;
@@ -99592,7 +100511,7 @@ function copiedTargetNow(reconciliation, recordedTarget, actualPosition) {
99592
100511
  );
99593
100512
  return { copiedNow, targetNow, kept: copiedTargetBesideOwnPosition(targetNow, copiedNow, actualPosition) };
99594
100513
  }
99595
- var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, _extractOrderResponseStates, createRuntimeId, _extractFilledSize, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, withCapacityTrim, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked, executeClientCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction;
100514
+ var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, _extractOrderResponseStates, createRuntimeId, _extractFilledSize, firstMemberAcknowledgement, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionListings, runtimeProtectionListing, resolveServerNativeEntry, SERVER_NATIVE_LEGACY_REFUSAL, isServerNativeLegacyRefusal, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, withCapacityTrim, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked, executeClientCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction;
99596
100515
  var init_runtime_execution = __esm({
99597
100516
  "lib/runtime/runtime-execution.ts"() {
99598
100517
  "use strict";
@@ -99621,6 +100540,8 @@ var init_runtime_execution = __esm({
99621
100540
  init_protective_stop_replacement();
99622
100541
  init_protective_entry_cover();
99623
100542
  init_error_surface_contract();
100543
+ init_native_position_protection();
100544
+ init_native_protection_device();
99624
100545
  init_runtime_handoff();
99625
100546
  clientProtectiveMutationAuthority = (request) => request.mutationAuthority === "manual_session" ? {} : {
99626
100547
  runtimeSessionId: request.sessionId || "__missing_runtime_session__",
@@ -99740,6 +100661,12 @@ var init_runtime_execution = __esm({
99740
100661
  walk(value);
99741
100662
  return found ? total : null;
99742
100663
  };
100664
+ firstMemberAcknowledgement = (payload) => {
100665
+ const root = payload;
100666
+ const statuses = root?.response?.data?.statuses;
100667
+ if (!root || !Array.isArray(statuses) || statuses.length === 0) return payload;
100668
+ return { ...root, response: { ...root.response, data: { ...root.response?.data, statuses: [statuses[0]] } } };
100669
+ };
99743
100670
  _extractOrderId = (value) => {
99744
100671
  const seen = /* @__PURE__ */ new Set();
99745
100672
  const walk = (node) => {
@@ -99830,6 +100757,7 @@ var init_runtime_execution = __esm({
99830
100757
  setClientRuntimeProtectionStorage = (storage3) => {
99831
100758
  if (clientRuntimeProtectionStorage === storage3) return;
99832
100759
  clientRuntimeProtectionStorage = storage3;
100760
+ setNativeProtectionStorage(storage3);
99833
100761
  trailingStopMemory.clear();
99834
100762
  protectiveGroupMemory.clear();
99835
100763
  protectiveGroupReadFailures.clear();
@@ -100274,7 +101202,7 @@ var init_runtime_execution = __esm({
100274
101202
  if (status != null && status !== HTTP_STATUS.UNAUTHORIZED && status !== HTTP_STATUS.FORBIDDEN) return false;
100275
101203
  return normalized.includes("runtime lease required") || normalized.includes("invalid or expired runtime lease") || normalized.includes("runtime lease no longer resolves to an active profile") || normalized.includes("runtime lease does not match the requested runtime session");
100276
101204
  };
100277
- hasClientRuntimeProtectionState = (profileId, symbol2) => readClientProtectiveGroups(String(profileId).trim(), symbol2).length > 0 || hasClientProtectiveGroupReadFailure(String(profileId).trim(), symbol2);
101205
+ hasClientRuntimeProtectionState = (profileId, symbol2) => readClientProtectiveGroups(String(profileId).trim(), symbol2).length > 0 || hasClientProtectiveGroupReadFailure(String(profileId).trim(), symbol2) || readNativeRecord(String(profileId).trim(), symbol2).kind !== "none";
100278
101206
  clearClientRuntimeVetoedProtectiveIntent = (input) => {
100279
101207
  const profileId = String(input.profileId).trim();
100280
101208
  const symbol2 = String(input.symbol).trim();
@@ -103145,6 +104073,175 @@ var init_runtime_execution = __esm({
103145
104073
  }
103146
104074
  writeTrackedTrailingStops(profileId, symbol2, records.map((record5) => orderIds.has(String(record5.orderId)) ? { ...record5, positionTpsl: false } : record5));
103147
104075
  };
104076
+ nativeSettingsOf = (context) => nativeProtectionSettings({
104077
+ tpSlEnabled: context.tpSlEnabled === true,
104078
+ stopLossEnabled: context.stopLossEnabled !== false,
104079
+ stopLossType: context.stopLossType === "trailing" ? "trailing" : "fixed",
104080
+ stopLossMode: context.stopLossMode === "usdc" ? "usdc" : "percent",
104081
+ stopLossPct: toPositiveNumber(context.stopLossPct),
104082
+ stopLossUsdc: toPositiveNumber(context.stopLossUsdc),
104083
+ takeProfitEnabled: context.takeProfitEnabled !== false,
104084
+ takeProfitMode: context.takeProfitMode === "usdc" ? "usdc" : "percent",
104085
+ takeProfitPct: toPositiveNumber(context.takeProfitPct),
104086
+ takeProfitUsdc: toPositiveNumber(context.takeProfitUsdc)
104087
+ });
104088
+ nativePassEnded = (request, error48) => Boolean(request.signal?.aborted) || isClientRuntimeWindowHandoffBeforePlanDispatch(error48 instanceof NativeOrderNotSentError ? error48.cause : error48);
104089
+ nativeProtectionIo = (request, isLong) => {
104090
+ const symbol2 = request.executionContext.symbol;
104091
+ const walletAddress = String(request.executionContext.walletAddress || "").trim();
104092
+ const exitSide = isLong ? "sell" : "buy";
104093
+ const common = {
104094
+ profileId: request.profileId,
104095
+ ...clientProtectiveMutationAuthority(request),
104096
+ walletAddress,
104097
+ config: request.config ?? null,
104098
+ signal: request.signal,
104099
+ signingKey: request.signingKey,
104100
+ symbol: symbol2
104101
+ };
104102
+ const mutationOf = (clientOrderId) => {
104103
+ const mutationId = mutationIdForClientOrderId(clientOrderId);
104104
+ if (!mutationId) throw new Error("Native protective order id is malformed.");
104105
+ return mutationId;
104106
+ };
104107
+ const fenced = (call) => withDispatchBoundary(
104108
+ (onDispatched) => call(() => {
104109
+ request.onExchangeOrderDispatched?.("protection");
104110
+ onDispatched();
104111
+ })
104112
+ );
104113
+ return {
104114
+ readPosition: async () => {
104115
+ const snapshot = await fetchBrowserPositionSnapshot(
104116
+ request.config ?? {},
104117
+ walletAddress,
104118
+ symbol2,
104119
+ request.signal,
104120
+ "trading_reduce"
104121
+ );
104122
+ return { size: snapshot.size, entryPrice: snapshot.entryPrice, stateTimeMs: snapshot.stateTimeMs };
104123
+ },
104124
+ readOpenOrders: () => fetchClientRuntimeOpenOrders(request, "trading_reduce"),
104125
+ readOrderStatus: (orderId) => fetchBrowserOrderStatusEvidence({
104126
+ publicRequestPriority: "trading_reduce",
104127
+ config: request.config ?? null,
104128
+ walletAddress,
104129
+ signal: request.signal,
104130
+ orderId
104131
+ }),
104132
+ placePositionOrder: ({ kind, triggerPrice, clientOrderId }) => fenced((onExchangeOrderDispatched) => executeClientOrderBatch({
104133
+ ...common,
104134
+ onExchangeOrderDispatched,
104135
+ mutationId: mutationOf(clientOrderId),
104136
+ clientOrderId,
104137
+ grouping: "positionTpsl",
104138
+ members: [{
104139
+ side: exitSide,
104140
+ size: 0,
104141
+ limitPrice: triggerPrice,
104142
+ orderKind: "trigger",
104143
+ reduceOnly: true,
104144
+ triggerPrice,
104145
+ triggerKind: kind,
104146
+ triggerIsMarket: true,
104147
+ positionOrder: true,
104148
+ clientOrderId
104149
+ }]
104150
+ })),
104151
+ modifyPositionOrder: ({ orderId, kind, triggerPrice, clientOrderId }) => fenced((onExchangeOrderDispatched) => executeClientModifyOrder({
104152
+ ...common,
104153
+ onExchangeOrderDispatched,
104154
+ mutationId: mutationOf(clientOrderId),
104155
+ clientOrderId,
104156
+ orderId,
104157
+ side: exitSide,
104158
+ size: 0,
104159
+ limitPrice: triggerPrice,
104160
+ orderKind: "trigger",
104161
+ reduceOnly: true,
104162
+ triggerPrice,
104163
+ triggerKind: kind,
104164
+ triggerIsMarket: true,
104165
+ positionOrder: true
104166
+ })),
104167
+ cancelOrder: (orderId) => fenced((onExchangeOrderDispatched) => executeClientCancelOrder({
104168
+ ...common,
104169
+ onExchangeOrderDispatched,
104170
+ publicRequestPriority: "trading_reduce",
104171
+ orderId
104172
+ })),
104173
+ isDefinitiveRefusal: (error48) => error48 instanceof HyperliquidExchangeRejectionError || error48 instanceof NativeOrderNotSentError,
104174
+ neverLandsAfterMs: (sentAtMs) => clientOrderNeverLandsAfterMs(request.config, { kind: "absent", ageStartMs: sentAtMs }),
104175
+ newMutationId: () => createRuntimeId().toLowerCase(),
104176
+ nowMs: () => Date.now(),
104177
+ persist: (record5) => writeNativeProtectionRecord(String(request.profileId).trim(), symbol2, record5),
104178
+ endsPass: (error48) => nativePassEnded(request, error48)
104179
+ };
104180
+ };
104181
+ nativeStorageReport = (symbol2, reasonCode) => ({
104182
+ order_id: null,
104183
+ symbol: symbol2,
104184
+ action: "PROTECTIVE_RECONCILIATION",
104185
+ status: "failed",
104186
+ execution_metadata: { reason_code: reasonCode }
104187
+ });
104188
+ readNativeRecord = (profileId, symbol2) => {
104189
+ try {
104190
+ const record5 = readNativeProtectionRecord(profileId, symbol2);
104191
+ return record5 == null ? { kind: "none" } : { kind: "record", record: record5 };
104192
+ } catch {
104193
+ return { kind: "invalid" };
104194
+ }
104195
+ };
104196
+ reconcileNativeProtectionForDecision = async (request) => {
104197
+ const profileId = String(request.profileId).trim();
104198
+ const symbol2 = request.executionContext.symbol;
104199
+ const read = readNativeRecord(profileId, symbol2);
104200
+ if (read.kind === "none") return [];
104201
+ if (read.kind === "invalid") return [nativeStorageReport(symbol2, "protective_lifecycle_storage_invalid")];
104202
+ const wallet = String(request.executionContext.walletAddress || "").trim().toLowerCase();
104203
+ if (read.record.walletAddress !== wallet) return [nativeStorageReport(symbol2, "protective_wallet_mismatch")];
104204
+ try {
104205
+ const io = nativeProtectionIo(request, read.record.isLong);
104206
+ if (read.record.phase === "entry_pending") {
104207
+ const settled = await settleNativeProtectionAfterFill({
104208
+ record: read.record,
104209
+ settings: nativeSettingsOf(request.executionContext),
104210
+ sizeDecimals: request.executionContext.sizeDecimals,
104211
+ fillSize: "0",
104212
+ entryOrderId: read.record.entryClientOrderId,
104213
+ io
104214
+ });
104215
+ const reports2 = [...settled.reports];
104216
+ if (!writeNativeProtectionRecord(profileId, symbol2, settled.record)) {
104217
+ reports2.push(nativeStorageReport(symbol2, "protective_lifecycle_persistence_failed"));
104218
+ }
104219
+ return reports2;
104220
+ }
104221
+ const result = await reconcileNativeProtection({
104222
+ record: read.record,
104223
+ settings: nativeSettingsOf(request.executionContext),
104224
+ sizeDecimals: request.executionContext.sizeDecimals,
104225
+ io
104226
+ });
104227
+ const reports = [...result.reports];
104228
+ if (!writeNativeProtectionRecord(profileId, symbol2, result.record)) {
104229
+ reports.push(nativeStorageReport(symbol2, "protective_lifecycle_persistence_failed"));
104230
+ }
104231
+ return reports;
104232
+ } catch (error48) {
104233
+ if (nativePassEnded(request, error48)) {
104234
+ throw error48 instanceof NativeOrderNotSentError ? error48.cause : error48;
104235
+ }
104236
+ return [{
104237
+ ...nativeStorageReport(symbol2, "protective_open_orders_unresolved"),
104238
+ execution_metadata: {
104239
+ reason_code: "protective_open_orders_unresolved",
104240
+ error: getSanitizedRuntimeErrorMessage(error48) || "Unable to read native protection."
104241
+ }
104242
+ }];
104243
+ }
104244
+ };
103148
104245
  reconcileClientProtectiveGroups = async (request, knownPositionSize) => {
103149
104246
  const profileId = String(request.profileId).trim();
103150
104247
  const symbol2 = request.executionContext.symbol;
@@ -104899,10 +105996,9 @@ var init_runtime_execution = __esm({
104899
105996
  runtimeDeviceId: request.runtimeDeviceId,
104900
105997
  schedulerInstanceId: request.schedulerInstanceId
104901
105998
  });
104902
- runtimeProtectionOwners = /* @__PURE__ */ new WeakMap();
104903
- resolveRuntimeProtectionOwner = (request) => {
104904
- if (request.executionMode === "server") return Promise.resolve("server");
104905
- const cached2 = runtimeProtectionOwners.get(request);
105999
+ runtimeProtectionListings = /* @__PURE__ */ new WeakMap();
106000
+ runtimeProtectionListing = (request) => {
106001
+ const cached2 = runtimeProtectionListings.get(request);
104906
106002
  if (cached2) return cached2;
104907
106003
  const authority = runtimeProtectionAuthority(request);
104908
106004
  const pending3 = listClientProtectiveActions(
@@ -104911,7 +106007,49 @@ var init_runtime_execution = __esm({
104911
106007
  authority.runtimeLeaseToken,
104912
106008
  authority.runtimeDeviceId,
104913
106009
  authority.schedulerInstanceId
104914
- ).then((listed) => listed.client_protection_owner);
106010
+ );
106011
+ runtimeProtectionListings.set(request, pending3);
106012
+ return pending3;
106013
+ };
106014
+ resolveServerNativeEntry = async (input) => {
106015
+ let state2;
106016
+ try {
106017
+ state2 = readServerNativeProtectionState(await runtimeProtectionListing(input.request));
106018
+ } catch {
106019
+ return null;
106020
+ }
106021
+ if (state2 == null || !state2.enabled) return null;
106022
+ const settings = nativeSettingsOf(input.request.executionContext);
106023
+ if (settings.stopLoss?.trailing) return null;
106024
+ const symbol2 = normalizeHyperliquidMarketSymbol(input.request.executionContext.symbol);
106025
+ const request = nativeEntryRequest({
106026
+ settings,
106027
+ isLong: input.isLong,
106028
+ sizeDecimals: input.request.executionContext.sizeDecimals,
106029
+ referencePrice: input.referencePrice,
106030
+ entrySize: input.entrySize,
106031
+ positionBefore: input.positionBefore,
106032
+ positionHasLegacyLegs: state2.legacySymbols.has(symbol2)
106033
+ });
106034
+ if (request.shape === "legacy_per_entry") return null;
106035
+ return {
106036
+ native: { position_before: String(input.positionBefore) },
106037
+ children: request.shape === "entry_with_position_children" ? request.children.map((child) => ({
106038
+ kind: child.kind,
106039
+ triggerPrice: Number(child.trigger),
106040
+ clientOrderId: clientOrderIdForMutation(createRuntimeId().toLowerCase())
106041
+ })) : []
106042
+ };
106043
+ };
106044
+ SERVER_NATIVE_LEGACY_REFUSAL = "native_protection_legacy_position";
106045
+ isServerNativeLegacyRefusal = (error48) => Boolean(error48 && typeof error48 === "object") && error48.code === SERVER_NATIVE_LEGACY_REFUSAL;
106046
+ runtimeProtectionOwners = /* @__PURE__ */ new WeakMap();
106047
+ resolveRuntimeProtectionOwner = (request) => {
106048
+ if (request.executionMode === "server") return Promise.resolve("server");
106049
+ const cached2 = runtimeProtectionOwners.get(request);
106050
+ if (cached2) return cached2;
106051
+ const authority = runtimeProtectionAuthority(request);
106052
+ const pending3 = runtimeProtectionListing(request).then((listed) => listed.client_protection_owner);
104915
106053
  runtimeProtectionOwners.set(request, pending3);
104916
106054
  return pending3;
104917
106055
  };
@@ -105639,7 +106777,7 @@ var init_runtime_execution = __esm({
105639
106777
  const context = input.executionContext;
105640
106778
  const profileId = String(input.profileId).trim();
105641
106779
  if (input.decision !== "HOLD" && Math.max(0, Math.trunc(input.units)) > 0) return true;
105642
- if (readClientProtectiveGroups(profileId, context.symbol).some((group) => group.legs.length > 0 || group.attachmentJournal != null) || hasClientProtectiveGroupReadFailure(profileId, context.symbol)) {
106780
+ if (readClientProtectiveGroups(profileId, context.symbol).some((group) => group.legs.length > 0 || group.attachmentJournal != null) || hasClientProtectiveGroupReadFailure(profileId, context.symbol) || readNativeRecord(profileId, context.symbol).kind !== "none") {
105643
106781
  return true;
105644
106782
  }
105645
106783
  const positionSize = Number.isFinite(context.currentPositionSize) ? Number(context.currentPositionSize) : 0;
@@ -105779,6 +106917,7 @@ var init_runtime_execution = __esm({
105779
106917
  status: "failed",
105780
106918
  execution_metadata: { reason_code: "protective_lifecycle_storage_invalid" }
105781
106919
  }] : hasTrackedProtection ? await reconcileClientProtectiveGroups(input) : [];
106920
+ reconciliationReports.push(...await reconcileNativeProtectionForDecision(input));
105782
106921
  if (input.decision === "HOLD" || requestedUnits <= 0) {
105783
106922
  const shouldTrail = !input.skipTrailingMaintenance && input.executionContext.tpSlEnabled === true && input.executionContext.stopLossEnabled !== false && input.executionContext.stopLossType === "trailing" && decisionSnapshotPositionSize !== 0;
105784
106923
  if (shouldTrail && !reconciliationReports.some((report) => report.status === "failed")) {
@@ -106406,7 +107545,92 @@ var init_runtime_execution = __esm({
106406
107545
  const localProtection = shouldAttachSlTp && !serverOwnedProtection;
106407
107546
  entryMutationId = await decisionLegMutationId("entry");
106408
107547
  if (entryMutationId) entryClientOrderId = clientOrderIdForMutation(entryMutationId);
107548
+ let nativeOpen = null;
107549
+ let nativeAddRecord = null;
107550
+ const nativeProfileId = String(input.profileId).trim();
107551
+ const nativeBlocked = (reasonCode, message) => ({
107552
+ // A flip whose close already filled reports that close as executed.
107553
+ status: progress.committedReports != null ? "executed" : "skipped",
107554
+ intent: classified.intent,
107555
+ side: classified.side,
107556
+ reduceOnly: classified.reduceOnly,
107557
+ requestedUnits: classified.requestedUnits,
107558
+ targetSignedUnits: classified.targetSignedUnits,
107559
+ executedSizeAsset: progress.committedOrder?.executedSizeAsset ?? 0,
107560
+ executionReports: [
107561
+ ...executionReports,
107562
+ {
107563
+ order_id: null,
107564
+ symbol: input.executionContext.symbol,
107565
+ action: "PROTECTIVE_RECONCILIATION",
107566
+ status: "blocked",
107567
+ execution_metadata: { reason_code: reasonCode, execution_stage: "entry_precondition" }
107568
+ }
107569
+ ],
107570
+ message,
107571
+ executionSnapshotId,
107572
+ executionSnapshotCapturedAt
107573
+ });
106409
107574
  if (localProtection) {
107575
+ let existingNative = readNativeRecord(nativeProfileId, input.executionContext.symbol);
107576
+ if (existingNative.kind === "record" && targetResolution.closeOpposingPosition) {
107577
+ executionReports.push(...await reconcileNativeProtectionForDecision(input));
107578
+ existingNative = readNativeRecord(nativeProfileId, input.executionContext.symbol);
107579
+ }
107580
+ if (existingNative.kind === "invalid") {
107581
+ return nativeBlocked(
107582
+ "protective_lifecycle_storage_invalid",
107583
+ "Blocked new exposure because the stored position protection could not be read."
107584
+ );
107585
+ }
107586
+ if (classified.intent === "add") {
107587
+ if (existingNative.kind === "record" && existingNative.record.isLong === (classified.side === "buy")) {
107588
+ nativeAddRecord = existingNative.record;
107589
+ }
107590
+ } else if (existingNative.kind === "record") {
107591
+ return nativeBlocked(
107592
+ "protective_reconciliation_unresolved",
107593
+ "Blocked new exposure because the earlier position's protection is still being resolved."
107594
+ );
107595
+ } else if (input.config?.client_native_position_protection_enabled === true) {
107596
+ entryMutationId ??= createRuntimeId().toLowerCase();
107597
+ entryClientOrderId = clientOrderIdForMutation(entryMutationId);
107598
+ nativeOpen = planNativeOpen({
107599
+ profileId: nativeProfileId,
107600
+ symbol: input.executionContext.symbol,
107601
+ walletAddress: String(input.executionContext.walletAddress || ""),
107602
+ settings: nativeSettingsOf(input.executionContext),
107603
+ isLong: classified.side === "buy",
107604
+ sizeDecimals: input.executionContext.sizeDecimals,
107605
+ referencePrice: executionPrice,
107606
+ entrySize: sizeAsset,
107607
+ // An entry that closed the opposing position first starts from flat;
107608
+ // otherwise from the live position, which may differ from the
107609
+ // decision's snapshot.
107610
+ positionBefore: targetResolution.closeOpposingPosition ? 0 : currentPositionSize,
107611
+ positionHasLegacyLegs: readClientProtectiveGroups(nativeProfileId, input.executionContext.symbol).length > 0,
107612
+ entryMutationId,
107613
+ entryClientOrderId,
107614
+ newMutationId: () => createRuntimeId().toLowerCase(),
107615
+ nowMs: Date.now()
107616
+ });
107617
+ if (nativeOpen != null && !writeNativeProtectionRecord(nativeProfileId, input.executionContext.symbol, nativeOpen.record)) {
107618
+ return nativeBlocked(
107619
+ "protective_lifecycle_persistence_failed",
107620
+ "Blocked new exposure because its position protection could not be stored."
107621
+ );
107622
+ }
107623
+ }
107624
+ }
107625
+ const nativeProtection = nativeOpen != null || nativeAddRecord != null;
107626
+ let serverNative = serverOwnedProtection ? await resolveServerNativeEntry({
107627
+ request: input,
107628
+ isLong: classified.side === "buy",
107629
+ referencePrice: executionPrice,
107630
+ entrySize: sizeAsset,
107631
+ positionBefore: targetResolution.closeOpposingPosition ? 0 : currentPositionSize
107632
+ }) : null;
107633
+ if (localProtection && !nativeProtection) {
106410
107634
  entryMutationId ??= createRuntimeId().toLowerCase();
106411
107635
  entryClientOrderId = clientOrderIdForMutation(entryMutationId);
106412
107636
  const pendingProtection = persistPendingClientProtectiveGroup({
@@ -106494,13 +107718,16 @@ var init_runtime_execution = __esm({
106494
107718
  reduceOnly: classified.reduceOnly,
106495
107719
  mutationId: entryMutationId,
106496
107720
  clientOrderId: entryClientOrderId,
107721
+ ...nativeOpen != null ? { positionChildren: nativeOpen.children } : {},
106497
107722
  ...serverOwnedProtection ? {
106498
107723
  // The server attaches the configured Auto SL/TP to this entry.
106499
107724
  protection: {
106500
107725
  source: "runtime_config",
106501
107726
  requested_entry_size: sizeAsset,
106502
- is_long: entrySide === "buy"
107727
+ is_long: entrySide === "buy",
107728
+ ...serverNative ? { native: serverNative.native } : {}
106503
107729
  },
107730
+ ...serverNative && serverNative.children.length > 0 ? { positionChildren: serverNative.children } : {},
106504
107731
  onSettled: (mutation) => {
106505
107732
  settledServerProtectedEntry = mutation;
106506
107733
  }
@@ -106508,7 +107735,15 @@ var init_runtime_execution = __esm({
106508
107735
  });
106509
107736
  try {
106510
107737
  try {
106511
- marketOrderResponse = await sendEntry();
107738
+ try {
107739
+ marketOrderResponse = await sendEntry();
107740
+ } catch (nativeRefusal) {
107741
+ if (serverNative == null || !isServerNativeLegacyRefusal(nativeRefusal) || entryDispatchBoundaryPassed) {
107742
+ throw nativeRefusal;
107743
+ }
107744
+ serverNative = null;
107745
+ marketOrderResponse = await sendEntry();
107746
+ }
106512
107747
  } catch (rejection) {
106513
107748
  const retry = await serverOrderMetadataRetry(input, rejection, "entry", entryMutationId);
106514
107749
  const retrySize = retry === null ? 0 : quantizeHyperliquidOrderSizeValue(intendedSizeAsset, retry.sizeDecimals, "nearest");
@@ -106522,6 +107757,9 @@ var init_runtime_execution = __esm({
106522
107757
  marketOrderResponse = await sendEntry();
106523
107758
  }
106524
107759
  } catch (entryDispatchError) {
107760
+ if (nativeOpen != null && (!entryDispatchBoundaryPassed || isDefinitiveEntryRejection(entryDispatchError, entryMutationId))) {
107761
+ writeNativeProtectionRecord(nativeProfileId, input.executionContext.symbol, null);
107762
+ }
106525
107763
  const handoffVeto = isClientRuntimeWindowHandoffBeforePlanDispatch(entryDispatchError);
106526
107764
  const handoffBeforeDispatch = handoffVeto || !entryDispatchBoundaryPassed && input.shouldCancelBeforeExchangeOrderDispatch?.() === true;
106527
107765
  const hasCommittedReports = executionReports.some((report) => report.status === "executed" && String(report.order_id || "").trim().length > 0);
@@ -106569,7 +107807,8 @@ var init_runtime_execution = __esm({
106569
107807
  throw entryDispatchError;
106570
107808
  }
106571
107809
  const confirmedMarketFill = extractCanonicalHyperliquidFilledOrderAcknowledgement(
106572
- marketOrderResponse
107810
+ // An entry carrying position children is member 0 of its action.
107811
+ nativeOpen != null || (serverNative?.children.length ?? 0) > 0 ? firstMemberAcknowledgement(marketOrderResponse) : marketOrderResponse
106573
107812
  );
106574
107813
  executionReports.push({
106575
107814
  order_id: _extractOrderId(marketOrderResponse),
@@ -106639,7 +107878,50 @@ var init_runtime_execution = __esm({
106639
107878
  const settledEntry = settledServerProtectedEntry;
106640
107879
  await drainServerProtectionForRuntime(input, settledEntry?.protective_actions ?? null);
106641
107880
  }
106642
- if (localProtection) {
107881
+ if (nativeProtection) {
107882
+ const symbol2 = input.executionContext.symbol;
107883
+ let record5 = nativeOpen != null ? recordEntryChildren(nativeOpen.record, marketOrderResponse) : nativeAddRecord;
107884
+ let keepNativeJournal = false;
107885
+ if (nativeOpen != null && !writeNativeProtectionRecord(nativeProfileId, symbol2, record5)) {
107886
+ executionReports.push(nativeStorageReport(symbol2, "protective_lifecycle_persistence_failed"));
107887
+ }
107888
+ if (confirmedMarketFill == null) {
107889
+ executionReports.push({
107890
+ order_id: _extractOrderId(marketOrderResponse),
107891
+ symbol: symbol2,
107892
+ action: "PROTECTIVE_RECONCILIATION",
107893
+ status: "blocked",
107894
+ execution_metadata: { reason_code: "entry_fill_unresolved", execution_stage: "protective_trigger_precondition" }
107895
+ });
107896
+ } else {
107897
+ try {
107898
+ const settled = await settleNativeProtectionAfterFill({
107899
+ record: record5,
107900
+ settings: nativeSettingsOf(input.executionContext),
107901
+ sizeDecimals: input.executionContext.sizeDecimals,
107902
+ fillSize: String(confirmedMarketFill.filledSize),
107903
+ entryOrderId: confirmedMarketFill.orderId,
107904
+ io: nativeProtectionIo(input, record5.isLong)
107905
+ });
107906
+ executionReports.push(...settled.reports);
107907
+ if (settled.record != null) record5 = settled.record;
107908
+ } catch (postEntryProtectionError) {
107909
+ if (isClientRuntimeLeaseOwnershipError(postEntryProtectionError)) throw postEntryProtectionError;
107910
+ if (nativePassEnded(input, postEntryProtectionError)) {
107911
+ keepNativeJournal = true;
107912
+ const cause = postEntryProtectionError instanceof NativeOrderNotSentError ? postEntryProtectionError.cause : postEntryProtectionError;
107913
+ if (isClientRuntimeWindowHandoffBeforePlanDispatch(cause)) throw cause;
107914
+ appendPostEntryProtectionFailure(cause);
107915
+ } else {
107916
+ appendPostEntryProtectionFailure(postEntryProtectionError);
107917
+ }
107918
+ }
107919
+ }
107920
+ if (!keepNativeJournal && !writeNativeProtectionRecord(nativeProfileId, symbol2, record5)) {
107921
+ executionReports.push(nativeStorageReport(symbol2, "protective_lifecycle_persistence_failed"));
107922
+ }
107923
+ }
107924
+ if (localProtection && !nativeProtection) {
106643
107925
  let protectionBlockReason = confirmedMarketFill == null ? "entry_fill_unresolved" : classified.intent === "flip" && !flipCloseFillConfirmed ? "flip_close_fill_unresolved" : null;
106644
107926
  const protectionFill = protectionBlockReason == null ? confirmedMarketFill : null;
106645
107927
  const protectionSize = protectionFill == null ? 0 : protectionFill.filledSize;
@@ -108390,7 +109672,7 @@ var init_inference_observability = __esm({
108390
109672
  AI_INVOCATION_PARSER_CONTRACT_VERSION = 1;
108391
109673
  NEVER_SENT_FAILURE_CATEGORY = "configuration";
108392
109674
  MISSING_API_KEY_FAILURE_CODE = "missing_api_key";
108393
- isNeverSentInvocation = (attempt) => attempt.failure_category === NEVER_SENT_FAILURE_CATEGORY;
109675
+ isNeverSentInvocation = (attempt2) => attempt2.failure_category === NEVER_SENT_FAILURE_CATEGORY;
108394
109676
  USE_CASES = /* @__PURE__ */ new Set(["trader", "decision_chat", "screener"]);
108395
109677
  ROLES_BY_USE_CASE = {
108396
109678
  trader: /* @__PURE__ */ new Set(["primary", "review"]),
@@ -111346,7 +112628,7 @@ function canAdvanceProfileModel(error48, external, signal, ownAttempts) {
111346
112628
  if (failure2.runtimePartialOutput || failure2.result?.content || failure2.result?.reasoningContent) return false;
111347
112629
  if (external) return failure2.modelFallbackSafe === true;
111348
112630
  const attempts = ownAttempts ?? failure2.runtimeInvocationAttempts ?? [];
111349
- if (attempts.some((attempt) => attempt.status === "succeeded" || attempt.provider_status_code == null && !isNeverSentInvocation(attempt) && !(failure2.runtimeNativeRecoverySafe === true && ["timeout", "transport_error"].includes(attempt.failure_code ?? "")) || Boolean(attempt.response_content) || Boolean(attempt.reasoning_content))) return false;
112631
+ if (attempts.some((attempt2) => attempt2.status === "succeeded" || attempt2.provider_status_code == null && !isNeverSentInvocation(attempt2) && !(failure2.runtimeNativeRecoverySafe === true && ["timeout", "transport_error"].includes(attempt2.failure_code ?? "")) || Boolean(attempt2.response_content) || Boolean(attempt2.reasoning_content))) return false;
111350
112632
  const message = error48.message.toLowerCase();
111351
112633
  if (/outcome.?unknown|dispatch.?unknown/.test(message)) return false;
111352
112634
  if (failure2.runtimeNativeRecoverySafe === true && failure2.runtimeNativeFailureKind && attempts.length > 0) return true;
@@ -111376,17 +112658,17 @@ async function invokeProfileModelCascade(input) {
111376
112658
  if (attempted.has(identity2)) continue;
111377
112659
  attempted.add(identity2);
111378
112660
  if (input.signal?.aborted) throw input.signal.reason ?? new DOMException("Cancelled", "AbortError");
111379
- const priorIds = new Set(attempts.map((attempt) => attempt.client_invocation_id));
112661
+ const priorIds = new Set(attempts.map((attempt2) => attempt2.client_invocation_id));
111380
112662
  try {
111381
112663
  const result = await input.invoke(entry, index, attempts);
111382
112664
  const resultInvocations = result.invocations ?? [];
111383
- const ids = new Set(resultInvocations.map((attempt) => attempt.client_invocation_id));
111384
- return { ...result, invocations: [...attempts.filter((attempt) => !ids.has(attempt.client_invocation_id)), ...resultInvocations] };
112665
+ const ids = new Set(resultInvocations.map((attempt2) => attempt2.client_invocation_id));
112666
+ return { ...result, invocations: [...attempts.filter((attempt2) => !ids.has(attempt2.client_invocation_id)), ...resultInvocations] };
111385
112667
  } catch (error48) {
111386
112668
  const observed = error48?.runtimeInvocationAttempts;
111387
112669
  if (Array.isArray(observed)) attempts = observed;
111388
112670
  if (error48 instanceof Error) error48.runtimeInvocationAttempts = attempts;
111389
- const ownAttempts = attempts.filter((attempt) => !priorIds.has(attempt.client_invocation_id));
112671
+ const ownAttempts = attempts.filter((attempt2) => !priorIds.has(attempt2.client_invocation_id));
111390
112672
  if (error48 instanceof Error) failedModels.push(fallbackAttemptFor(entry, error48, ownAttempts));
111391
112673
  if (index === entries.length - 1 || !canAdvanceProfileModel(error48, entry.kind === "external_agent" || entry.source === "external_agent", input.signal, ownAttempts)) surface(error48);
111392
112674
  lastFailure = error48;
@@ -115593,19 +116875,19 @@ var init_provider_client = __esm({
115593
116875
  if (!rawAttempt || typeof rawAttempt !== "object") {
115594
116876
  continue;
115595
116877
  }
115596
- const attempt = rawAttempt;
115597
- const errorDetail = String(attempt.errorDetail || "Provider compatibility dispatch failed.");
116878
+ const attempt2 = rawAttempt;
116879
+ const errorDetail = String(attempt2.errorDetail || "Provider compatibility dispatch failed.");
115598
116880
  chain.push(await buildBrowserInvocation({
115599
116881
  context: invocationContext,
115600
116882
  attemptIndex: chain.length,
115601
116883
  status: "failed",
115602
116884
  provider,
115603
- transport: attempt.transport ?? defaultProviderTransport(provider),
116885
+ transport: attempt2.transport ?? defaultProviderTransport(provider),
115604
116886
  requestedModel: model,
115605
116887
  actualModel: model,
115606
116888
  credentialSlotIndex: provider === "local" ? null : providerKeySlotIndex + 1,
115607
- startedAt: attempt.startedAt ?? invocationStartedAt,
115608
- latencyMs: Number(attempt.latencyMs ?? 0),
116889
+ startedAt: attempt2.startedAt ?? invocationStartedAt,
116890
+ latencyMs: Number(attempt2.latencyMs ?? 0),
115609
116891
  systemPrompt,
115610
116892
  userPrompt,
115611
116893
  extraMessages: normalizedExtraMessages,
@@ -115614,15 +116896,15 @@ var init_provider_client = __esm({
115614
116896
  reasoningPayload,
115615
116897
  nativeRequestParameters,
115616
116898
  nativeRequestParameterValues,
115617
- sentReasoningParameters: attempt.sentReasoningParameters,
115618
- effectiveReasoningParameters: attempt.effectiveReasoningParameters,
116899
+ sentReasoningParameters: attempt2.sentReasoningParameters,
116900
+ effectiveReasoningParameters: attempt2.effectiveReasoningParameters,
115619
116901
  errorDetail,
115620
- statusCode: attempt.statusCode ?? null,
115621
- requestInputTokens: attempt.requestInputTokens,
115622
- providerDiagnostics: attempt.providerDiagnostics,
115623
- providerRequestId: attempt.providerRequestId,
115624
- response: attempt.response ?? null,
115625
- retryable: attempt.retryable ?? false,
116902
+ statusCode: attempt2.statusCode ?? null,
116903
+ requestInputTokens: attempt2.requestInputTokens,
116904
+ providerDiagnostics: attempt2.providerDiagnostics,
116905
+ providerRequestId: attempt2.providerRequestId,
116906
+ response: attempt2.response ?? null,
116907
+ retryable: attempt2.retryable ?? false,
115626
116908
  fallbackFrom: chain.at(-1) ?? null
115627
116909
  }));
115628
116910
  }
@@ -115909,7 +117191,7 @@ var init_provider_client = __esm({
115909
117191
  error48?.runtimeDispatchStartedAt
115910
117192
  );
115911
117193
  const invocationAttempts2 = [...observedInvocationAttempts2];
115912
- const nativeRecoverySafe = input.nativeRecoverySafe !== false && !input.tools?.length && !inputOnDelta && !emittedDelta && (statusCode !== null || Boolean(nativeFailureKind)) && (!Array.isArray(rawInternalDispatchAttempts) || rawInternalDispatchAttempts.every((attempt) => attempt.statusCode != null));
117194
+ const nativeRecoverySafe = input.nativeRecoverySafe !== false && !input.tools?.length && !inputOnDelta && !emittedDelta && (statusCode !== null || Boolean(nativeFailureKind)) && (!Array.isArray(rawInternalDispatchAttempts) || rawInternalDispatchAttempts.every((attempt2) => attempt2.statusCode != null));
115913
117195
  if (currentDispatchObserved) {
115914
117196
  const failedProviderResponse = error48?.runtimeProviderResult && typeof error48.runtimeProviderResult === "object" ? error48.runtimeProviderResult : null;
115915
117197
  const failedCostInfo = failedProviderResponse ? calculateProviderCost(
@@ -121075,7 +122357,7 @@ ${behaviorJson}
121075
122357
  }
121076
122358
  };
121077
122359
  fetchBoundPromptContracts = async (profileId, payload, signal, walletAddress, getEquity, getTotalUnrealizedPnl, getAccountStateResolvedAtMs, getUserFills, waitForLiveAccountState, initialMetadata, getPositions, getPerpDexAccounts, runsWithoutEquity = false) => {
121078
- let attempt = 0;
122360
+ let attempt2 = 0;
121079
122361
  while (true) {
121080
122362
  if (waitForLiveAccountState) {
121081
122363
  const accountStateWaitStartedAtMs = Date.now();
@@ -121106,7 +122388,7 @@ ${behaviorJson}
121106
122388
  appendRuntimeTimingEvent(
121107
122389
  "prompt_parity_account_state_ready",
121108
122390
  accountStateWaitStartedAtMs,
121109
- `attempt=${attempt + 1}`
122391
+ `attempt=${attempt2 + 1}`
121110
122392
  );
121111
122393
  reportPromptParityTelemetry(
121112
122394
  profileId,
@@ -121115,7 +122397,7 @@ ${behaviorJson}
121115
122397
  "phase=account_state_wait",
121116
122398
  {
121117
122399
  phase: "account_state_wait",
121118
- attempt: attempt + 1,
122400
+ attempt: attempt2 + 1,
121119
122401
  duration_ms: Date.now() - accountStateWaitStartedAtMs
121120
122402
  }
121121
122403
  );
@@ -121130,7 +122412,7 @@ ${behaviorJson}
121130
122412
  const accountStateAgeMs = typeof accountStateResolvedAtMs === "number" ? Math.max(0, parityPreparedAtMs - accountStateResolvedAtMs) : null;
121131
122413
  appendRuntimeDebugEvent({
121132
122414
  label: "prompt_parity_context_prepared",
121133
- note: `attempt=${attempt + 1} parity_included=${parityIncluded ? "yes" : "no"} account_equity=${liveEquity.toFixed(RUNTIME_DEBUG_USD_DECIMALS)} account_state_age_ms=${accountStateAgeMs ?? "unresolved"}`
122415
+ note: `attempt=${attempt2 + 1} parity_included=${parityIncluded ? "yes" : "no"} account_equity=${liveEquity.toFixed(RUNTIME_DEBUG_USD_DECIMALS)} account_state_age_ms=${accountStateAgeMs ?? "unresolved"}`
121134
122416
  });
121135
122417
  reportPromptParityTelemetry(
121136
122418
  profileId,
@@ -121139,7 +122421,7 @@ ${behaviorJson}
121139
122421
  `phase=derived_context_preflight parity_included=${parityIncluded ? "yes" : "no"}`,
121140
122422
  {
121141
122423
  phase: "derived_context_preflight",
121142
- attempt: attempt + 1,
122424
+ attempt: attempt2 + 1,
121143
122425
  parity_included: parityIncluded,
121144
122426
  account_equity_positive: liveEquity > 0,
121145
122427
  account_state_age_ms: accountStateAgeMs,
@@ -121157,7 +122439,7 @@ ${behaviorJson}
121157
122439
  "phase=derived_context_preflight parity_included=no",
121158
122440
  {
121159
122441
  phase: "derived_context_preflight",
121160
- attempt: attempt + 1,
122442
+ attempt: attempt2 + 1,
121161
122443
  account_state_age_ms: accountStateAgeMs,
121162
122444
  account_equity_positive: false
121163
122445
  }
@@ -121186,7 +122468,7 @@ ${behaviorJson}
121186
122468
  };
121187
122469
  appendRuntimeDebugEvent({
121188
122470
  label: "prompt_parity_fills_prepared",
121189
- note: `attempt=${attempt + 1} fills=${fills.length}`
122471
+ note: `attempt=${attempt2 + 1} fills=${fills.length}`
121190
122472
  });
121191
122473
  }
121192
122474
  const derivedPayload = {
@@ -121204,7 +122486,7 @@ ${behaviorJson}
121204
122486
  });
121205
122487
  } catch (error48) {
121206
122488
  const detail = error48 instanceof Error ? error48.message : String(error48);
121207
- const errorMetadata = attempt === 0 && initialMetadata ? initialMetadata : await fetchClientRuntimePromptMetadata(profileId, payload, {
122489
+ const errorMetadata = attempt2 === 0 && initialMetadata ? initialMetadata : await fetchClientRuntimePromptMetadata(profileId, payload, {
121208
122490
  schedulerInstanceId: payload.schedulerInstanceId,
121209
122491
  signal
121210
122492
  });
@@ -121224,7 +122506,7 @@ ${behaviorJson}
121224
122506
  );
121225
122507
  const metadataStartedAtMs = Date.now();
121226
122508
  let embeddedMetadata = derived.prompt_metadata;
121227
- const initialMetadataPrecedesDerived = attempt === 0 && initialMetadata !== null;
122509
+ const initialMetadataPrecedesDerived = attempt2 === 0 && initialMetadata !== null;
121228
122510
  const legacyMetadataFollowsDerived = !embeddedMetadata && !initialMetadataPrecedesDerived;
121229
122511
  let metadata;
121230
122512
  if (embeddedMetadata && typeof embeddedMetadata === "object") {
@@ -121291,23 +122573,23 @@ ${behaviorJson}
121291
122573
  assertPromptContractTemporalBounds(metadata, derived);
121292
122574
  appendRuntimeDebugEvent({
121293
122575
  label: "prompt_contract_binding_validated",
121294
- note: `attempt=${attempt + 1} contract_hash=${metadata.envelope.contract_hash} cycle_snapshot_id=${derived.cycle_snapshot_id}`
122576
+ note: `attempt=${attempt2 + 1} contract_hash=${metadata.envelope.contract_hash} cycle_snapshot_id=${derived.cycle_snapshot_id}`
121295
122577
  });
121296
122578
  return { metadata, derived };
121297
122579
  } catch (error48) {
121298
122580
  const detail = error48 instanceof Error ? error48.message : String(error48);
121299
- if (attempt >= maxBindingRetries) {
121300
- throw new Error(`Prompt contract binding mismatch after ${attempt + 1} attempt(s): ${detail}`);
122581
+ if (attempt2 >= maxBindingRetries) {
122582
+ throw new Error(`Prompt contract binding mismatch after ${attempt2 + 1} attempt(s): ${detail}`);
121301
122583
  }
121302
- const exponentialBackoff = Math.min(backoffMaxMs, backoffBaseMs * BACKOFF_GROWTH_FACTOR ** attempt);
122584
+ const exponentialBackoff = Math.min(backoffMaxMs, backoffBaseMs * BACKOFF_GROWTH_FACTOR ** attempt2);
121303
122585
  const jitter = backoffJitterMs > 0 ? Math.floor(Math.random() * (backoffJitterMs + 1)) : 0;
121304
122586
  const waitMs = exponentialBackoff + jitter;
121305
122587
  appendRuntimeDebugEvent({
121306
122588
  label: "prompt_contract_binding_retry",
121307
- note: `attempt=${attempt + 1} wait_ms=${waitMs} reason=${detail}`
122589
+ note: `attempt=${attempt2 + 1} wait_ms=${waitMs} reason=${detail}`
121308
122590
  });
121309
122591
  await sleepWithAbort(waitMs, signal);
121310
- attempt += 1;
122592
+ attempt2 += 1;
121311
122593
  }
121312
122594
  }
121313
122595
  };
@@ -123833,11 +125115,11 @@ var init_engine = __esm({
123833
125115
  if (!Array.isArray(attempts)) {
123834
125116
  return null;
123835
125117
  }
123836
- const normalized = attempts.map((attempt) => {
123837
- if (!attempt || typeof attempt !== "object") {
125118
+ const normalized = attempts.map((attempt2) => {
125119
+ if (!attempt2 || typeof attempt2 !== "object") {
123838
125120
  return null;
123839
125121
  }
123840
- const record5 = attempt;
125122
+ const record5 = attempt2;
123841
125123
  const model = String(record5.model || "").trim();
123842
125124
  if (!model) {
123843
125125
  return null;
@@ -123850,10 +125132,10 @@ var init_engine = __esm({
123850
125132
  error: sanitizeRuntimeDiagnosticValue(String(record5.error || "")).slice(0, FALLBACK_ERROR_MAX_CHARS) || null,
123851
125133
  statusCode: Number.isInteger(statusCode) ? statusCode : null
123852
125134
  };
123853
- }).filter((attempt) => attempt !== null);
125135
+ }).filter((attempt2) => attempt2 !== null);
123854
125136
  return normalized.length > 0 ? normalized : null;
123855
125137
  };
123856
- sentInvocationAttemptCount = (record5) => Array.isArray(record5.runtimeInvocationAttempts) ? record5.runtimeInvocationAttempts.filter((attempt) => !attempt || typeof attempt !== "object" || !isNeverSentInvocation(attempt)).length : 0;
125138
+ sentInvocationAttemptCount = (record5) => Array.isArray(record5.runtimeInvocationAttempts) ? record5.runtimeInvocationAttempts.filter((attempt2) => !attempt2 || typeof attempt2 !== "object" || !isNeverSentInvocation(attempt2)).length : 0;
123857
125139
  boundRuntimeFallbackAttempts = (reason, maxModels) => {
123858
125140
  const attempts = getRuntimeFallbackAttempts(reason);
123859
125141
  return attempts ? boundRuntimeReportAttempts(attempts, maxModels) : null;
@@ -127399,8 +128681,8 @@ var init_engine = __esm({
127399
128681
  }
127400
128682
  if (decisionError instanceof Error && decisionError.status === HTTP_STATUS.CONFLICT && (decisionError.code === "snapshot_stale" || decisionError.message.startsWith("Runtime decision rejected by constraints:"))) {
127401
128683
  Object.assign(decisionError, {
127402
- runtimeInvocationAttempts: result.invocations?.map((attempt) => ({
127403
- ...attempt,
128684
+ runtimeInvocationAttempts: result.invocations?.map((attempt2) => ({
128685
+ ...attempt2,
127404
128686
  used_for_final_decision: false
127405
128687
  }))
127406
128688
  });
@@ -130290,13 +131572,13 @@ async function runHeadlessRuntime(options) {
130290
131572
  const waitForServerBackup = async () => {
130291
131573
  if (options.once || stopController.signal.aborted) return "not_backup";
130292
131574
  let status = null;
130293
- for (let attempt = 0; ; attempt += 1) {
131575
+ for (let attempt2 = 0; ; attempt2 += 1) {
130294
131576
  const read = await readWaitStatus();
130295
131577
  if (read === "ended" || typeof read === "object" && "refused" in read) return "not_backup";
130296
131578
  status = read === "retry" ? null : read.status;
130297
- if (status || attempt >= BACKUP_FIRST_READ_RETRY_MS.length || stopController.signal.aborted) break;
131579
+ if (status || attempt2 >= BACKUP_FIRST_READ_RETRY_MS.length || stopController.signal.aborted) break;
130298
131580
  try {
130299
- await sleep3(BACKUP_FIRST_READ_RETRY_MS[attempt], void 0, { signal: stopController.signal });
131581
+ await sleep3(BACKUP_FIRST_READ_RETRY_MS[attempt2], void 0, { signal: stopController.signal });
130300
131582
  } catch {
130301
131583
  break;
130302
131584
  }