@vtxmacro/cli 2026.10.10 → 2026.10.12

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.10", 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.12", 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
 
@@ -136,7 +136,10 @@ var init_runtime_policy_generated = __esm({
136
136
  jitter_milliseconds: 750,
137
137
  base_delay_milliseconds: 500,
138
138
  min_delay_milliseconds: 250,
139
- max_delay_milliseconds: 1e4
139
+ max_delay_milliseconds: 1e4,
140
+ recovery_base_delay_milliseconds: 1e3,
141
+ recovery_max_delay_milliseconds: 3e4,
142
+ recovery_exponent_max: 5
140
143
  },
141
144
  trade_refresh_policy: {
142
145
  server_config_stream_timeout_ms: 1e4,
@@ -144,11 +147,26 @@ var init_runtime_policy_generated = __esm({
144
147
  copy_trading_status_poll_ms: 5e3,
145
148
  post_execution_refresh_delay_ms: 3e3,
146
149
  account_read_backoff_min_ms: 2e3,
147
- account_read_backoff_max_ms: 6e4
150
+ account_read_backoff_max_ms: 6e4,
151
+ ai_start_grace_min_ms: 45e3
148
152
  },
149
153
  deployment_reload_observability: {
150
154
  bootstrap_max_error_events_per_page: 4,
151
155
  bootstrap_max_profiles: 10
156
+ },
157
+ ws_fallback_polling: {
158
+ screener_active_run_ms: 2500
159
+ },
160
+ deployment_reload: {
161
+ version_poll_interval_seconds: 30,
162
+ reload_delay_seconds: 5
163
+ },
164
+ profile_runtime_status: {
165
+ sync_timeout_ms: 8e3,
166
+ sync_concurrency: 3,
167
+ refresh_interval_ms: 1e4,
168
+ watchdog_interval_ms: 1e3,
169
+ watchdog_grace_ms: 500
152
170
  }
153
171
  },
154
172
  ai_dashboard: {
@@ -211,7 +229,12 @@ var init_runtime_policy_generated = __esm({
211
229
  idle_recheck_seconds: 60,
212
230
  attention_refresh_seconds: 60,
213
231
  evidence_max_items: 32,
214
- evidence_shared_read_seconds: 10
232
+ evidence_shared_read_seconds: 10,
233
+ retry_delay_seconds: 15
234
+ },
235
+ exchange_mutation: {
236
+ settlement_retry_milliseconds: 1e3,
237
+ settlement_retry_window_seconds: 120
215
238
  },
216
239
  protective_plan_set_lock: {
217
240
  wait_seconds: 120
@@ -234,7 +257,15 @@ var init_runtime_policy_generated = __esm({
234
257
  hyperliquid_snapshot: {
235
258
  max_fills_per_execution: 20,
236
259
  max_fill_payload_bytes: 32768
237
- }
260
+ },
261
+ loop_early_return_retry_milliseconds: 5e3,
262
+ window_handoff_cleanup_retry_milliseconds: 1e3,
263
+ ai_schedule_pause_min_milliseconds: 1e3,
264
+ ai_schedule_pause_max_milliseconds: 36e5,
265
+ ai_schedule_pause_unknown_milliseconds: 6e4,
266
+ provider_failure_diagnostics_delay_milliseconds: 2500,
267
+ provider_failure_diagnostics_max_age_milliseconds: 3e4,
268
+ killswitch_timer_floor_milliseconds: 1e3
238
269
  },
239
270
  server_runtime: {
240
271
  prompt_rescue: {
@@ -278,11 +309,55 @@ var init_runtime_policy_generated = __esm({
278
309
  restart_stable_uptime_ms: 6e4,
279
310
  restart_backoff_base_ms: 1e3,
280
311
  restart_backoff_max_ms: 3e4,
281
- restart_exponent_max: 5
312
+ restart_exponent_max: 5,
313
+ cooperative_stop_timeout_ms: 75e3,
314
+ update_readiness_timeout_ms: 6e5,
315
+ rollback_confirmation_min_attempts: 100,
316
+ ready_consecutive_observations: 2,
317
+ control_lock_wait_attempts: 400,
318
+ control_lock_retry_interval_ms: 250,
319
+ supervisor_manifest_poll_interval_ms: 250,
320
+ worker_readiness_settle_ms: 500
282
321
  },
283
322
  claim_diagnostics: {
284
323
  event_loop_sample_interval_ms: 100
285
- }
324
+ },
325
+ host_runtime: {
326
+ advertisement_ttl_ms: 12e4,
327
+ advertisement_refresh_lead_ms: 3e4,
328
+ host_heartbeat_interval_ms: 3e3,
329
+ attempt_heartbeat_interval_ms: 3e3,
330
+ agent_heartbeat_interval_ms: 3e3,
331
+ agent_heartbeat_max_retry_delay_ms: 9e3,
332
+ provider_rate_limit_refresh_ms: 6e4,
333
+ drain_timeout_ms: 3e4,
334
+ remote_retry_limit: 3,
335
+ minimum_sleep_ms: 10,
336
+ heartbeat_gap_diagnostic_min_ms: 1e4,
337
+ heartbeat_gap_diagnostic_factor: 3,
338
+ agent_auth_cooldown_ms: 3e5,
339
+ agent_rate_limit_cooldown_ms: 6e4,
340
+ agent_transient_cooldown_ms: 5e3,
341
+ claim_start_window_min_ms: 5e3,
342
+ attempt_start_retry_delay_max_ms: 15e3,
343
+ claim_dispatch_batch_size: 16,
344
+ codex_quota_cooldown_max_ms: 6912e5,
345
+ attempt_start_retry_base_ms: 1e3,
346
+ attempt_start_retry_exponent_max: 4,
347
+ remote_retry_backoff_step_ms: 250,
348
+ remote_retry_backoff_max_ms: 1e3,
349
+ remote_retry_fallback_ms: 1e3,
350
+ access_token_refresh_lead_ms: 5e3,
351
+ rate_limit_read_timeout_max_ms: 2e3,
352
+ agent_idle_retry_ms: 1e3,
353
+ agent_idle_poll_ms: 5e3,
354
+ agent_turn_timeout_ms: 6e5,
355
+ codex_rate_limit_metadata_timeout_ms: 5e3,
356
+ codex_login_timeout_ms: 9e5,
357
+ codex_command_timeout_ms: 3e4
358
+ },
359
+ quota_membership_cooldown_seconds: 300,
360
+ transient_membership_cooldown_seconds: 30
286
361
  },
287
362
  desktop: {
288
363
  runtime_watchdog: {
@@ -415,6 +490,44 @@ var init_runtime_policy_generated = __esm({
415
490
  benzinga: {
416
491
  enabled: false
417
492
  }
493
+ },
494
+ market_data: {
495
+ chart_interest: {
496
+ historical_backfill_candle_limit: 1e3
497
+ }
498
+ },
499
+ auth: {
500
+ tokens: {
501
+ email_2fa_code_length: 6,
502
+ totp_code_length: 6
503
+ }
504
+ },
505
+ websocket: {
506
+ client_connection: {
507
+ reconnect_delay_ms: 3e3,
508
+ ping_interval_ms: 3e4,
509
+ message_flush_interval_ms: 16,
510
+ price_change_highlight_ms: 1e3,
511
+ debug_recent_channel_limit: 24
512
+ }
513
+ },
514
+ notifications: {
515
+ desktop: {
516
+ heartbeat_seconds: 20
517
+ }
518
+ },
519
+ validation: {
520
+ profile_handles: {
521
+ min_length: 3,
522
+ max_length: 20,
523
+ update_confirmation_ms: 3e3
524
+ }
525
+ },
526
+ profiles: {
527
+ limits: {
528
+ handle_changes_per_window: 2,
529
+ handle_change_window_days: 14
530
+ }
418
531
  }
419
532
  };
420
533
  }
@@ -3775,6 +3888,43 @@ var init_updater = __esm({
3775
3888
  }
3776
3889
  });
3777
3890
 
3891
+ // lib/constants.ts
3892
+ var MS_PER_SECOND, SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, DAYS_PER_WEEK, MS_PER_MINUTE, BACKOFF_GROWTH_FACTOR, HTTP_STATUS, HTTP_STATUS_MIN, HTTP_STATUS_MAX, HTTP_CLIENT_ERROR_MIN, HTTP_SERVER_ERROR_MIN;
3893
+ var init_constants = __esm({
3894
+ "lib/constants.ts"() {
3895
+ "use strict";
3896
+ init_define_VTX_EXO_POLICY();
3897
+ init_define_VTX_GROK_POLICY();
3898
+ init_define_VTX_PI_MODEL_POLICY();
3899
+ MS_PER_SECOND = 1e3;
3900
+ SECONDS_PER_MINUTE = 60;
3901
+ MINUTES_PER_HOUR = 60;
3902
+ HOURS_PER_DAY = 24;
3903
+ DAYS_PER_WEEK = 7;
3904
+ MS_PER_MINUTE = MS_PER_SECOND * SECONDS_PER_MINUTE;
3905
+ BACKOFF_GROWTH_FACTOR = 2;
3906
+ HTTP_STATUS = {
3907
+ BAD_REQUEST: 400,
3908
+ UNAUTHORIZED: 401,
3909
+ PAYMENT_REQUIRED: 402,
3910
+ FORBIDDEN: 403,
3911
+ NOT_FOUND: 404,
3912
+ REQUEST_TIMEOUT: 408,
3913
+ CONFLICT: 409,
3914
+ TOO_EARLY: 425,
3915
+ TOO_MANY_REQUESTS: 429,
3916
+ INTERNAL_SERVER_ERROR: 500,
3917
+ BAD_GATEWAY: 502,
3918
+ SERVICE_UNAVAILABLE: 503,
3919
+ GATEWAY_TIMEOUT: 504
3920
+ };
3921
+ HTTP_STATUS_MIN = 100;
3922
+ HTTP_STATUS_MAX = 599;
3923
+ HTTP_CLIENT_ERROR_MIN = 400;
3924
+ HTTP_SERVER_ERROR_MIN = 500;
3925
+ }
3926
+ });
3927
+
3778
3928
  // node_modules/zod/v4/core/core.js
3779
3929
  // @__NO_SIDE_EFFECTS__
3780
3930
  function $constructor(name, initializer3, params) {
@@ -22121,7 +22271,10 @@ var init_runtime_policy_generated2 = __esm({
22121
22271
  jitter_milliseconds: 750,
22122
22272
  base_delay_milliseconds: 500,
22123
22273
  min_delay_milliseconds: 250,
22124
- max_delay_milliseconds: 1e4
22274
+ max_delay_milliseconds: 1e4,
22275
+ recovery_base_delay_milliseconds: 1e3,
22276
+ recovery_max_delay_milliseconds: 3e4,
22277
+ recovery_exponent_max: 5
22125
22278
  },
22126
22279
  trade_refresh_policy: {
22127
22280
  server_config_stream_timeout_ms: 1e4,
@@ -22129,11 +22282,26 @@ var init_runtime_policy_generated2 = __esm({
22129
22282
  copy_trading_status_poll_ms: 5e3,
22130
22283
  post_execution_refresh_delay_ms: 3e3,
22131
22284
  account_read_backoff_min_ms: 2e3,
22132
- account_read_backoff_max_ms: 6e4
22285
+ account_read_backoff_max_ms: 6e4,
22286
+ ai_start_grace_min_ms: 45e3
22133
22287
  },
22134
22288
  deployment_reload_observability: {
22135
22289
  bootstrap_max_error_events_per_page: 4,
22136
22290
  bootstrap_max_profiles: 10
22291
+ },
22292
+ ws_fallback_polling: {
22293
+ screener_active_run_ms: 2500
22294
+ },
22295
+ deployment_reload: {
22296
+ version_poll_interval_seconds: 30,
22297
+ reload_delay_seconds: 5
22298
+ },
22299
+ profile_runtime_status: {
22300
+ sync_timeout_ms: 8e3,
22301
+ sync_concurrency: 3,
22302
+ refresh_interval_ms: 1e4,
22303
+ watchdog_interval_ms: 1e3,
22304
+ watchdog_grace_ms: 500
22137
22305
  }
22138
22306
  },
22139
22307
  ai_dashboard: {
@@ -22196,7 +22364,12 @@ var init_runtime_policy_generated2 = __esm({
22196
22364
  idle_recheck_seconds: 60,
22197
22365
  attention_refresh_seconds: 60,
22198
22366
  evidence_max_items: 32,
22199
- evidence_shared_read_seconds: 10
22367
+ evidence_shared_read_seconds: 10,
22368
+ retry_delay_seconds: 15
22369
+ },
22370
+ exchange_mutation: {
22371
+ settlement_retry_milliseconds: 1e3,
22372
+ settlement_retry_window_seconds: 120
22200
22373
  },
22201
22374
  protective_plan_set_lock: {
22202
22375
  wait_seconds: 120
@@ -22219,7 +22392,15 @@ var init_runtime_policy_generated2 = __esm({
22219
22392
  hyperliquid_snapshot: {
22220
22393
  max_fills_per_execution: 20,
22221
22394
  max_fill_payload_bytes: 32768
22222
- }
22395
+ },
22396
+ loop_early_return_retry_milliseconds: 5e3,
22397
+ window_handoff_cleanup_retry_milliseconds: 1e3,
22398
+ ai_schedule_pause_min_milliseconds: 1e3,
22399
+ ai_schedule_pause_max_milliseconds: 36e5,
22400
+ ai_schedule_pause_unknown_milliseconds: 6e4,
22401
+ provider_failure_diagnostics_delay_milliseconds: 2500,
22402
+ provider_failure_diagnostics_max_age_milliseconds: 3e4,
22403
+ killswitch_timer_floor_milliseconds: 1e3
22223
22404
  },
22224
22405
  server_runtime: {
22225
22406
  prompt_rescue: {
@@ -22263,11 +22444,55 @@ var init_runtime_policy_generated2 = __esm({
22263
22444
  restart_stable_uptime_ms: 6e4,
22264
22445
  restart_backoff_base_ms: 1e3,
22265
22446
  restart_backoff_max_ms: 3e4,
22266
- restart_exponent_max: 5
22447
+ restart_exponent_max: 5,
22448
+ cooperative_stop_timeout_ms: 75e3,
22449
+ update_readiness_timeout_ms: 6e5,
22450
+ rollback_confirmation_min_attempts: 100,
22451
+ ready_consecutive_observations: 2,
22452
+ control_lock_wait_attempts: 400,
22453
+ control_lock_retry_interval_ms: 250,
22454
+ supervisor_manifest_poll_interval_ms: 250,
22455
+ worker_readiness_settle_ms: 500
22267
22456
  },
22268
22457
  claim_diagnostics: {
22269
22458
  event_loop_sample_interval_ms: 100
22270
- }
22459
+ },
22460
+ host_runtime: {
22461
+ advertisement_ttl_ms: 12e4,
22462
+ advertisement_refresh_lead_ms: 3e4,
22463
+ host_heartbeat_interval_ms: 3e3,
22464
+ attempt_heartbeat_interval_ms: 3e3,
22465
+ agent_heartbeat_interval_ms: 3e3,
22466
+ agent_heartbeat_max_retry_delay_ms: 9e3,
22467
+ provider_rate_limit_refresh_ms: 6e4,
22468
+ drain_timeout_ms: 3e4,
22469
+ remote_retry_limit: 3,
22470
+ minimum_sleep_ms: 10,
22471
+ heartbeat_gap_diagnostic_min_ms: 1e4,
22472
+ heartbeat_gap_diagnostic_factor: 3,
22473
+ agent_auth_cooldown_ms: 3e5,
22474
+ agent_rate_limit_cooldown_ms: 6e4,
22475
+ agent_transient_cooldown_ms: 5e3,
22476
+ claim_start_window_min_ms: 5e3,
22477
+ attempt_start_retry_delay_max_ms: 15e3,
22478
+ claim_dispatch_batch_size: 16,
22479
+ codex_quota_cooldown_max_ms: 6912e5,
22480
+ attempt_start_retry_base_ms: 1e3,
22481
+ attempt_start_retry_exponent_max: 4,
22482
+ remote_retry_backoff_step_ms: 250,
22483
+ remote_retry_backoff_max_ms: 1e3,
22484
+ remote_retry_fallback_ms: 1e3,
22485
+ access_token_refresh_lead_ms: 5e3,
22486
+ rate_limit_read_timeout_max_ms: 2e3,
22487
+ agent_idle_retry_ms: 1e3,
22488
+ agent_idle_poll_ms: 5e3,
22489
+ agent_turn_timeout_ms: 6e5,
22490
+ codex_rate_limit_metadata_timeout_ms: 5e3,
22491
+ codex_login_timeout_ms: 9e5,
22492
+ codex_command_timeout_ms: 3e4
22493
+ },
22494
+ quota_membership_cooldown_seconds: 300,
22495
+ transient_membership_cooldown_seconds: 30
22271
22496
  },
22272
22497
  desktop: {
22273
22498
  runtime_watchdog: {
@@ -22400,6 +22625,44 @@ var init_runtime_policy_generated2 = __esm({
22400
22625
  benzinga: {
22401
22626
  enabled: false
22402
22627
  }
22628
+ },
22629
+ market_data: {
22630
+ chart_interest: {
22631
+ historical_backfill_candle_limit: 1e3
22632
+ }
22633
+ },
22634
+ auth: {
22635
+ tokens: {
22636
+ email_2fa_code_length: 6,
22637
+ totp_code_length: 6
22638
+ }
22639
+ },
22640
+ websocket: {
22641
+ client_connection: {
22642
+ reconnect_delay_ms: 3e3,
22643
+ ping_interval_ms: 3e4,
22644
+ message_flush_interval_ms: 16,
22645
+ price_change_highlight_ms: 1e3,
22646
+ debug_recent_channel_limit: 24
22647
+ }
22648
+ },
22649
+ notifications: {
22650
+ desktop: {
22651
+ heartbeat_seconds: 20
22652
+ }
22653
+ },
22654
+ validation: {
22655
+ profile_handles: {
22656
+ min_length: 3,
22657
+ max_length: 20,
22658
+ update_confirmation_ms: 3e3
22659
+ }
22660
+ },
22661
+ profiles: {
22662
+ limits: {
22663
+ handle_changes_per_window: 2,
22664
+ handle_change_window_days: 14
22665
+ }
22403
22666
  }
22404
22667
  };
22405
22668
  }
@@ -30090,6 +30353,8 @@ var init_codex_app_server = __esm({
30090
30353
  init_define_VTX_EXO_POLICY();
30091
30354
  init_define_VTX_GROK_POLICY();
30092
30355
  init_define_VTX_PI_MODEL_POLICY();
30356
+ init_runtime_policy_generated();
30357
+ init_constants();
30093
30358
  init_config2();
30094
30359
  CODEX_INFERENCE_PERMISSION_PROFILE = "vtx_inference_readonly";
30095
30360
  CODEX_AGENT_PERMISSION_PROFILE = "vtx_inference_agent";
@@ -30195,9 +30460,9 @@ var init_codex_app_server = __esm({
30195
30460
  "workspace_owner_usage_limit_reached",
30196
30461
  "workspace_member_usage_limit_reached"
30197
30462
  ];
30198
- DEFAULT_CODEX_QUOTA_COOLDOWN_MS = 5 * 60 * 1e3;
30199
- MAX_CODEX_QUOTA_COOLDOWN_MS = 8 * 24 * 60 * 60 * 1e3;
30200
- CODEX_TRANSIENT_RATE_LIMIT_COOLDOWN_MS = 30 * 1e3;
30463
+ DEFAULT_CODEX_QUOTA_COOLDOWN_MS = runtime_policy_generated_default.external_inference.quota_membership_cooldown_seconds * MS_PER_SECOND;
30464
+ MAX_CODEX_QUOTA_COOLDOWN_MS = runtime_policy_generated_default.external_inference.host_runtime.codex_quota_cooldown_max_ms;
30465
+ CODEX_TRANSIENT_RATE_LIMIT_COOLDOWN_MS = runtime_policy_generated_default.external_inference.transient_membership_cooldown_seconds * MS_PER_SECOND;
30201
30466
  parseCreditsSnapshot = (value) => {
30202
30467
  const candidate = objectOrNull(value);
30203
30468
  if (!candidate || typeof candidate.hasCredits !== "boolean" || typeof candidate.unlimited !== "boolean" || candidate.balance != null && typeof candidate.balance !== "string") return null;
@@ -30242,7 +30507,7 @@ var init_codex_app_server = __esm({
30242
30507
  );
30243
30508
  for (const window2 of windows) {
30244
30509
  if (window2.resetsAt === null) continue;
30245
- const resetAtMs = window2.resetsAt * 1e3;
30510
+ const resetAtMs = window2.resetsAt * MS_PER_SECOND;
30246
30511
  if (!Number.isSafeInteger(resetAtMs)) continue;
30247
30512
  if (window2.usedPercent >= 100) exhaustedResets.push(resetAtMs);
30248
30513
  if (snapshot.rateLimitReachedType !== null || snapshot.spendControlReached === true) {
@@ -30371,8 +30636,8 @@ var init_codex_app_server = __esm({
30371
30636
  if (!(variant in structured)) continue;
30372
30637
  const details = objectOrNull(structured[variant]);
30373
30638
  const rawStatus = details?.httpStatusCode;
30374
- const httpStatusCode = Number.isSafeInteger(rawStatus) && Number(rawStatus) >= 100 && Number(rawStatus) <= 599 ? Number(rawStatus) : null;
30375
- if (httpStatusCode === 401) {
30639
+ const httpStatusCode = Number.isSafeInteger(rawStatus) && Number(rawStatus) >= HTTP_STATUS_MIN && Number(rawStatus) <= HTTP_STATUS_MAX ? Number(rawStatus) : null;
30640
+ if (httpStatusCode === HTTP_STATUS.UNAUTHORIZED) {
30376
30641
  return {
30377
30642
  code: "auth_expired",
30378
30643
  category: "auth",
@@ -30380,7 +30645,7 @@ var init_codex_app_server = __esm({
30380
30645
  httpStatusCode
30381
30646
  };
30382
30647
  }
30383
- if (httpStatusCode === 429) {
30648
+ if (httpStatusCode === HTTP_STATUS.TOO_MANY_REQUESTS) {
30384
30649
  return {
30385
30650
  code: "codex_rate_limited",
30386
30651
  category: "adapter",
@@ -30388,9 +30653,9 @@ var init_codex_app_server = __esm({
30388
30653
  httpStatusCode
30389
30654
  };
30390
30655
  }
30391
- if (httpStatusCode !== null && httpStatusCode >= 400 && httpStatusCode < 500 && httpStatusCode !== 408 && httpStatusCode !== 425) {
30656
+ if (httpStatusCode !== null && httpStatusCode >= HTTP_CLIENT_ERROR_MIN && httpStatusCode < HTTP_SERVER_ERROR_MIN && httpStatusCode !== HTTP_STATUS.REQUEST_TIMEOUT && httpStatusCode !== HTTP_STATUS.TOO_EARLY) {
30392
30657
  const semanticText = JSON.stringify(details || {}).toLowerCase();
30393
- if (httpStatusCode === 402 || /(quota|credit|spend|payment|subscription.*limit)/u.test(semanticText)) {
30658
+ if (httpStatusCode === HTTP_STATUS.PAYMENT_REQUIRED || /(quota|credit|spend|payment|subscription.*limit)/u.test(semanticText)) {
30394
30659
  return {
30395
30660
  code: "quota_exceeded",
30396
30661
  category: "model",
@@ -30398,7 +30663,7 @@ var init_codex_app_server = __esm({
30398
30663
  httpStatusCode
30399
30664
  };
30400
30665
  }
30401
- if (httpStatusCode === 403 && /(auth|account|workspace|billing|entitlement)/u.test(semanticText)) {
30666
+ if (httpStatusCode === HTTP_STATUS.FORBIDDEN && /(auth|account|workspace|billing|entitlement)/u.test(semanticText)) {
30402
30667
  return {
30403
30668
  code: "auth_expired",
30404
30669
  category: "auth",
@@ -30406,7 +30671,7 @@ var init_codex_app_server = __esm({
30406
30671
  httpStatusCode
30407
30672
  };
30408
30673
  }
30409
- if (httpStatusCode === 403 && /(policy|safety|cyber)/u.test(semanticText)) {
30674
+ if (httpStatusCode === HTTP_STATUS.FORBIDDEN && /(policy|safety|cyber)/u.test(semanticText)) {
30410
30675
  return {
30411
30676
  code: "codex_policy_rejected",
30412
30677
  category: "adapter",
@@ -30415,7 +30680,7 @@ var init_codex_app_server = __esm({
30415
30680
  };
30416
30681
  }
30417
30682
  return {
30418
- code: httpStatusCode === 400 ? "codex_bad_request" : "codex_http_client_error",
30683
+ code: httpStatusCode === HTTP_STATUS.BAD_REQUEST ? "codex_bad_request" : "codex_http_client_error",
30419
30684
  category: "adapter",
30420
30685
  retryable: false,
30421
30686
  httpStatusCode
@@ -30424,7 +30689,7 @@ var init_codex_app_server = __esm({
30424
30689
  return {
30425
30690
  code,
30426
30691
  category: "adapter",
30427
- retryable: httpStatusCode === null ? true : httpStatusCode === 408 || httpStatusCode === 425 || httpStatusCode >= 500,
30692
+ retryable: httpStatusCode === null ? true : httpStatusCode === HTTP_STATUS.REQUEST_TIMEOUT || httpStatusCode === HTTP_STATUS.TOO_EARLY || httpStatusCode >= HTTP_SERVER_ERROR_MIN,
30428
30693
  httpStatusCode
30429
30694
  };
30430
30695
  }
@@ -32221,13 +32486,13 @@ child.once('close', async (code, signal) => {
32221
32486
  const observedUsage = threadUsage ?? rawResponseUsage;
32222
32487
  let retryAtMs = null;
32223
32488
  let observedRateLimits = null;
32224
- if (failure2.code === "quota_exceeded" || failure2.httpStatusCode === 429) {
32489
+ if (failure2.code === "quota_exceeded" || failure2.httpStatusCode === HTTP_STATUS.TOO_MANY_REQUESTS) {
32225
32490
  const observedAtMs = Date.now();
32226
32491
  let accountLimitReached = failure2.code === "quota_exceeded";
32227
32492
  try {
32228
32493
  const metadataDeadlineAtMs = Math.min(
32229
32494
  request.deadlineAtMs,
32230
- observedAtMs + 5e3
32495
+ observedAtMs + runtime_policy_generated_default.external_inference.host_runtime.codex_rate_limit_metadata_timeout_ms
32231
32496
  );
32232
32497
  if (metadataDeadlineAtMs <= observedAtMs) throw new Error("rate-limit deadline elapsed");
32233
32498
  observedRateLimits = await this.readAccountRateLimits(
@@ -32930,13 +33195,15 @@ function createDefaultInferenceHostRunnerDependencies(options) {
32930
33195
  envelopePublicKey: options.envelopePublicKey
32931
33196
  };
32932
33197
  }
32933
- var import_ajv, providerHttpStatus, terminalFailureRequiresManualRecovery, canReplayFencedAgentTerminal, RUNTIME_RECEIPT_SCHEMA_VERSION, ATTEMPT_RECEIPT_SCHEMA_VERSION, CLAIM_DISPATCH_BATCH_SIZE, DEFAULT_ADVERTISEMENT_TTL_MS, DEFAULT_ADVERTISEMENT_REFRESH_LEAD_MS, DEFAULT_HOST_HEARTBEAT_MS, DEFAULT_PROVIDER_RATE_LIMIT_REFRESH_MS, DEFAULT_ATTEMPT_HEARTBEAT_MS, DEFAULT_DRAIN_TIMEOUT_MS, DEFAULT_REMOTE_RETRY_LIMIT, MIN_SLEEP_MS, MIN_HOST_HEARTBEAT_GAP_DIAGNOSTIC_MS, HOST_HEARTBEAT_GAP_DIAGNOSTIC_FACTOR, DEFAULT_CODEX_ACCOUNT_COOLDOWN_MS, DEFAULT_AGENT_RATE_LIMIT_COOLDOWN_MS, DEFAULT_AGENT_QUOTA_COOLDOWN_MS, DEFAULT_AGENT_TRANSIENT_COOLDOWN_MS, MIN_CLAIM_START_WINDOW_MS, MAX_ATTEMPT_START_RETRY_DELAY_MS, UNBOUNDED_AVAILABLE_SLOTS, buildInferenceAdvertisedModels, summarizeInferenceHostRuntimeRecovery, FileInferenceHostRuntimeReceiptStore, InferenceHostRecoveryRequiredError, InferenceHostRunnerError, defaultSleep, abortError, settlesWithin, defaultRegisterSignalHandlers, safeInteger, exactObjectKeys, validIso, validateAttemptReceipt, validateRuntimeReceipt, sha256, stableOperationId, buildAttemptStartRequest, isoAt, providerWeeklyQuotaFromRateLimits, usableProviderQuotaSnapshot, finitePositiveOption, validateRunnerOptions, assertLocalCredentialIdentity, retryableRemoteError, remoteRetryAfterMs, controlPlaneFatal, defaultValidateOutput, objectRecord, positiveUtf8ByteLimit, assertCompilableOutputSchema, parseOutputContract, serverProviderDispatchNotAfterMs, membershipFailureDisposition, safeFailureCode, publicServerFailureCode, attemptStartRetryFallbackMs, exactJson2, runnerIdentityMismatch, assertAdvertisementResult, assertHostHeartbeatResult, assertClaimResult, assertStartResult, assertJobHeartbeatResult, assertTerminalResult, isDefinitiveCompletionEvidenceExpiry, classifyFailure, ambiguousHeartbeatTransport, reportedTokenUsage, reportedUsage, InferenceHostRunner, createInferenceAgentControlClient, INFERENCE_AGENT_WAKE_SCHEMA, parseInferenceAgentWake, InferenceAgentRuntime;
33198
+ var import_ajv, providerHttpStatus, terminalFailureRequiresManualRecovery, canReplayFencedAgentTerminal, RUNTIME_RECEIPT_SCHEMA_VERSION, ATTEMPT_RECEIPT_SCHEMA_VERSION, HOST_RUNTIME_POLICY, CLAIM_DISPATCH_BATCH_SIZE, DEFAULT_ADVERTISEMENT_TTL_MS, DEFAULT_ADVERTISEMENT_REFRESH_LEAD_MS, DEFAULT_HOST_HEARTBEAT_MS, DEFAULT_PROVIDER_RATE_LIMIT_REFRESH_MS, DEFAULT_ATTEMPT_HEARTBEAT_MS, DEFAULT_DRAIN_TIMEOUT_MS, DEFAULT_REMOTE_RETRY_LIMIT, MIN_SLEEP_MS, MIN_HOST_HEARTBEAT_GAP_DIAGNOSTIC_MS, HOST_HEARTBEAT_GAP_DIAGNOSTIC_FACTOR, DEFAULT_QUOTA_COOLDOWN_MS, DEFAULT_AGENT_AUTH_COOLDOWN_MS, DEFAULT_AGENT_RATE_LIMIT_COOLDOWN_MS, DEFAULT_AGENT_TRANSIENT_COOLDOWN_MS, MIN_CLAIM_START_WINDOW_MS, MAX_ATTEMPT_START_RETRY_DELAY_MS, UNBOUNDED_AVAILABLE_SLOTS, buildInferenceAdvertisedModels, summarizeInferenceHostRuntimeRecovery, FileInferenceHostRuntimeReceiptStore, InferenceHostRecoveryRequiredError, InferenceHostRunnerError, defaultSleep, abortError, settlesWithin, defaultRegisterSignalHandlers, safeInteger, exactObjectKeys, validIso, validateAttemptReceipt, validateRuntimeReceipt, sha256, stableOperationId, buildAttemptStartRequest, isoAt, providerWeeklyQuotaFromRateLimits, usableProviderQuotaSnapshot, finitePositiveOption, validateRunnerOptions, assertLocalCredentialIdentity, retryableRemoteError, remoteRetryAfterMs, controlPlaneFatal, defaultValidateOutput, objectRecord, positiveUtf8ByteLimit, assertCompilableOutputSchema, parseOutputContract, serverProviderDispatchNotAfterMs, membershipFailureDisposition, safeFailureCode, publicServerFailureCode, attemptStartRetryFallbackMs, exactJson2, runnerIdentityMismatch, assertAdvertisementResult, assertHostHeartbeatResult, assertClaimResult, assertStartResult, assertJobHeartbeatResult, assertTerminalResult, isDefinitiveCompletionEvidenceExpiry, classifyFailure, ambiguousHeartbeatTransport, reportedTokenUsage, reportedUsage, InferenceHostRunner, createInferenceAgentControlClient, INFERENCE_AGENT_WAKE_SCHEMA, parseInferenceAgentWake, InferenceAgentRuntime;
32934
33199
  var init_runner = __esm({
32935
33200
  "lib/inference-host/runner.ts"() {
32936
33201
  "use strict";
32937
33202
  init_define_VTX_EXO_POLICY();
32938
33203
  init_define_VTX_GROK_POLICY();
32939
33204
  init_define_VTX_PI_MODEL_POLICY();
33205
+ init_runtime_policy_generated();
33206
+ init_constants();
32940
33207
  import_ajv = __toESM(require_ajv(), 1);
32941
33208
  init_external_inference_contract();
32942
33209
  init_config2();
@@ -32950,29 +33217,30 @@ var init_runner = __esm({
32950
33217
  providerHttpStatus = (error48) => {
32951
33218
  if (!(error48 instanceof CodexAppServerError)) return null;
32952
33219
  const status = error48.httpStatusCode;
32953
- return typeof status === "number" && Number.isInteger(status) && status >= 400 && status <= 599 ? status : null;
33220
+ return typeof status === "number" && Number.isInteger(status) && status >= HTTP_CLIENT_ERROR_MIN && status <= HTTP_STATUS_MAX ? status : null;
32954
33221
  };
32955
33222
  terminalFailureRequiresManualRecovery = (error48) => (error48.terminalEvidence !== null || error48.grokToolValidation != null || error48.grokResponseIdentity != null) && !error48.retryable && error48.category !== "auth" && !["quota_exceeded", "codex_rate_limited", "provider_rate_limited"].includes(error48.code);
32956
33223
  canReplayFencedAgentTerminal = (state2, fence) => state2?.schema_version === "vtx_inference_agent_runtime_v3" && state2.adapter_id === fence.adapter_id && state2.host_id === fence.host_id && state2.assignment.assignment_id === fence.assignment_id && state2.pending_turn?.terminal_receipt?.terminal_status === "failed" && state2.pending_turn.terminal_receipt.failure_code === fence.failure_code && (fence.dispatch_outcome !== "outcome_unknown" || (state2.pending_turn.terminal_receipt.grok_tool_validation?.prior_dispatch === true || state2.pending_turn.terminal_receipt.grok_response_identity != null || state2.pending_turn.terminal_receipt.provider_http_status !== void 0) && state2.pending_turn.terminal_receipt.dispatch_outcome === "outcome_unknown");
32957
33224
  RUNTIME_RECEIPT_SCHEMA_VERSION = "vtx_inference_host_runtime_v1";
32958
33225
  ATTEMPT_RECEIPT_SCHEMA_VERSION = "vtx_inference_attempt_receipt_v1";
32959
- CLAIM_DISPATCH_BATCH_SIZE = 16;
32960
- DEFAULT_ADVERTISEMENT_TTL_MS = 12e4;
32961
- DEFAULT_ADVERTISEMENT_REFRESH_LEAD_MS = 3e4;
32962
- DEFAULT_HOST_HEARTBEAT_MS = 3e3;
32963
- DEFAULT_PROVIDER_RATE_LIMIT_REFRESH_MS = 6e4;
32964
- DEFAULT_ATTEMPT_HEARTBEAT_MS = 3e3;
32965
- DEFAULT_DRAIN_TIMEOUT_MS = 3e4;
32966
- DEFAULT_REMOTE_RETRY_LIMIT = 3;
32967
- MIN_SLEEP_MS = 10;
32968
- MIN_HOST_HEARTBEAT_GAP_DIAGNOSTIC_MS = 1e4;
32969
- HOST_HEARTBEAT_GAP_DIAGNOSTIC_FACTOR = 3;
32970
- DEFAULT_CODEX_ACCOUNT_COOLDOWN_MS = 5 * 60 * 1e3;
32971
- DEFAULT_AGENT_RATE_LIMIT_COOLDOWN_MS = 6e4;
32972
- DEFAULT_AGENT_QUOTA_COOLDOWN_MS = 5 * 60 * 1e3;
32973
- DEFAULT_AGENT_TRANSIENT_COOLDOWN_MS = 5e3;
32974
- MIN_CLAIM_START_WINDOW_MS = 5e3;
32975
- MAX_ATTEMPT_START_RETRY_DELAY_MS = 15e3;
33226
+ HOST_RUNTIME_POLICY = runtime_policy_generated_default.external_inference.host_runtime;
33227
+ CLAIM_DISPATCH_BATCH_SIZE = HOST_RUNTIME_POLICY.claim_dispatch_batch_size;
33228
+ DEFAULT_ADVERTISEMENT_TTL_MS = HOST_RUNTIME_POLICY.advertisement_ttl_ms;
33229
+ DEFAULT_ADVERTISEMENT_REFRESH_LEAD_MS = HOST_RUNTIME_POLICY.advertisement_refresh_lead_ms;
33230
+ DEFAULT_HOST_HEARTBEAT_MS = HOST_RUNTIME_POLICY.host_heartbeat_interval_ms;
33231
+ DEFAULT_PROVIDER_RATE_LIMIT_REFRESH_MS = HOST_RUNTIME_POLICY.provider_rate_limit_refresh_ms;
33232
+ DEFAULT_ATTEMPT_HEARTBEAT_MS = HOST_RUNTIME_POLICY.attempt_heartbeat_interval_ms;
33233
+ DEFAULT_DRAIN_TIMEOUT_MS = HOST_RUNTIME_POLICY.drain_timeout_ms;
33234
+ DEFAULT_REMOTE_RETRY_LIMIT = HOST_RUNTIME_POLICY.remote_retry_limit;
33235
+ MIN_SLEEP_MS = HOST_RUNTIME_POLICY.minimum_sleep_ms;
33236
+ MIN_HOST_HEARTBEAT_GAP_DIAGNOSTIC_MS = HOST_RUNTIME_POLICY.heartbeat_gap_diagnostic_min_ms;
33237
+ HOST_HEARTBEAT_GAP_DIAGNOSTIC_FACTOR = HOST_RUNTIME_POLICY.heartbeat_gap_diagnostic_factor;
33238
+ DEFAULT_QUOTA_COOLDOWN_MS = runtime_policy_generated_default.external_inference.quota_membership_cooldown_seconds * MS_PER_SECOND;
33239
+ DEFAULT_AGENT_AUTH_COOLDOWN_MS = HOST_RUNTIME_POLICY.agent_auth_cooldown_ms;
33240
+ DEFAULT_AGENT_RATE_LIMIT_COOLDOWN_MS = HOST_RUNTIME_POLICY.agent_rate_limit_cooldown_ms;
33241
+ DEFAULT_AGENT_TRANSIENT_COOLDOWN_MS = HOST_RUNTIME_POLICY.agent_transient_cooldown_ms;
33242
+ MIN_CLAIM_START_WINDOW_MS = HOST_RUNTIME_POLICY.claim_start_window_min_ms;
33243
+ MAX_ATTEMPT_START_RETRY_DELAY_MS = HOST_RUNTIME_POLICY.attempt_start_retry_delay_max_ms;
32976
33244
  UNBOUNDED_AVAILABLE_SLOTS = Number.MAX_SAFE_INTEGER;
32977
33245
  buildInferenceAdvertisedModels = (capabilities, adapterRuntimeVersion, adapter = "codex", structuredOutput = true, sameAttemptRecovery = adapter === "codex", supportedControlModes = ["provider"]) => {
32978
33246
  const visible = capabilities.filter((capability) => !capability.hidden);
@@ -33276,7 +33544,7 @@ var init_runner = __esm({
33276
33544
  providerWeeklyQuotaFromRateLimits = (rateLimits, observedAtMs, currentTimeMs = observedAtMs, includeCredits = true) => {
33277
33545
  if (!rateLimits) return null;
33278
33546
  for (const window2 of [rateLimits.rateLimits.primary, rateLimits.rateLimits.secondary]) {
33279
- if (window2?.windowDurationMins !== 7 * 24 * 60 || window2.resetsAt === null || window2.resetsAt * 1e3 <= currentTimeMs) continue;
33547
+ if (window2?.windowDurationMins !== DAYS_PER_WEEK * HOURS_PER_DAY * MINUTES_PER_HOUR || window2.resetsAt === null || window2.resetsAt * MS_PER_SECOND <= currentTimeMs) continue;
33280
33548
  return {
33281
33549
  source: "codex_app_server",
33282
33550
  ...includeCredits ? {
@@ -33284,7 +33552,7 @@ var init_runner = __esm({
33284
33552
  rate_limit_reached: codexAccountRateLimitReached(rateLimits)
33285
33553
  } : {},
33286
33554
  used_percent: window2.usedPercent,
33287
- resets_at: isoAt(window2.resetsAt * 1e3),
33555
+ resets_at: isoAt(window2.resetsAt * MS_PER_SECOND),
33288
33556
  observed_at: isoAt(observedAtMs)
33289
33557
  };
33290
33558
  }
@@ -33294,7 +33562,7 @@ var init_runner = __esm({
33294
33562
  const window2 = rateLimits.rateLimits[key];
33295
33563
  const known = previous?.[key];
33296
33564
  if (known && (!window2 || window2.windowDurationMins !== known.windowDurationMins)) return false;
33297
- return window2 === null || window2.resetsAt !== null && window2.resetsAt * 1e3 > nowMs2 && (window2.usedPercent < 100 || codexCreditsAvailable(rateLimits.rateLimits));
33565
+ return window2 === null || window2.resetsAt !== null && window2.resetsAt * MS_PER_SECOND > nowMs2 && (window2.usedPercent < 100 || codexCreditsAvailable(rateLimits.rateLimits));
33298
33566
  });
33299
33567
  finitePositiveOption = (value, fallback, label2) => {
33300
33568
  const result = value ?? fallback;
@@ -33572,7 +33840,7 @@ var init_runner = __esm({
33572
33840
  };
33573
33841
  publicServerFailureCode = (value) => value !== null && /^[a-z0-9][a-z0-9._-]{0,95}$/u.test(value) ? value : null;
33574
33842
  attemptStartRetryFallbackMs = (retryCount) => Math.min(
33575
- 1e3 * 2 ** Math.min(Math.max(0, retryCount - 1), 4),
33843
+ HOST_RUNTIME_POLICY.attempt_start_retry_base_ms * BACKOFF_GROWTH_FACTOR ** Math.min(Math.max(0, retryCount - 1), HOST_RUNTIME_POLICY.attempt_start_retry_exponent_max),
33576
33844
  MAX_ATTEMPT_START_RETRY_DELAY_MS
33577
33845
  );
33578
33846
  exactJson2 = (left, right) => JSON.stringify(left) === JSON.stringify(right);
@@ -33831,7 +34099,7 @@ var init_runner = __esm({
33831
34099
  assertLocalCredentialIdentity(localState, refreshed.credential);
33832
34100
  credential = refreshed.credential;
33833
34101
  access7 = refreshed;
33834
- accessExpiresAt = now() + refreshed.expiresIn * 1e3;
34102
+ accessExpiresAt = now() + refreshed.expiresIn * MS_PER_SECOND;
33835
34103
  return refreshed.accessToken;
33836
34104
  })();
33837
34105
  try {
@@ -33843,7 +34111,7 @@ var init_runner = __esm({
33843
34111
  await refreshAccessToken({ signal: this.options.signal });
33844
34112
  const tokenSource = {
33845
34113
  accessToken: async (requestOptions) => {
33846
- if (!access7 || accessExpiresAt - now() <= 5e3) {
34114
+ if (!access7 || accessExpiresAt - now() <= HOST_RUNTIME_POLICY.access_token_refresh_lead_ms) {
33847
34115
  return refreshAccessToken(requestOptions);
33848
34116
  }
33849
34117
  return access7.accessToken;
@@ -33944,7 +34212,7 @@ var init_runner = __esm({
33944
34212
  const runtimeState = await readInferenceAgentRuntimeState(
33945
34213
  agentRuntimeSettings.statePath
33946
34214
  );
33947
- const retryAtMs = failure2.dispatchOutcome === "outcome_unknown" || failure2.category === "auth" && settings.adapterId === "deepseek-harness" ? null : error48.retryAtMs !== null && error48.retryAtMs > now() ? error48.retryAtMs : now() + (failure2.category === "quota" || failure2.code === "quota_exceeded" ? DEFAULT_AGENT_QUOTA_COOLDOWN_MS : failure2.category === "auth" ? DEFAULT_CODEX_ACCOUNT_COOLDOWN_MS : failure2.code === "provider_rate_limited" || failure2.code === "codex_rate_limited" ? DEFAULT_AGENT_RATE_LIMIT_COOLDOWN_MS : DEFAULT_AGENT_TRANSIENT_COOLDOWN_MS);
34215
+ const retryAtMs = failure2.dispatchOutcome === "outcome_unknown" || failure2.category === "auth" && settings.adapterId === "deepseek-harness" ? null : error48.retryAtMs !== null && error48.retryAtMs > now() ? error48.retryAtMs : now() + (failure2.category === "quota" || failure2.code === "quota_exceeded" ? DEFAULT_QUOTA_COOLDOWN_MS : failure2.category === "auth" ? DEFAULT_AGENT_AUTH_COOLDOWN_MS : failure2.code === "provider_rate_limited" || failure2.code === "codex_rate_limited" ? DEFAULT_AGENT_RATE_LIMIT_COOLDOWN_MS : DEFAULT_AGENT_TRANSIENT_COOLDOWN_MS);
33948
34216
  await writeInferenceAgentFailureFence(agentRuntimeSettings.statePath, {
33949
34217
  schema_version: "vtx_inference_agent_failure_fence_v1",
33950
34218
  adapter_id: settings.adapterId,
@@ -33977,7 +34245,7 @@ var init_runner = __esm({
33977
34245
  const retained = await readInferenceAgentRuntimeState(agentRuntimeSettings.statePath);
33978
34246
  const fence = await readInferenceAgentFailureFence(agentRuntimeSettings.statePath);
33979
34247
  if (!fence || !canReplayFencedAgentTerminal(retained, fence)) return;
33980
- await sleep4(1e3, agentIdleSignal).catch(() => void 0);
34248
+ await sleep4(HOST_RUNTIME_POLICY.agent_idle_retry_ms, agentIdleSignal).catch(() => void 0);
33981
34249
  continue;
33982
34250
  }
33983
34251
  try {
@@ -33997,7 +34265,7 @@ var init_runner = __esm({
33997
34265
  const retained = await readInferenceAgentRuntimeState(agentRuntimeSettings.statePath);
33998
34266
  if (!retained || retained.schema_version !== "vtx_inference_agent_runtime_v3" || !retained.pending_turn?.terminal_receipt) return;
33999
34267
  if (this.options.once) return;
34000
- await sleep4(1e3, agentIdleSignal).catch((error49) => {
34268
+ await sleep4(HOST_RUNTIME_POLICY.agent_idle_retry_ms, agentIdleSignal).catch((error49) => {
34001
34269
  if (!quiesceRequested) throw error49;
34002
34270
  });
34003
34271
  continue;
@@ -34011,7 +34279,7 @@ var init_runner = __esm({
34011
34279
  });
34012
34280
  if (this.options.once) return;
34013
34281
  try {
34014
- await sleep4(1e3, agentIdleSignal).catch((error49) => {
34282
+ await sleep4(HOST_RUNTIME_POLICY.agent_idle_retry_ms, agentIdleSignal).catch((error49) => {
34015
34283
  if (!quiesceRequested) throw error49;
34016
34284
  });
34017
34285
  } catch {
@@ -34132,7 +34400,7 @@ var init_runner = __esm({
34132
34400
  if (!retryableRemoteError(error48) || error48 instanceof ExternalInferenceMcpError && error48.definitivelyNotApplied || attempt === settings.remoteRetryLimit) throw error48;
34133
34401
  const requestedRetryDelay = remoteRetryAfterMs(
34134
34402
  error48,
34135
- Math.min(250 * attempt, 1e3)
34403
+ Math.min(HOST_RUNTIME_POLICY.remote_retry_backoff_step_ms * attempt, HOST_RUNTIME_POLICY.remote_retry_backoff_max_ms)
34136
34404
  );
34137
34405
  const remaining = boundary.deadlineAtMs === void 0 ? Number.POSITIVE_INFINITY : Math.max(0, boundary.deadlineAtMs - now());
34138
34406
  if (requestedRetryDelay < 1 || requestedRetryDelay >= remaining) {
@@ -34265,7 +34533,7 @@ var init_runner = __esm({
34265
34533
  if (!wasRegistered && receipt.registered && (!receipt.advertisement_expires_at || Date.parse(receipt.advertisement_expires_at) - now() <= settings.advertisementRefreshLeadMs)) {
34266
34534
  await publishAdvertisement("healthy", true);
34267
34535
  }
34268
- let providerRetryAtMs = this.options.codexRateLimits && codexAccountRateLimitReached(this.options.codexRateLimits) ? codexRateLimitRetryAtMs(this.options.codexRateLimits) ?? now() + DEFAULT_CODEX_ACCOUNT_COOLDOWN_MS : null;
34536
+ let providerRetryAtMs = this.options.codexRateLimits && codexAccountRateLimitReached(this.options.codexRateLimits) ? codexRateLimitRetryAtMs(this.options.codexRateLimits) ?? now() + DEFAULT_QUOTA_COOLDOWN_MS : null;
34269
34537
  let providerCooldownReason = providerRetryAtMs === null ? null : "provider_limit_snapshot";
34270
34538
  let providerFailureRetryAtMs = 0;
34271
34539
  let providerFailureCooldownReason = null;
@@ -34932,7 +35200,7 @@ var init_runner = __esm({
34932
35200
  const refreshVersion = providerCooldownVersion;
34933
35201
  const refreshStartedAt = now();
34934
35202
  const refreshedRateLimits = await this.dependencies.codexAdapter.readAccountRateLimits(
34935
- Date.now() + Math.min(2e3, settings.hostHeartbeatMs),
35203
+ Date.now() + Math.min(HOST_RUNTIME_POLICY.rate_limit_read_timeout_max_ms, settings.hostHeartbeatMs),
34936
35204
  agentAbort.signal
34937
35205
  );
34938
35206
  if (agentAbort.signal.aborted || refreshVersion !== providerCooldownVersion) return;
@@ -34946,7 +35214,7 @@ var init_runner = __esm({
34946
35214
  );
34947
35215
  providerQuotaRecoveryObservedAtMs = usableSnapshot ? refreshStartedAt : null;
34948
35216
  retainKnownQuotaWindows(providerRateLimits.rateLimits);
34949
- const refreshedRetryAt = codexAccountRateLimitReached(providerRateLimits) ? codexRateLimitRetryAtMs(providerRateLimits) ?? refreshedAt + DEFAULT_CODEX_ACCOUNT_COOLDOWN_MS : null;
35217
+ const refreshedRetryAt = codexAccountRateLimitReached(providerRateLimits) ? codexRateLimitRetryAtMs(providerRateLimits) ?? refreshedAt + DEFAULT_QUOTA_COOLDOWN_MS : null;
34950
35218
  if (refreshedRetryAt !== null && refreshedRetryAt > refreshedAt) {
34951
35219
  providerRetryAtMs = Math.max(providerRetryAtMs ?? 0, refreshedRetryAt);
34952
35220
  providerCooldownReason = "provider_limit_snapshot";
@@ -35009,7 +35277,7 @@ var init_runner = __esm({
35009
35277
  requestDrain("advertisement_failed");
35010
35278
  break;
35011
35279
  }
35012
- nextAdvertisementAttemptAt = now() + remoteRetryAfterMs(error48, 1e3);
35280
+ nextAdvertisementAttemptAt = now() + remoteRetryAfterMs(error48, HOST_RUNTIME_POLICY.remote_retry_fallback_ms);
35013
35281
  nextClaimAt = Math.max(nextClaimAt, nextAdvertisementAttemptAt);
35014
35282
  }
35015
35283
  }
@@ -35129,7 +35397,7 @@ var init_runner = __esm({
35129
35397
  }
35130
35398
  } else if (!this.options.signal?.aborted && retryableRemoteError(error48)) {
35131
35399
  const rejectedAtMs = now();
35132
- const retryAtMs = rejectedAtMs + remoteRetryAfterMs(error48, 1e3);
35400
+ const retryAtMs = rejectedAtMs + remoteRetryAfterMs(error48, HOST_RUNTIME_POLICY.remote_retry_fallback_ms);
35133
35401
  if (error48 instanceof ExternalInferenceMcpError && error48.serverFailureCode === "host_not_claimable") {
35134
35402
  claimAvailabilityBackoff = { untilMs: retryAtMs, rejectedAtMs };
35135
35403
  } else {
@@ -36488,7 +36756,7 @@ var init_runner = __esm({
36488
36756
  );
36489
36757
  }
36490
36758
  state2 = await this.upgradeLegacyRuntimeState(recoveredState, signal);
36491
- if (!state2) return this.now() + (this.options.idlePollMs ?? 5e3);
36759
+ if (!state2) return this.now() + (this.options.idlePollMs ?? HOST_RUNTIME_POLICY.agent_idle_poll_ms);
36492
36760
  } else if (recoveredState?.schema_version === "vtx_codex_agent_runtime_v2") {
36493
36761
  if (this.options.adapterId !== "codex") {
36494
36762
  throw new InferenceHostRunnerError(
@@ -36518,7 +36786,7 @@ var init_runner = __esm({
36518
36786
  host_id: this.options.hostId,
36519
36787
  requested_at: nowIso()
36520
36788
  }, { signal });
36521
- if (!assignment2) return this.now() + (this.options.idlePollMs ?? 5e3);
36789
+ if (!assignment2) return this.now() + (this.options.idlePollMs ?? HOST_RUNTIME_POLICY.agent_idle_poll_ms);
36522
36790
  state2 = {
36523
36791
  schema_version: "vtx_inference_agent_runtime_v3",
36524
36792
  adapter_id: this.options.adapterId,
@@ -36535,11 +36803,11 @@ var init_runner = __esm({
36535
36803
  if (persistedWakeAtMs > this.now()) {
36536
36804
  const wakeOutcome = await this.waitUntilWake(persistedWakeAtMs, signal);
36537
36805
  if (wakeOutcome !== "ready") {
36538
- return this.now() + (this.options.idlePollMs ?? 5e3);
36806
+ return this.now() + (this.options.idlePollMs ?? HOST_RUNTIME_POLICY.agent_idle_poll_ms);
36539
36807
  }
36540
36808
  const rereadState = await readInferenceAgentRuntimeState(this.options.statePath);
36541
36809
  if (rereadState?.schema_version !== "vtx_inference_agent_runtime_v3" || rereadState.adapter_id !== this.options.adapterId) {
36542
- return this.now() + (this.options.idlePollMs ?? 5e3);
36810
+ return this.now() + (this.options.idlePollMs ?? HOST_RUNTIME_POLICY.agent_idle_poll_ms);
36543
36811
  }
36544
36812
  state2 = rereadState;
36545
36813
  }
@@ -36577,7 +36845,7 @@ var init_runner = __esm({
36577
36845
  );
36578
36846
  }
36579
36847
  await this.releaseForHostStop(terminal.terminal_receipt.failure_code ?? "provider_failure");
36580
- return this.now() + (this.options.idlePollMs ?? 5e3);
36848
+ return this.now() + (this.options.idlePollMs ?? HOST_RUNTIME_POLICY.agent_idle_poll_ms);
36581
36849
  }
36582
36850
  if (!terminal.next_wake_at) {
36583
36851
  throw new InferenceHostRunnerError(
@@ -36619,7 +36887,7 @@ var init_runner = __esm({
36619
36887
  }, { signal });
36620
36888
  if (preTurnHeartbeat.directive === "cancel") {
36621
36889
  await this.handleCancelledAssignment(state2, signal);
36622
- return this.now() + (this.options.idlePollMs ?? 5e3);
36890
+ return this.now() + (this.options.idlePollMs ?? HOST_RUNTIME_POLICY.agent_idle_poll_ms);
36623
36891
  }
36624
36892
  if (this.options.quiesceSignal?.aborted) return this.now();
36625
36893
  assignment = {
@@ -36650,7 +36918,7 @@ var init_runner = __esm({
36650
36918
  }
36651
36919
  latestLeaseExpiry = heartbeat.lease_expires_at;
36652
36920
  await this.sleep(
36653
- this.options.heartbeatIntervalMs ?? 3e3,
36921
+ this.options.heartbeatIntervalMs ?? HOST_RUNTIME_POLICY.agent_heartbeat_interval_ms,
36654
36922
  turnAbort.signal
36655
36923
  );
36656
36924
  }
@@ -36658,7 +36926,7 @@ var init_runner = __esm({
36658
36926
  if (!turnAbort.signal.aborted) turnAbort.abort(error48);
36659
36927
  });
36660
36928
  try {
36661
- const deadlineAtMs = this.now() + (this.options.turnTimeoutMs ?? 10 * 6e4);
36929
+ const deadlineAtMs = this.now() + (this.options.turnTimeoutMs ?? HOST_RUNTIME_POLICY.agent_turn_timeout_ms);
36662
36930
  const dataRequestTimeoutMs = this.options.dataRequestTimeoutMs ?? await loadInferenceAgentDataRequestTimeoutMs();
36663
36931
  if (!Number.isSafeInteger(dataRequestTimeoutMs) || dataRequestTimeoutMs < 1) {
36664
36932
  throw new InferenceHostRunnerError("invalid_configuration", "Agent data request timeout is invalid.");
@@ -36844,7 +37112,7 @@ var init_runner = __esm({
36844
37112
  let nextWakeAtMs = null;
36845
37113
  let wakeError;
36846
37114
  try {
36847
- nextWakeAtMs = wakeScheduledAtMs + parseInferenceAgentWake(result.turn.text, assignment) * 1e3;
37115
+ nextWakeAtMs = wakeScheduledAtMs + parseInferenceAgentWake(result.turn.text, assignment) * MS_PER_SECOND;
36848
37116
  } catch (error48) {
36849
37117
  wakeError = error48;
36850
37118
  }
@@ -36886,7 +37154,7 @@ var init_runner = __esm({
36886
37154
  await writeInferenceAgentRuntimeState(this.options.statePath, state2);
36887
37155
  await this.handleCancelledAssignment(state2);
36888
37156
  }
36889
- return this.now() + (this.options.idlePollMs ?? 5e3);
37157
+ return this.now() + (this.options.idlePollMs ?? HOST_RUNTIME_POLICY.agent_idle_poll_ms);
36890
37158
  }
36891
37159
  latestLeaseExpiry = wakeHeartbeat.lease_expires_at;
36892
37160
  state2 = {
@@ -36978,7 +37246,7 @@ var init_runner = __esm({
36978
37246
  }
36979
37247
  if (!cancelled) throw error48;
36980
37248
  await this.handleCancelledAssignment(state2);
36981
- return this.now() + (this.options.idlePollMs ?? 5e3);
37249
+ return this.now() + (this.options.idlePollMs ?? HOST_RUNTIME_POLICY.agent_idle_poll_ms);
36982
37250
  } finally {
36983
37251
  heartbeatStopped = true;
36984
37252
  turnAbort.abort();
@@ -37062,7 +37330,7 @@ var init_runner = __esm({
37062
37330
  await clearInferenceAgentRuntimeState(this.options.statePath);
37063
37331
  }
37064
37332
  async waitUntilWake(nextWakeAtMs, signal) {
37065
- const heartbeatIntervalMs = this.options.heartbeatIntervalMs ?? 3e3;
37333
+ const heartbeatIntervalMs = this.options.heartbeatIntervalMs ?? HOST_RUNTIME_POLICY.agent_heartbeat_interval_ms;
37066
37334
  while (!this.stopped && !signal?.aborted && !this.options.quiesceSignal?.aborted && this.now() < nextWakeAtMs) {
37067
37335
  const waitSignal = this.options.quiesceSignal ? AbortSignal.any([this.options.quiesceSignal, ...signal ? [signal] : []]) : signal;
37068
37336
  try {
@@ -44543,7 +44811,7 @@ import { createWriteStream, readFileSync as readFileSync2 } from "node:fs";
44543
44811
  import { access as access6, chmod as chmod4, mkdir as mkdir5, readFile as readFile12, rm as rm14, writeFile as writeFile5 } from "node:fs/promises";
44544
44812
  import { homedir as homedir4 } from "node:os";
44545
44813
  import { dirname as dirname15, join as join16, resolve as resolve12 } from "node:path";
44546
- var SERVICE_NAME, SYSTEMD_UNIT, LAUNCHD_LABEL, SERVICE_COOPERATIVE_STOP_SECONDS, SERVICE_UPDATE_STARTUP_SECONDS, INFERENCE_HOST_SERVICE_DRAIN_COMMAND, INFERENCE_HOST_SERVICE_QUIESCE_COMMAND, InferenceHostBootstrapRestartRequiredError, inferenceHostServiceChildEnvironment, isWindowsSubsystemForLinux, inferenceHostServiceManifestPath, inferenceHostServiceDesiredPath, inferenceHostServiceLogPath, inferenceHostServiceRuntimePath, xmlEscape, plistEscape, systemdQuote, defaultRunCommand, probeInferenceHostLauncher, managerName, assertRuntimeEnvironment, withoutConcurrencyLimit, assertServicePath, manifestGeneration, assertWorker, assertManifest, assertServiceRuntimeState, assertDesiredState, readInferenceHostServiceManifest, readManifestAcrossAtomicReplacement, readInferenceHostServiceRuntime, readRuntimeAcrossAtomicReplacement, readInferenceHostServiceDesired, readDesiredAcrossAtomicReplacement, writeDesired, runtimeEnvironment, serviceBootstrapArguments, windowsOwnedCommandLine, vbScriptString, windowsServiceLauncher, windowsTaskXml, systemdUnit, launchAgentPlist, sameWorker, sameServiceDefinition, sameWorkerSet, InferenceHostServiceManager, appendServiceLog, spawnInferenceHostServiceChild, runInferenceHostServiceSupervisor;
44814
+ var SERVICE_NAME, SYSTEMD_UNIT, LAUNCHD_LABEL, SERVICE_POLICY, SERVICE_COOPERATIVE_STOP_SECONDS, pollAttemptsWithin, INFERENCE_HOST_SERVICE_DRAIN_COMMAND, INFERENCE_HOST_SERVICE_QUIESCE_COMMAND, InferenceHostBootstrapRestartRequiredError, inferenceHostServiceChildEnvironment, isWindowsSubsystemForLinux, inferenceHostServiceManifestPath, inferenceHostServiceDesiredPath, inferenceHostServiceLogPath, inferenceHostServiceRuntimePath, xmlEscape, plistEscape, systemdQuote, defaultRunCommand, probeInferenceHostLauncher, managerName, assertRuntimeEnvironment, withoutConcurrencyLimit, assertServicePath, manifestGeneration, assertWorker, assertManifest, assertServiceRuntimeState, assertDesiredState, readInferenceHostServiceManifest, readManifestAcrossAtomicReplacement, readInferenceHostServiceRuntime, readRuntimeAcrossAtomicReplacement, readInferenceHostServiceDesired, readDesiredAcrossAtomicReplacement, writeDesired, runtimeEnvironment, serviceBootstrapArguments, windowsOwnedCommandLine, vbScriptString, windowsServiceLauncher, windowsTaskXml, systemdUnit, launchAgentPlist, sameWorker, sameServiceDefinition, sameWorkerSet, InferenceHostServiceManager, appendServiceLog, spawnInferenceHostServiceChild, runInferenceHostServiceSupervisor;
44547
44815
  var init_service = __esm({
44548
44816
  "lib/inference-host/service.ts"() {
44549
44817
  "use strict";
@@ -44553,13 +44821,15 @@ var init_service = __esm({
44553
44821
  init_service_launcher_state();
44554
44822
  init_agent_cli_release();
44555
44823
  init_runtime_policy_generated();
44824
+ init_constants();
44556
44825
  init_durable_adapter();
44557
44826
  init_config2();
44558
44827
  SERVICE_NAME = "VTX Macro Inference Host";
44559
44828
  SYSTEMD_UNIT = "vtx-inference-host.service";
44560
44829
  LAUNCHD_LABEL = "com.vtxmacro.inference-host";
44561
- SERVICE_COOPERATIVE_STOP_SECONDS = 75;
44562
- SERVICE_UPDATE_STARTUP_SECONDS = 600;
44830
+ SERVICE_POLICY = runtime_policy_generated_default.external_inference.service;
44831
+ SERVICE_COOPERATIVE_STOP_SECONDS = Math.ceil(SERVICE_POLICY.cooperative_stop_timeout_ms / MS_PER_SECOND);
44832
+ pollAttemptsWithin = (milliseconds) => Math.ceil(milliseconds / SERVICE_POLICY.startup_poll_interval_ms);
44563
44833
  INFERENCE_HOST_SERVICE_DRAIN_COMMAND = "vtx-inference-host-service-drain-v1";
44564
44834
  INFERENCE_HOST_SERVICE_QUIESCE_COMMAND = "vtx-inference-host-service-quiesce-v1";
44565
44835
  InferenceHostBootstrapRestartRequiredError = class extends Error {
@@ -44980,9 +45250,9 @@ WantedBy=default.target
44980
45250
  this.sleep = dependencies.sleep ?? (async (milliseconds) => {
44981
45251
  await new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
44982
45252
  });
44983
- this.stopWaitAttempts = dependencies.stopWaitAttempts ?? SERVICE_COOPERATIVE_STOP_SECONDS * 4;
44984
- this.startWaitAttempts = dependencies.startWaitAttempts ?? runtime_policy_generated_default.external_inference.service.startup_max_attempts;
44985
- this.reconcileWaitAttempts = dependencies.reconcileWaitAttempts ?? SERVICE_COOPERATIVE_STOP_SECONDS * 4;
45253
+ this.stopWaitAttempts = dependencies.stopWaitAttempts ?? pollAttemptsWithin(SERVICE_POLICY.cooperative_stop_timeout_ms);
45254
+ this.startWaitAttempts = dependencies.startWaitAttempts ?? SERVICE_POLICY.startup_max_attempts;
45255
+ this.reconcileWaitAttempts = dependencies.reconcileWaitAttempts ?? pollAttemptsWithin(SERVICE_POLICY.cooperative_stop_timeout_ms);
44986
45256
  this.confirmInitialReadiness = dependencies.confirmInitialReadiness ?? true;
44987
45257
  this.acquireProcessLock = dependencies.acquireProcessLock ?? acquireInferenceHostProcessLock;
44988
45258
  managerName(this.platform);
@@ -45024,17 +45294,17 @@ WantedBy=default.target
45024
45294
  }
45025
45295
  async withControlLock(operation) {
45026
45296
  let lock2 = null;
45027
- for (let attempt = 0; attempt < 400; attempt += 1) {
45297
+ for (let attempt = 0; attempt < SERVICE_POLICY.control_lock_wait_attempts; attempt += 1) {
45028
45298
  try {
45029
45299
  lock2 = await this.acquireProcessLock(this.controlLockPath());
45030
45300
  break;
45031
45301
  } catch (error48) {
45032
45302
  if (!/already owns/iu.test(error48 instanceof Error ? error48.message : "")) throw error48;
45033
- await this.sleep(250);
45303
+ await this.sleep(SERVICE_POLICY.control_lock_retry_interval_ms);
45034
45304
  }
45035
45305
  }
45036
45306
  if (!lock2) {
45037
- throw new Error("Another inference-host service control operation did not finish within 100 seconds.");
45307
+ throw new Error(`Another inference-host service control operation did not finish within ${SERVICE_POLICY.control_lock_wait_attempts * SERVICE_POLICY.control_lock_retry_interval_ms / MS_PER_SECOND} seconds.`);
45038
45308
  }
45039
45309
  try {
45040
45310
  return await operation();
@@ -45112,9 +45382,9 @@ WantedBy=default.target
45112
45382
  for (let attempt = 0; attempt < this.startWaitAttempts; attempt += 1) {
45113
45383
  const status = await this.status();
45114
45384
  if (status.manager_active) return status;
45115
- await this.sleep(runtime_policy_generated_default.external_inference.service.startup_poll_interval_ms);
45385
+ await this.sleep(SERVICE_POLICY.startup_poll_interval_ms);
45116
45386
  }
45117
- throw new Error(`Background service did not reach an active state within ${this.startWaitAttempts * runtime_policy_generated_default.external_inference.service.startup_poll_interval_ms / 1e3} seconds.`);
45387
+ throw new Error(`Background service did not reach an active state within ${this.startWaitAttempts * SERVICE_POLICY.startup_poll_interval_ms / MS_PER_SECOND} seconds.`);
45118
45388
  }
45119
45389
  async restoreRunningSupervisor(manifest, preserveGeneration = false, targetInstanceName) {
45120
45390
  const previousRuntime = await readRuntimeAcrossAtomicReplacement(this.runtimePath()).catch(() => null);
@@ -45176,7 +45446,7 @@ ${result.stderr}`)) {
45176
45446
  const allReady = runtime.workers.every((worker) => worker.state === "running");
45177
45447
  if (exactWorkerSet && (targetInstanceName ? target?.state === "running" : allReady)) {
45178
45448
  consecutiveReadyObservations += 1;
45179
- if (consecutiveReadyObservations >= 2) return runtime;
45449
+ if (consecutiveReadyObservations >= SERVICE_POLICY.ready_consecutive_observations) return runtime;
45180
45450
  } else {
45181
45451
  consecutiveReadyObservations = 0;
45182
45452
  }
@@ -45189,7 +45459,7 @@ ${result.stderr}`)) {
45189
45459
  if (runtime?.rejected_manifest_generation === manifest.generation) {
45190
45460
  throw new Error("Inference-host supervisor rejected the updated worker set.");
45191
45461
  }
45192
- await this.sleep(250);
45462
+ await this.sleep(SERVICE_POLICY.startup_poll_interval_ms);
45193
45463
  }
45194
45464
  throw new Error(
45195
45465
  targetInstanceName ? `Inference-host supervisor did not confirm worker ${targetInstanceName} ready before timeout.` : "Inference-host supervisor did not confirm the updated worker set before timeout."
@@ -45257,7 +45527,7 @@ ${started.stderr}`)) {
45257
45527
  await this.waitForManifestApplied(
45258
45528
  manifest,
45259
45529
  targetInstanceName,
45260
- Math.max(this.reconcileWaitAttempts, SERVICE_UPDATE_STARTUP_SECONDS * 4)
45530
+ Math.max(this.reconcileWaitAttempts, pollAttemptsWithin(SERVICE_POLICY.update_readiness_timeout_ms))
45261
45531
  );
45262
45532
  }
45263
45533
  }
@@ -45331,7 +45601,7 @@ ${cleanup.stderr}`)) {
45331
45601
  // restores the previous manifest. Never give rollback less than
45332
45602
  // a bounded 100-observation confirmation window, even when a
45333
45603
  // caller intentionally shortens forward-readiness checks.
45334
- Math.max(this.reconcileWaitAttempts, 100)
45604
+ Math.max(this.reconcileWaitAttempts, SERVICE_POLICY.rollback_confirmation_min_attempts)
45335
45605
  );
45336
45606
  } catch (rollbackError) {
45337
45607
  throw new Error(
@@ -45571,7 +45841,7 @@ ${result.stderr}`)) {
45571
45841
  serviceReleased = true;
45572
45842
  break;
45573
45843
  }
45574
- await this.sleep(250);
45844
+ await this.sleep(SERVICE_POLICY.startup_poll_interval_ms);
45575
45845
  }
45576
45846
  if (!serviceReleased) {
45577
45847
  throw new Error(
@@ -45796,7 +46066,7 @@ ${result.stderr}`)) {
45796
46066
  cooperativeStopTimer = setTimeout(() => {
45797
46067
  cooperativeStopTimedOut = true;
45798
46068
  child.kill("SIGKILL");
45799
- }, SERVICE_COOPERATIVE_STOP_SECONDS * 1e3);
46069
+ }, SERVICE_POLICY.cooperative_stop_timeout_ms);
45800
46070
  cooperativeStopTimer.unref();
45801
46071
  };
45802
46072
  if (signal.aborted) onAbort();
@@ -45977,7 +46247,7 @@ ${result.stderr}`)) {
45977
46247
  if (readinessSignalled) return;
45978
46248
  readinessSignalled = true;
45979
46249
  readinessTask = (async () => {
45980
- await sleep4(500);
46250
+ await sleep4(SERVICE_POLICY.worker_readiness_settle_ms);
45981
46251
  if (!launchSettled && !attemptController.signal.aborted && !record5.controller.signal.aborted && !signal.aborted) {
45982
46252
  await updateRecord(record5, "running");
45983
46253
  }
@@ -46000,8 +46270,8 @@ ${result.stderr}`)) {
46000
46270
  throw new Error("worker_cooperative_stop_timeout");
46001
46271
  }
46002
46272
  if (signal.aborted || quiesceSignal.aborted || record5.controller.signal.aborted || !await readDesiredAcrossAtomicReplacement(desiredPath)) break;
46003
- failures = result.uptimeMs >= runtime_policy_generated_default.external_inference.service.restart_stable_uptime_ms ? 0 : failures + 1;
46004
- const retryAfterMs = Math.min(runtime_policy_generated_default.external_inference.service.restart_backoff_base_ms * 2 ** Math.min(failures, runtime_policy_generated_default.external_inference.service.restart_exponent_max), runtime_policy_generated_default.external_inference.service.restart_backoff_max_ms);
46273
+ failures = result.uptimeMs >= SERVICE_POLICY.restart_stable_uptime_ms ? 0 : failures + 1;
46274
+ const retryAfterMs = Math.min(SERVICE_POLICY.restart_backoff_base_ms * BACKOFF_GROWTH_FACTOR ** Math.min(failures, SERVICE_POLICY.restart_exponent_max), SERVICE_POLICY.restart_backoff_max_ms);
46005
46275
  await updateRecord(record5, "failed", "worker_exited");
46006
46276
  await appendServiceLog(serviceManifest.log_path, "worker_exited", {
46007
46277
  instance_name: record5.worker.instance_name,
@@ -46015,7 +46285,7 @@ ${result.stderr}`)) {
46015
46285
  if (error48 instanceof Error && error48.message === "worker_cooperative_stop_timeout") throw error48;
46016
46286
  if (signal.aborted || quiesceSignal.aborted || record5.controller.signal.aborted) break;
46017
46287
  failures += 1;
46018
- const retryAfterMs = Math.min(runtime_policy_generated_default.external_inference.service.restart_backoff_base_ms * 2 ** Math.min(failures, runtime_policy_generated_default.external_inference.service.restart_exponent_max), runtime_policy_generated_default.external_inference.service.restart_backoff_max_ms);
46288
+ const retryAfterMs = Math.min(SERVICE_POLICY.restart_backoff_base_ms * BACKOFF_GROWTH_FACTOR ** Math.min(failures, SERVICE_POLICY.restart_exponent_max), SERVICE_POLICY.restart_backoff_max_ms);
46019
46289
  await updateRecord(record5, "failed", "worker_launch_failed");
46020
46290
  await appendServiceLog(serviceManifest.log_path, "worker_launch_failed", {
46021
46291
  instance_name: record5.worker.instance_name,
@@ -46111,7 +46381,7 @@ ${result.stderr}`)) {
46111
46381
  if (!storedNext) throw new Error("Inference-host service manifest is missing.");
46112
46382
  const next = withServiceScript(storedNext);
46113
46383
  if (next.generation !== appliedManifest.generation && next.generation !== rejectedManifestGeneration) await reconcile(next);
46114
- await sleep4(250);
46384
+ await sleep4(SERVICE_POLICY.supervisor_manifest_poll_interval_ms);
46115
46385
  }
46116
46386
  if (quiesceSignal.aborted && !signal.aborted) {
46117
46387
  let finished = false;
@@ -46120,7 +46390,7 @@ ${result.stderr}`)) {
46120
46390
  return results;
46121
46391
  });
46122
46392
  while (!finished && !signal.aborted && await readDesiredAcrossAtomicReplacement(desiredPath)) {
46123
- await Promise.race([completion, sleep4(250)]);
46393
+ await Promise.race([completion, sleep4(SERVICE_POLICY.supervisor_manifest_poll_interval_ms)]);
46124
46394
  }
46125
46395
  if (!finished) {
46126
46396
  await drainWorkers();
@@ -46340,6 +46610,8 @@ var init_cli = __esm({
46340
46610
  init_define_VTX_EXO_POLICY();
46341
46611
  init_define_VTX_GROK_POLICY();
46342
46612
  init_define_VTX_PI_MODEL_POLICY();
46613
+ init_runtime_policy_generated();
46614
+ init_constants();
46343
46615
  init_external_inference_contract();
46344
46616
  init_agent_cli_release();
46345
46617
  init_reauthorize();
@@ -46377,8 +46649,8 @@ var init_cli = __esm({
46377
46649
  foregroundHostLockPath = (config2) => `${config2.processLockPath}.foreground`;
46378
46650
  credentialLifecycleLockPath = (config2) => `${inferenceHostCredentialContextPath(config2)}.lock`;
46379
46651
  serviceRecoveryCommandLockPath = (config2) => `${config2.supervisorProcessLockPath}.service-recovery-command`;
46380
- AGENT_HEARTBEAT_INTERVAL_MS = 3e3;
46381
- AGENT_HEARTBEAT_MAX_RETRY_DELAY_MS = 9e3;
46652
+ AGENT_HEARTBEAT_INTERVAL_MS = runtime_policy_generated_default.external_inference.host_runtime.agent_heartbeat_interval_ms;
46653
+ AGENT_HEARTBEAT_MAX_RETRY_DELAY_MS = runtime_policy_generated_default.external_inference.host_runtime.agent_heartbeat_max_retry_delay_ms;
46382
46654
  retryableAgentHeartbeatError = (error48) => {
46383
46655
  if (!(error48 instanceof ExternalInferenceMcpError)) return false;
46384
46656
  if (error48.code === "network_error" || error48.code === "request_timeout") return true;
@@ -47244,7 +47516,7 @@ Waiting for approval...
47244
47516
  const status = await (dependencies.loginCodex ?? loginCodexSubscription)({
47245
47517
  binary,
47246
47518
  codexHome: config2.codexHomePath,
47247
- deadlineAtMs: Date.now() + 15 * 6e4,
47519
+ deadlineAtMs: Date.now() + runtime_policy_generated_default.external_inference.host_runtime.codex_login_timeout_ms,
47248
47520
  signal: cancellation.signal,
47249
47521
  onChallenge: async (challenge) => {
47250
47522
  emitStdout(parsed.json ? `${JSON.stringify({
@@ -47294,7 +47566,7 @@ Waiting for approval...
47294
47566
  await (dependencies.logoutCodex ?? logoutCodexSubscription)({
47295
47567
  binary,
47296
47568
  codexHome: config2.codexHomePath,
47297
- deadlineAtMs: Date.now() + 3e4,
47569
+ deadlineAtMs: Date.now() + runtime_policy_generated_default.external_inference.host_runtime.codex_command_timeout_ms,
47298
47570
  signal: cancellation.signal
47299
47571
  });
47300
47572
  return {
@@ -47941,7 +48213,7 @@ Waiting for approval...
47941
48213
  const preflight = await (dependencies.preflightCodex ?? preflightCodexSubscription)({
47942
48214
  binary: verifiedBinary,
47943
48215
  codexHome: config2.codexHomePath,
47944
- deadlineAtMs: Date.now() + 3e4,
48216
+ deadlineAtMs: Date.now() + runtime_policy_generated_default.external_inference.host_runtime.codex_command_timeout_ms,
47945
48217
  signal: cancellation.signal
47946
48218
  });
47947
48219
  const summary = await (dependencies.runForeground ?? defaultRunForeground)({
@@ -48129,7 +48401,7 @@ Waiting for approval...
48129
48401
  const sleep4 = dependencies.sleep ?? (async (milliseconds) => {
48130
48402
  await new Promise((resolve14) => setTimeout(resolve14, milliseconds));
48131
48403
  });
48132
- const stopAt = now().getTime() + parsed.waitSeconds * 1e3;
48404
+ const stopAt = now().getTime() + parsed.waitSeconds * MS_PER_SECOND;
48133
48405
  while (true) {
48134
48406
  const result = await withAgentCommandLock(config2, async () => {
48135
48407
  let state2 = await readInferenceForegroundAgentControlState(config2.statePath) ?? foregroundAgentControlState(session.localState.host_id, now().toISOString());
@@ -48655,7 +48927,7 @@ Waiting for approval...
48655
48927
  pendingHeartbeatRequest = heartbeatRequest;
48656
48928
  consecutiveHeartbeatFailures += 1;
48657
48929
  retryDelayMs = Math.min(
48658
- AGENT_HEARTBEAT_INTERVAL_MS * 2 ** Math.max(0, consecutiveHeartbeatFailures - 1),
48930
+ AGENT_HEARTBEAT_INTERVAL_MS * BACKOFF_GROWTH_FACTOR ** Math.max(0, consecutiveHeartbeatFailures - 1),
48659
48931
  AGENT_HEARTBEAT_MAX_RETRY_DELAY_MS
48660
48932
  );
48661
48933
  const message = `Agent-driven inference heartbeat was temporarily unavailable; retrying in ${retryDelayMs}ms.
@@ -48712,7 +48984,7 @@ Waiting for approval...
48712
48984
  if (!retryableAgentHeartbeatError(error48)) throw error48;
48713
48985
  consecutiveHeartbeatFailures += 1;
48714
48986
  retryDelayMs = Math.min(
48715
- AGENT_HEARTBEAT_INTERVAL_MS * 2 ** Math.max(0, consecutiveHeartbeatFailures - 1),
48987
+ AGENT_HEARTBEAT_INTERVAL_MS * BACKOFF_GROWTH_FACTOR ** Math.max(0, consecutiveHeartbeatFailures - 1),
48716
48988
  AGENT_HEARTBEAT_MAX_RETRY_DELAY_MS
48717
48989
  );
48718
48990
  emitStderr(parsed.json ? `${JSON.stringify({
@@ -48761,7 +49033,7 @@ Waiting for approval...
48761
49033
  const sleep4 = dependencies.sleep ?? (async (milliseconds) => {
48762
49034
  await new Promise((resolve14) => setTimeout(resolve14, milliseconds));
48763
49035
  });
48764
- const stopAt = now().getTime() + parsed.waitSeconds * 1e3;
49036
+ const stopAt = now().getTime() + parsed.waitSeconds * MS_PER_SECOND;
48765
49037
  while (true) {
48766
49038
  let pending3 = await readInferenceAgentNextState(config2.statePath);
48767
49039
  if (!pending3) {
@@ -49468,7 +49740,7 @@ Waiting for approval...
49468
49740
  const preflight = await (dependencies.preflightCodex ?? preflightCodexSubscription)({
49469
49741
  binary,
49470
49742
  codexHome: config2.codexHomePath,
49471
- deadlineAtMs: Date.now() + 3e4
49743
+ deadlineAtMs: Date.now() + runtime_policy_generated_default.external_inference.host_runtime.codex_command_timeout_ms
49472
49744
  });
49473
49745
  const status = await manager.install({
49474
49746
  adapter: "codex",
@@ -50219,7 +50491,7 @@ function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
50219
50491
  if (profileId) headers["x-profile-id"] = profileId.toString();
50220
50492
  return headers;
50221
50493
  }
50222
- var configuredApiTransport, getApiUrl, apiFetch, sleep, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, canUseClientGetRequestCache, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
50494
+ var configuredApiTransport, getApiUrl, apiFetch, sleep, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, canUseClientGetRequestCache, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
50223
50495
  var init_shared = __esm({
50224
50496
  "lib/api/shared.ts"() {
50225
50497
  "use strict";
@@ -50259,6 +50531,7 @@ var init_shared = __esm({
50259
50531
  clientGetRequestGenerations = /* @__PURE__ */ new Map();
50260
50532
  initializedClientGetRequestKeys = /* @__PURE__ */ new Set();
50261
50533
  CLIENT_GET_DEDUPE_TTL_MS = 2e3;
50534
+ CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS = 5e3;
50262
50535
  CLIENT_LLM_CONFIG_PRIME_TTL_MS = 1e4;
50263
50536
  AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.max_attempts;
50264
50537
  AUTH_BOOTSTRAP_RETRY_JITTER_MS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.jitter_milliseconds;
@@ -50281,19 +50554,19 @@ var init_shared = __esm({
50281
50554
  shareClientGetRequest = async (key, request, options) => {
50282
50555
  if (!canUseClientGetRequestCache(options?.cookie)) {
50283
50556
  if (options?.signal?.aborted) throw toAbortError(options.signal.reason);
50284
- return raceWithAbortSignal(request(), options?.signal);
50557
+ return raceWithAbortSignal(request(options?.signal), options?.signal);
50285
50558
  }
50286
50559
  const now = Date.now();
50287
50560
  const recent = recentClientGetResponses.get(key);
50288
50561
  if (recent && recent.expiresAt > now) return recent.value;
50289
50562
  if (recent) recentClientGetResponses.delete(key);
50290
50563
  if (options?.signal?.aborted) throw toAbortError(options.signal.reason);
50291
- if (options?.signal && !options.shareAbortScoped) return raceWithAbortSignal(request(), options.signal);
50564
+ if (options?.signal && !options.shareAbortScoped) return raceWithAbortSignal(request(options.signal), options.signal);
50292
50565
  const existing = inFlightClientGetRequests.get(key);
50293
50566
  if (existing) return raceWithAbortSignal(existing, options?.signal);
50294
50567
  const requestGeneration = clientGetRequestGenerations.get(key) ?? 0;
50295
50568
  initializedClientGetRequestKeys.add(key);
50296
- const promise2 = request().then((value) => {
50569
+ const promise2 = request(void 0).then((value) => {
50297
50570
  if ((clientGetRequestGenerations.get(key) ?? 0) === requestGeneration) {
50298
50571
  recentClientGetResponses.set(key, {
50299
50572
  expiresAt: Date.now() + (options?.ttlMs ?? CLIENT_GET_DEDUPE_TTL_MS),
@@ -50810,6 +51083,16 @@ var init_ai_status_auth_fallback_contract = __esm({
50810
51083
  }
50811
51084
  });
50812
51085
 
51086
+ // lib/navigation/same-origin.ts
51087
+ var init_same_origin = __esm({
51088
+ "lib/navigation/same-origin.ts"() {
51089
+ "use strict";
51090
+ init_define_VTX_EXO_POLICY();
51091
+ init_define_VTX_GROK_POLICY();
51092
+ init_define_VTX_PI_MODEL_POLICY();
51093
+ }
51094
+ });
51095
+
50813
51096
  // lib/auth/google-auth-url.ts
50814
51097
  var init_google_auth_url = __esm({
50815
51098
  "lib/auth/google-auth-url.ts"() {
@@ -50817,6 +51100,7 @@ var init_google_auth_url = __esm({
50817
51100
  init_define_VTX_EXO_POLICY();
50818
51101
  init_define_VTX_GROK_POLICY();
50819
51102
  init_define_VTX_PI_MODEL_POLICY();
51103
+ init_same_origin();
50820
51104
  }
50821
51105
  });
50822
51106
 
@@ -51673,7 +51957,7 @@ var init_local_breadcrumbs = __esm({
51673
51957
  });
51674
51958
 
51675
51959
  // lib/runtime/client-runtime-ownership-errors.ts
51676
- var CLIENT_RUNTIME_OWNERSHIP_ERROR_CODES, OWNERSHIP_CODE_SET, readField, readClientRuntimeOwnershipErrorCode, readClientRuntimeOwnershipLossScope, readStatus, LEASE_ENDED_CODES, clientRuntimeLeaseEndedFromCode, ownershipLossReasonFromCode, clientRuntimeReleasedFromCode, clientRuntimeSessionStoppedFromCode;
51960
+ var CLIENT_RUNTIME_OWNERSHIP_ERROR_CODES, OWNERSHIP_CODE_SET, readField, readClientRuntimeOwnershipErrorCode, readClientRuntimeOwnershipLossScope, readStatus, LEASE_ENDED_CODES, clientRuntimeLeaseEndedFromCode, AUTHORITY_ENDED_CODES, clientRuntimeAuthorityEndedFromCode, ownershipLossReasonFromCode, clientRuntimeReleasedFromCode, clientRuntimeSessionStoppedFromCode;
51677
51961
  var init_client_runtime_ownership_errors = __esm({
51678
51962
  "lib/runtime/client-runtime-ownership-errors.ts"() {
51679
51963
  "use strict";
@@ -51731,6 +52015,16 @@ var init_client_runtime_ownership_errors = __esm({
51731
52015
  }
51732
52016
  return (code === "runtime_owner_superseded" || code === "runtime_owner_released") && statusCode === 401;
51733
52017
  };
52018
+ AUTHORITY_ENDED_CODES = /* @__PURE__ */ new Set([
52019
+ ...LEASE_ENDED_CODES,
52020
+ "runtime_owner_superseded",
52021
+ "runtime_owner_released",
52022
+ "runtime_scheduler_instance_mismatch"
52023
+ ]);
52024
+ clientRuntimeAuthorityEndedFromCode = (error48) => {
52025
+ const code = readClientRuntimeOwnershipErrorCode(error48);
52026
+ return code !== null && AUTHORITY_ENDED_CODES.has(code);
52027
+ };
51734
52028
  ownershipLossReasonFromCode = (error48) => {
51735
52029
  const code = readClientRuntimeOwnershipErrorCode(error48);
51736
52030
  if (code === null) {
@@ -51795,7 +52089,7 @@ var init_billing = __esm({
51795
52089
  async function getRecentCandles(limit = 10, exchange = "kraken", symbol2 = "PI_XBTUSD", timeframe = "1m", signal) {
51796
52090
  const params = new URLSearchParams({ limit: limit.toString(), exchange, symbol: symbol2, timeframe });
51797
52091
  const requestUrl = `${getApiUrl()}/candles/recent?${params.toString()}`;
51798
- return shareClientGetRequest(`recent-candles:${params.toString()}`, async () => {
52092
+ return shareClientGetRequest(`recent-candles:${params.toString()}`, async (requestSignal) => {
51799
52093
  const trace = startRuntimeNetworkDebugTrace({
51800
52094
  kind: "runtime",
51801
52095
  label: "market_data_api:candles_recent",
@@ -51807,7 +52101,7 @@ async function getRecentCandles(limit = 10, exchange = "kraken", symbol2 = "PI_X
51807
52101
  try {
51808
52102
  response = await apiFetch(requestUrl, {
51809
52103
  cache: "no-store",
51810
- signal: typeof window === "undefined" ? signal : void 0
52104
+ signal: requestSignal
51811
52105
  });
51812
52106
  if (!response.ok) {
51813
52107
  const error48 = await buildMarketDataFetchError(response, "recent candles", "/candles/recent");
@@ -51835,7 +52129,7 @@ async function getRecentCandles(limit = 10, exchange = "kraken", symbol2 = "PI_X
51835
52129
  }
51836
52130
  async function getLiveTicker(symbol2 = "PI_XBTUSD", exchange = "kraken", signal) {
51837
52131
  const requestKey = `live-ticker:${symbol2}:${exchange}`;
51838
- return shareClientGetRequest(requestKey, async () => {
52132
+ return shareClientGetRequest(requestKey, async (requestSignal) => {
51839
52133
  const requestUrl = `${getApiUrl()}/ticker/live?symbol=${encodeURIComponent(symbol2)}&exchange=${encodeURIComponent(exchange)}`;
51840
52134
  const trace = startRuntimeNetworkDebugTrace({
51841
52135
  kind: "runtime",
@@ -51846,7 +52140,7 @@ async function getLiveTicker(symbol2 = "PI_XBTUSD", exchange = "kraken", signal)
51846
52140
  });
51847
52141
  let response = null;
51848
52142
  try {
51849
- response = await apiFetch(requestUrl, { cache: "no-store", signal });
52143
+ response = await apiFetch(requestUrl, { cache: "no-store", signal: requestSignal });
51850
52144
  if (!response.ok) {
51851
52145
  const error48 = await buildMarketDataFetchError(response, "live ticker", "/ticker/live");
51852
52146
  trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
@@ -60338,7 +60632,7 @@ var init_strings = __esm({
60338
60632
  });
60339
60633
 
60340
60634
  // node_modules/ethers/lib.esm/constants/index.js
60341
- var init_constants = __esm({
60635
+ var init_constants2 = __esm({
60342
60636
  "node_modules/ethers/lib.esm/constants/index.js"() {
60343
60637
  init_define_VTX_EXO_POLICY();
60344
60638
  init_define_VTX_GROK_POLICY();
@@ -60360,7 +60654,7 @@ var init_signature = __esm({
60360
60654
  init_define_VTX_EXO_POLICY();
60361
60655
  init_define_VTX_GROK_POLICY();
60362
60656
  init_define_VTX_PI_MODEL_POLICY();
60363
- init_constants();
60657
+ init_constants2();
60364
60658
  init_utils();
60365
60659
  BN_04 = BigInt(0);
60366
60660
  BN_13 = BigInt(1);
@@ -64589,7 +64883,7 @@ var init_message = __esm({
64589
64883
  init_define_VTX_GROK_POLICY();
64590
64884
  init_define_VTX_PI_MODEL_POLICY();
64591
64885
  init_crypto3();
64592
- init_constants();
64886
+ init_constants2();
64593
64887
  init_transaction2();
64594
64888
  init_utils();
64595
64889
  }
@@ -70197,7 +70491,7 @@ var init_ens_resolver = __esm({
70197
70491
  init_define_VTX_GROK_POLICY();
70198
70492
  init_define_VTX_PI_MODEL_POLICY();
70199
70493
  init_address2();
70200
- init_constants();
70494
+ init_constants2();
70201
70495
  init_contract2();
70202
70496
  init_hash();
70203
70497
  init_utils();
@@ -71844,7 +72138,7 @@ var init_abstract_provider = __esm({
71844
72138
  init_define_VTX_GROK_POLICY();
71845
72139
  init_define_VTX_PI_MODEL_POLICY();
71846
72140
  init_address2();
71847
- init_constants();
72141
+ init_constants2();
71848
72142
  init_contract2();
71849
72143
  init_hash();
71850
72144
  init_transaction2();
@@ -83443,7 +83737,7 @@ var init_ethers = __esm({
83443
83737
  init_version();
83444
83738
  init_abi();
83445
83739
  init_address2();
83446
- init_constants();
83740
+ init_constants2();
83447
83741
  init_contract2();
83448
83742
  init_crypto3();
83449
83743
  init_hash();
@@ -84600,7 +84894,7 @@ var init_hyperliquid_signer = __esm({
84600
84894
  });
84601
84895
 
84602
84896
  // lib/runtime/hyperliquid-client.ts
84603
- 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, fetchBrowserHyperliquidInfoText, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, 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;
84897
+ 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, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, 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;
84604
84898
  var init_hyperliquid_client = __esm({
84605
84899
  "lib/runtime/hyperliquid-client.ts"() {
84606
84900
  "use strict";
@@ -84611,6 +84905,7 @@ var init_hyperliquid_client = __esm({
84611
84905
  init_order_identity();
84612
84906
  init_hyperliquid_order_status();
84613
84907
  init_runtime_policy_generated2();
84908
+ init_constants();
84614
84909
  init_hyperliquid_public_read();
84615
84910
  init_api2();
84616
84911
  init_abort();
@@ -84852,13 +85147,14 @@ var init_hyperliquid_client = __esm({
84852
85147
  url: requestUrl
84853
85148
  });
84854
85149
  try {
84855
- const { payload, bodyText } = await readHyperliquidPublicInfo(apiUrl, body, {
85150
+ const { payload, bodyText, fetchedAtMs } = await readHyperliquidPublicInfo(apiUrl, body, {
84856
85151
  signal: input.signal,
84857
85152
  publicRequestPriority: input.publicRequestPriority,
84858
- includeBodyText
85153
+ includeBodyText,
85154
+ ...input.cacheAccountMode ? { cacheAccountMode: true } : {}
84859
85155
  });
84860
85156
  trace.completeSuccess(200);
84861
- return { payload, bodyText };
85157
+ return { payload, bodyText, fetchedAtMs };
84862
85158
  } catch (error48) {
84863
85159
  const sanitizedError = toSanitizedRuntimeError(error48);
84864
85160
  trace.completeError(sanitizedError, error48?.status ?? null);
@@ -84867,6 +85163,10 @@ var init_hyperliquid_client = __esm({
84867
85163
  };
84868
85164
  postHyperliquidInfo = async (input, body, label2) => (await postHyperliquidInfoRead(input, body, label2)).payload;
84869
85165
  fetchBrowserHyperliquidInfoPayload = (input, body, label2) => postHyperliquidInfo(input, body, label2);
85166
+ fetchBrowserHyperliquidInfoRead = async (input, body, label2) => {
85167
+ const { payload, fetchedAtMs } = await postHyperliquidInfoRead(input, body, label2);
85168
+ return { payload, fetchedAtMs };
85169
+ };
84870
85170
  fetchBrowserHyperliquidInfoText = async (input, body, label2) => {
84871
85171
  const { bodyText } = await postHyperliquidInfoRead(input, body, label2, true);
84872
85172
  if (typeof bodyText !== "string") throw new Error("Hyperliquid returned no response text.");
@@ -86630,6 +86930,13 @@ var init_hyperliquid_client = __esm({
86630
86930
  }
86631
86931
  };
86632
86932
  const settleDefinitiveSuccess = async (exchangeOrderId, orderMemberResults) => {
86933
+ const settlementPolicy = runtime_policy_generated_default2.trading.engine.client_runtime.exchange_mutation;
86934
+ const settlementDeadlineMs = globalThis.performance.now() + settlementPolicy.settlement_retry_window_seconds * MS_PER_SECOND;
86935
+ const handOffToReconciliation = () => {
86936
+ if (begunMutation != null && pinnedAuthority != null) {
86937
+ handOffClientExchangeMutationToReconciliation(begunMutation, pinnedAuthority);
86938
+ }
86939
+ };
86633
86940
  while (true) {
86634
86941
  try {
86635
86942
  const settledMutation = await settleDurableMutation(
@@ -86645,15 +86952,14 @@ var init_hyperliquid_client = __esm({
86645
86952
  }
86646
86953
  return;
86647
86954
  } catch (settlementError) {
86955
+ const settlementCause = settlementError.settlementCause;
86648
86956
  if (input.signal?.aborted) {
86957
+ handOffToReconciliation();
86649
86958
  throw input.signal.reason instanceof Error ? input.signal.reason : settlementError;
86650
86959
  }
86651
- if (isClientExchangeMutationAuthorityConflict(
86652
- settlementError.settlementCause
86653
- )) {
86654
- if (begunMutation != null && pinnedAuthority != null) {
86655
- handOffClientExchangeMutationToReconciliation(begunMutation, pinnedAuthority);
86656
- }
86960
+ const neverSettles = isClientExchangeMutationAuthorityConflict(settlementCause);
86961
+ if (neverSettles || globalThis.performance.now() + settlementPolicy.settlement_retry_milliseconds > settlementDeadlineMs) {
86962
+ handOffToReconciliation();
86657
86963
  throw new RuntimeExecutionError(
86658
86964
  "Exchange submission may have completed; durable reconciliation is pending.",
86659
86965
  "outcome_unknown"
@@ -86668,7 +86974,10 @@ var init_hyperliquid_client = __esm({
86668
86974
  input.signal?.removeEventListener("abort", finish);
86669
86975
  resolve14();
86670
86976
  };
86671
- const timeoutId = globalThis.setTimeout(finish, 1e3);
86977
+ const timeoutId = globalThis.setTimeout(
86978
+ finish,
86979
+ settlementPolicy.settlement_retry_milliseconds
86980
+ );
86672
86981
  input.signal?.addEventListener("abort", finish, { once: true });
86673
86982
  });
86674
86983
  }
@@ -86928,14 +87237,14 @@ var init_exchange_mutation_evidence = __esm({
86928
87237
  const wallet = String(input.required.wallet_address ?? "").trim();
86929
87238
  if (!wallet) throw new Error("Missing wallet address for reconciliation evidence.");
86930
87239
  const apiUrl = await resolveHyperliquidApiUrl(input.profileId, input.required.hyperliquid_api_url, input.signal);
86931
- const readInput2 = { apiUrl, signal: input.signal, publicRequestPriority: "trading_reconcile" };
87240
+ const readInput = { apiUrl, signal: input.signal, publicRequestPriority: "trading_reconcile" };
86932
87241
  const startedAtMonotonicMs = monotonicNowMs();
86933
87242
  const observedAt = (/* @__PURE__ */ new Date()).toISOString();
86934
87243
  const orderStatuses = await Promise.all((input.required.order_refs ?? []).map(async (ref) => {
86935
87244
  const orderRef = String(ref).trim();
86936
87245
  const oid = /^\d+$/.test(orderRef) ? Number(orderRef) : orderRef;
86937
87246
  const response = await fetchBrowserHyperliquidInfoPayload(
86938
- readInput2,
87247
+ readInput,
86939
87248
  { type: "orderStatus", user: wallet, oid },
86940
87249
  "hyperliquid.orderStatus"
86941
87250
  );
@@ -86943,7 +87252,7 @@ var init_exchange_mutation_evidence = __esm({
86943
87252
  }));
86944
87253
  const coin = String(input.required.active_asset_coin ?? "").trim();
86945
87254
  const activeAssetData = coin ? await fetchBrowserHyperliquidInfoPayload(
86946
- readInput2,
87255
+ readInput,
86947
87256
  { type: "activeAssetData", user: wallet, coin },
86948
87257
  "hyperliquid.activeAssetData"
86949
87258
  ) : null;
@@ -86961,6 +87270,27 @@ var init_exchange_mutation_evidence = __esm({
86961
87270
  });
86962
87271
 
86963
87272
  // lib/api.ts
87273
+ async function reportServerBackupReadiness(profileId, ready, hostId, signal, power) {
87274
+ const response = await apiFetch(`${getApiUrl()}/trading/ai/client/server-backup/readiness`, {
87275
+ method: "POST",
87276
+ headers: getProfileHeaders({ "Content-Type": "application/json" }, profileId),
87277
+ credentials: "include",
87278
+ // A host too low on battery to take a runtime over is not ready to take a backup back.
87279
+ body: JSON.stringify({
87280
+ ready,
87281
+ host_id: hostId,
87282
+ ...power ? {
87283
+ power_source: power.source,
87284
+ ...typeof power.batteryPercent === "number" ? { battery_percent: power.batteryPercent } : {}
87285
+ } : {}
87286
+ }),
87287
+ signal
87288
+ });
87289
+ if (!response.ok) {
87290
+ throw new Error(await getErrorMessageFromResponse(response, "Failed to report client readiness"));
87291
+ }
87292
+ return response.json();
87293
+ }
86964
87294
  function relayNativeProviderRequest(provider, apiKey, payload, options = {}) {
86965
87295
  return apiFetch(`${getApiUrl()}/llm/native-provider-relay`, {
86966
87296
  method: "POST",
@@ -87031,12 +87361,27 @@ async function getClientRuntimeSecrets(profileId, options) {
87031
87361
  client_runtime_secret_version: fetchedPayload.client_runtime_secret_version
87032
87362
  };
87033
87363
  }
87364
+ async function getLocalAiEndpointSecret(baseUrl, profileId, signal) {
87365
+ const params = new URLSearchParams({ base_url: baseUrl });
87366
+ const response = await apiFetch(`${getApiUrl()}/auth/me/local-ai-endpoint-secret?${params.toString()}`, {
87367
+ method: "GET",
87368
+ cache: "no-store",
87369
+ headers: clientRuntimeSecretHeaders(profileId),
87370
+ credentials: "include",
87371
+ signal
87372
+ });
87373
+ if (!response.ok) {
87374
+ const message = await getErrorMessageFromResponse(response, "Failed to fetch Local AI endpoint secret", { fallbackDetail: true });
87375
+ throw new Error(message);
87376
+ }
87377
+ return response.json();
87378
+ }
87034
87379
  async function getPreferences(cookie, profileId, signal, includeTradeLayouts = false, runtimeAuthority) {
87035
87380
  const effectiveProfileId = profileId ?? getActiveProfileId() ?? null;
87036
87381
  const schedulerInstanceId = String(runtimeAuthority?.schedulerInstanceId ?? "").trim() || void 0;
87037
87382
  const baseRequestKey = clientPreferencesRequestKey(effectiveProfileId, includeTradeLayouts);
87038
87383
  const requestKey = schedulerInstanceId ? `${baseRequestKey}:scheduler=${schedulerInstanceId}` : baseRequestKey;
87039
- return shareClientGetRequest(requestKey, async () => {
87384
+ return shareClientGetRequest(requestKey, async (requestSignal) => {
87040
87385
  const headers = getProfileHeaders({}, profileId);
87041
87386
  if (cookie) {
87042
87387
  headers["Cookie"] = cookie;
@@ -87059,7 +87404,7 @@ async function getPreferences(cookie, profileId, signal, includeTradeLayouts = f
87059
87404
  credentials: "include",
87060
87405
  cache: "no-store",
87061
87406
  headers,
87062
- signal: typeof window === "undefined" ? signal : void 0
87407
+ signal: requestSignal
87063
87408
  });
87064
87409
  if (!response.ok) {
87065
87410
  throwUnauthorizedIfNeeded(response);
@@ -87099,7 +87444,8 @@ async function pollCopyTradingRuntimeSource(profileId, options) {
87099
87444
  body: JSON.stringify({
87100
87445
  dry_run: Boolean(options?.dryRun),
87101
87446
  force_refresh: Boolean(options?.forceRefresh),
87102
- ...options?.maxEvents ? { max_events: options.maxEvents } : {}
87447
+ ...options?.maxEvents ? { max_events: options.maxEvents } : {},
87448
+ ...options?.accountEvidence ? { account_evidence: options.accountEvidence } : {}
87103
87449
  }),
87104
87450
  credentials: "include",
87105
87451
  cache: "no-store",
@@ -87218,7 +87564,7 @@ async function acknowledgeClientCopyTradingOrderAction(profileId, actionId, payl
87218
87564
  }
87219
87565
  async function getLLMConfig(cookie, profileId, signal) {
87220
87566
  const effectiveProfileId = profileId ?? getActiveProfileId() ?? null;
87221
- return shareClientGetRequest(clientGetRequestKey("llm-config", effectiveProfileId), async () => {
87567
+ return shareClientGetRequest(clientGetRequestKey("llm-config", effectiveProfileId), async (requestSignal) => {
87222
87568
  const headers = getProfileHeaders({
87223
87569
  "Content-Type": "application/json"
87224
87570
  }, profileId);
@@ -87229,7 +87575,7 @@ async function getLLMConfig(cookie, profileId, signal) {
87229
87575
  method: "GET",
87230
87576
  headers,
87231
87577
  credentials: "include",
87232
- signal
87578
+ signal: requestSignal
87233
87579
  });
87234
87580
  if (!response.ok) {
87235
87581
  const message = await getErrorMessageFromResponse(
@@ -87522,6 +87868,10 @@ async function claimClientRuntime(profileId, payload, options) {
87522
87868
  kind: payload.kind,
87523
87869
  takeover: payload.kind === "explicit" && payload.takeover === true,
87524
87870
  ...payload.claimSurface ? { claim_surface: payload.claimSurface } : {},
87871
+ ...payload.power ? {
87872
+ power_source: payload.power.source,
87873
+ ...typeof payload.power.batteryPercent === "number" ? { battery_percent: payload.power.batteryPercent } : {}
87874
+ } : {},
87525
87875
  // This build signs server-issued TP/SL actions; a profile whose
87526
87876
  // protection the server owns admits only claims that say so.
87527
87877
  client_protection_capability_version: CLIENT_PROTECTION_CAPABILITY_VERSION
@@ -88440,6 +88790,41 @@ async function fetchClientRuntimeKillswitchContext(profileId, payload, options)
88440
88790
  options
88441
88791
  );
88442
88792
  }
88793
+ async function getClientRuntimeStatuses(profileIds, signal, options) {
88794
+ const normalizedProfileIds = [...new Set(profileIds)].sort((left, right) => left - right);
88795
+ const params = new URLSearchParams();
88796
+ for (const profileId of normalizedProfileIds) {
88797
+ params.append("profile_id", String(profileId));
88798
+ }
88799
+ const viewer = resolveClientRuntimeStatusViewerHeaders(options?.runtimeViewer);
88800
+ const requestKey = `client-runtime-statuses:${normalizedProfileIds.join(",")}${viewer.requestKey}`;
88801
+ return shareClientGetRequest(requestKey, async (requestSignal) => {
88802
+ const headers = { ...viewer.headers };
88803
+ const response = await apiFetch(
88804
+ `${getApiUrl()}/trading/ai/runtime/statuses?${params.toString()}`,
88805
+ {
88806
+ method: "GET",
88807
+ credentials: "include",
88808
+ cache: "no-store",
88809
+ headers,
88810
+ // Without the browser's shared request a caller's abort ends the request too.
88811
+ signal: requestSignal
88812
+ }
88813
+ );
88814
+ if (!response.ok) {
88815
+ const error48 = await createRuntimeRequestError(response, "Failed to fetch client runtime statuses");
88816
+ throw error48;
88817
+ }
88818
+ return response.json();
88819
+ }, {
88820
+ signal,
88821
+ shareAbortScoped: true,
88822
+ // A host-named read decides whether that host claims: it must see an
88823
+ // intent change made a moment ago, so it shares only an in-flight read
88824
+ // and never reuses a finished one.
88825
+ ttlMs: viewer.requestKey ? 0 : CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS
88826
+ });
88827
+ }
88443
88828
  var clientRuntimeSecretHeaders, preferencesWriteQueue, getCopyTradingRuntimeLeaseToken, getCopyTradingSchedulerInstanceId, resolveClientRuntimeStatusViewerHeaders, CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION, CLIENT_PROTECTION_CAPABILITY_VERSION, completedDeferredClientRuntimeStops, rememberCompletedDeferredClientRuntimeStop, consumeCompletedDeferredClientRuntimeStop, toNumericProfileId, buildClientRuntimeBody, shouldAttachRuntimeIdempotencyKey, attachRuntimeLeaseHeader, attachRuntimeSchedulerInstanceHeader, resolveRuntimeLeaseToken, resolveSchedulerBoundRuntimeLeaseToken, persistRuntimeLeaseFromPayload, persistRuntimeLeaseStatusMetadata, shouldClearPersistedRuntimeLeaseOnError, createRuntimeRequestError, parseClientRuntimeRequestContext, recordRuntimeAuthFailureBreadcrumb, classifyRuntimeRequestError, annotateRuntimeRequestError, parseRuntimeRetryAfterMs, isRetryableClientRuntimeStatus, shouldRetryClientRuntimeHttpStatus, isRuntimeIdempotencyInProgressError, isRetryableRuntimeConflictError, resolveClientRuntimeRetryDelayMs, reconcilePendingClientExchangeMutation, CLIENT_RUNTIME_CLAIM_EXCHANGE_MUTATION_WAIT_CODES, CLIENT_EXCHANGE_AUTHORITY_DEVICE_KEY, CLIENT_EXCHANGE_AUTHORITY_SESSION_KEY, getOrCreateClientExchangeAuthorityIdentity, resolveClientExchangeMutationAuthority, pinClientExchangeMutationAuthority, CLIENT_EXCHANGE_MUTATION_AUTHORITY_MISMATCH, isClientExchangeMutationAuthorityConflict, handOffClientExchangeMutationToReconciliation, clientExchangeMutationAuthorityBody, isPendingClientExchangeMutationError, isMissingActiveClientExchangeMutationError, clientExchangeMutationReconciliationTimers, MAX_CLIENT_EXCHANGE_RECONCILIATION_DELAY_MS, CLIENT_EXCHANGE_RECONCILIATION_CLOCK_SKEW_MS, ClientExchangeMutationRebuildRequiredError, isTerminalClientExchangeMutation, clientExchangeMutationReconciliationKey, clearScheduledClientExchangeMutationReconciliation, snapshotClientExchangeMutationReconciliationAuthority, completeClientExchangeMutationReconciliation, protectiveBoundClientExchangeMutations, rememberProtectiveBoundClientExchangeMutation, isProtectiveBoundClientExchangeMutation, postClientExchangeMutationReconciliation, scheduleClientExchangeMutationReconciliation;
88444
88829
  var init_api2 = __esm({
88445
88830
  "lib/api.ts"() {
@@ -88495,10 +88880,17 @@ var init_api2 = __esm({
88495
88880
  if (!deviceId) return { headers: {}, requestKey: "" };
88496
88881
  const sessionId = String(viewer?.sessionId ?? "").trim();
88497
88882
  const surface = String(viewer?.surface ?? "").trim();
88883
+ const power = viewer?.power?.source ?? "";
88884
+ const batteryPercent = viewer?.power?.batteryPercent;
88498
88885
  const headers = { "x-client-runtime-device-id": deviceId };
88499
88886
  if (sessionId) headers["x-client-runtime-session-id"] = sessionId;
88500
88887
  if (surface) headers["x-client-runtime-surface"] = surface;
88501
- return { headers, requestKey: `:viewer:${deviceId}:${sessionId}:${surface}` };
88888
+ if (power) headers["x-client-runtime-power"] = power;
88889
+ if (typeof batteryPercent === "number") headers["x-client-runtime-battery-percent"] = String(batteryPercent);
88890
+ return {
88891
+ headers,
88892
+ requestKey: `:viewer:${deviceId}:${sessionId}:${surface}:${power}:${batteryPercent ?? ""}`
88893
+ };
88502
88894
  };
88503
88895
  CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION = String(
88504
88896
  process.env.NEXT_PUBLIC_CLIENT_RUNTIME_PROMPT_CONTRACT_VERSION || "2026-08-24.1"
@@ -88935,15 +89327,11 @@ var init_api2 = __esm({
88935
89327
  CLIENT_EXCHANGE_MUTATION_AUTHORITY_MISMATCH = "exchange_mutation_authority_mismatch";
88936
89328
  isClientExchangeMutationAuthorityConflict = (error48) => {
88937
89329
  const candidate = error48;
89330
+ if (clientRuntimeAuthorityEndedFromCode(error48)) return true;
88938
89331
  if (Number(candidate?.status) !== 409) return false;
88939
- if (candidate?.code === CLIENT_EXCHANGE_MUTATION_AUTHORITY_MISMATCH) return true;
88940
- return /does not own this exchange mutation/i.test(String(candidate?.message ?? ""));
89332
+ return candidate?.code === CLIENT_EXCHANGE_MUTATION_AUTHORITY_MISMATCH || /does not own this exchange mutation/i.test(String(candidate?.message ?? ""));
88941
89333
  };
88942
- handOffClientExchangeMutationToReconciliation = (mutation, authority) => scheduleClientExchangeMutationReconciliation(
88943
- authority.numericProfileId,
88944
- mutation,
88945
- authority.requestOptions
88946
- );
89334
+ handOffClientExchangeMutationToReconciliation = (mutation, authority) => scheduleClientExchangeMutationReconciliation(authority.numericProfileId, mutation, authority.requestOptions);
88947
89335
  clientExchangeMutationAuthorityBody = (authority) => {
88948
89336
  const schedulerInstanceId = String(authority.requestOptions.schedulerInstanceId ?? "").trim();
88949
89337
  return {
@@ -89083,11 +89471,8 @@ var init_api2 = __esm({
89083
89471
  const timer = globalThis.setTimeout(() => {
89084
89472
  const scheduled = clientExchangeMutationReconciliationTimers.get(key);
89085
89473
  clientExchangeMutationReconciliationTimers.delete(key);
89086
- void postClientExchangeMutationReconciliation(
89087
- profileId,
89088
- mutation.mutation_id,
89089
- scheduled?.requestOptions ?? authority
89090
- ).catch(() => {
89474
+ const requestOptions2 = scheduled?.requestOptions ?? authority;
89475
+ void postClientExchangeMutationReconciliation(profileId, mutation.mutation_id, requestOptions2).catch((error48) => requestOptions2.runtimeLeaseToken && clientRuntimeAuthorityEndedFromCode(error48) ? postClientExchangeMutationReconciliation(profileId, mutation.mutation_id, { omitRuntimeLeaseToken: true }) : void 0).catch(() => {
89091
89476
  });
89092
89477
  }, Math.max(0, delayMs));
89093
89478
  clientExchangeMutationReconciliationTimers.set(key, {
@@ -89481,7 +89866,7 @@ var init_sort_utils = __esm({
89481
89866
  });
89482
89867
 
89483
89868
  // lib/local-ai.ts
89484
- var LOCAL_SOURCE_ALIASES, LOCAL_CONTEXT_CACHE_TTL_MS, LOCAL_AI_SERVER_TYPE_ALIASES, LOCAL_AI_ROOT_SUFFIXES, normalizeLocalAiServerType, assertSupportedLocalAiServerType, resolveLocalAiServerTypeInput, stripLocalAiKnownSuffix, getLocalAiRootUrl, normalizeLocalModelSource, isLocalModelSource, isClientOnlyModelSource, normalizeLocalAiBaseUrl, endpointOrigin, sameEndpointOriginKey, normalizeOpenAiCompatibleBaseUrl;
89869
+ var LOCAL_SOURCE_ALIASES, LOCAL_CONTEXT_CACHE_TTL_MS, LOCAL_AI_SERVER_TYPE_ALIASES, LOCAL_AI_ROOT_SUFFIXES, normalizeLocalAiServerType, assertSupportedLocalAiServerType, resolveLocalAiServerTypeInput, stripLocalAiKnownSuffix, getLocalAiRootUrl, normalizeLocalModelSource, isLocalModelSource, isClientOnlyModelSource, normalizeLocalAiBaseUrl, endpointOrigin, sameEndpointOriginKey, normalizeOpenAiCompatibleBaseUrl, buildLocalAiModelsEndpointForServerType;
89485
89870
  var init_local_ai = __esm({
89486
89871
  "lib/local-ai.ts"() {
89487
89872
  "use strict";
@@ -89608,6 +89993,14 @@ var init_local_ai = __esm({
89608
89993
  return null;
89609
89994
  }
89610
89995
  };
89996
+ buildLocalAiModelsEndpointForServerType = (baseUrl, serverType) => {
89997
+ assertSupportedLocalAiServerType(serverType);
89998
+ const normalizedBaseUrl = normalizeLocalAiBaseUrl(baseUrl);
89999
+ if (!normalizedBaseUrl) {
90000
+ return null;
90001
+ }
90002
+ return normalizedBaseUrl.toLowerCase().endsWith("/models") ? normalizedBaseUrl : `${normalizedBaseUrl}/models`;
90003
+ };
89611
90004
  }
89612
90005
  });
89613
90006
 
@@ -92161,7 +92554,7 @@ var init_hyperliquid_account_state_adapter = __esm({
92161
92554
  });
92162
92555
 
92163
92556
  // lib/runtime/protective-evidence.ts
92164
- var protectivePolicy, MAX_PROTECTIVE_EVIDENCE_ITEMS_PER_REPORT, EVIDENCE_FAILURE_BACKOFF_MS, STALE_EVIDENCE_CODE, SHARED_ACCOUNT_READ_MS, sharedAccountReads, EVIDENCE_READ_PRIORITY, MIN_EVIDENCE_SWEEP_DELAY_MS, evidenceBackoffUntil, errorCode, parseDueAtMs, boundedEvidenceSweepAtMs, authorityArgs, dexBody, readInput, evidenceItems, readOrNull, reportBody, readEvidenceBatch, withEvidenceReporterLock, reportDueClientProtectiveEvidence, readClientProtectiveOpenOrdersEvidence, openOrdersEvidenceForUpload;
92557
+ var protectivePolicy, MAX_PROTECTIVE_EVIDENCE_ITEMS_PER_REPORT, EVIDENCE_FAILURE_BACKOFF_MS, STALE_EVIDENCE_CODE, SHARED_ACCOUNT_READ_MS, sharedAccountReads, EVIDENCE_READ_PRIORITY, MIN_EVIDENCE_SWEEP_DELAY_MS, evidenceBackoffUntil, errorCode, parseDueAtMs, boundedEvidenceSweepAtMs, authorityArgs, dexBody, isEvidenceOrderRef, orderStatusOid, evidenceReadInput, evidenceItems, readOrNull, reportBody, readEvidenceBatch, withEvidenceReporterLock, reportDueClientProtectiveEvidence, readClientProtectiveOpenOrdersEvidence, openOrdersEvidenceForUpload;
92165
92558
  var init_protective_evidence = __esm({
92166
92559
  "lib/runtime/protective-evidence.ts"() {
92167
92560
  "use strict";
@@ -92201,7 +92594,9 @@ var init_protective_evidence = __esm({
92201
92594
  return scheduler ? [session, lease, device, scheduler] : [session, lease, device];
92202
92595
  };
92203
92596
  dexBody = (dex) => dex ? { dex } : {};
92204
- readInput = (context) => {
92597
+ isEvidenceOrderRef = (orderRef) => /^\d+$/.test(orderRef) && Number.isSafeInteger(Number(orderRef)) || /^0x[0-9a-fA-F]{32}$/.test(orderRef);
92598
+ orderStatusOid = (orderRef) => /^\d+$/.test(orderRef) ? Number(orderRef) : orderRef;
92599
+ evidenceReadInput = (context) => {
92205
92600
  const apiUrl = String(context.hyperliquidApiUrl ?? "").trim();
92206
92601
  return {
92207
92602
  config: context.config,
@@ -92216,7 +92611,7 @@ var init_protective_evidence = __esm({
92216
92611
  const dex = String(request.dex ?? "").trim();
92217
92612
  if (request.kind === "order_status") {
92218
92613
  const orderRef = String(request.order_ref ?? "").trim();
92219
- if (!/^\d+$/.test(orderRef) && !/^0x[0-9a-fA-F]{32}$/.test(orderRef)) continue;
92614
+ if (!isEvidenceOrderRef(orderRef)) continue;
92220
92615
  const key = `order_status:${orderRef}`;
92221
92616
  const existing = items.get(key);
92222
92617
  items.set(key, {
@@ -92257,7 +92652,7 @@ var init_protective_evidence = __esm({
92257
92652
  observed_age_ms: monotonicAgeMs(batch.startedAtMonotonicMs)
92258
92653
  });
92259
92654
  readEvidenceBatch = async (context, wallet, batch) => {
92260
- const input = readInput(context);
92655
+ const input = evidenceReadInput(context);
92261
92656
  let startedAtMonotonicMs = monotonicNowMs();
92262
92657
  const observedAt = (/* @__PURE__ */ new Date()).toISOString();
92263
92658
  const perDex = /* @__PURE__ */ new Map();
@@ -92289,7 +92684,7 @@ var init_protective_evidence = __esm({
92289
92684
  const markets = [];
92290
92685
  await Promise.all(batch.map(async (item) => {
92291
92686
  if (item.kind === "order_status") {
92292
- const oid = /^\d+$/.test(item.orderRef) ? Number(item.orderRef) : item.orderRef;
92687
+ const oid = orderStatusOid(item.orderRef);
92293
92688
  const response = await readOrNull(() => fetchBrowserHyperliquidInfoPayload(
92294
92689
  input,
92295
92690
  { type: "orderStatus", user: wallet, oid },
@@ -92408,7 +92803,7 @@ var init_protective_evidence = __esm({
92408
92803
  readClientProtectiveOpenOrdersEvidence = async (context, dexes) => {
92409
92804
  const wallet = String(context.walletAddress ?? "").trim();
92410
92805
  if (!wallet) throw new Error("Missing Hyperliquid wallet address for open-orders evidence.");
92411
- const input = readInput(context);
92806
+ const input = evidenceReadInput(context);
92412
92807
  return Promise.all([...new Set(dexes.map((dex) => String(dex ?? "").trim()))].map(async (dex) => {
92413
92808
  const startedAtMonotonicMs = monotonicNowMs();
92414
92809
  const observedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -93126,6 +93521,189 @@ var init_execution_guard_contract = __esm({
93126
93521
  }
93127
93522
  });
93128
93523
 
93524
+ // lib/runtime/copy-trading-evidence.ts
93525
+ var ACCOUNT_MODE_CACHE_MS, dexList, normalizeRequest, openOrderRefs, EvidenceReadFailed, readClientCopyTradingAccountEvidence, accountEvidenceForUpload, readCopyOrderStatusEvidence, orderStatusEvidenceForAck;
93526
+ var init_copy_trading_evidence = __esm({
93527
+ "lib/runtime/copy-trading-evidence.ts"() {
93528
+ "use strict";
93529
+ init_define_VTX_EXO_POLICY();
93530
+ init_define_VTX_GROK_POLICY();
93531
+ init_define_VTX_PI_MODEL_POLICY();
93532
+ init_runtime_policy_generated2();
93533
+ init_hyperliquid_account_mode_contract();
93534
+ init_hyperliquid_client();
93535
+ init_monotonic_clock();
93536
+ init_protective_evidence();
93537
+ ACCOUNT_MODE_CACHE_MS = runtime_policy_generated_default2.exchange.hyperliquid.client_public_read_budget.account_mode_ttl_seconds * 1e3;
93538
+ dexList = (value) => {
93539
+ if (!Array.isArray(value) || value.some((dex) => typeof dex !== "string")) return null;
93540
+ return [...new Set(value.map((dex) => dex.trim()))];
93541
+ };
93542
+ normalizeRequest = (request) => {
93543
+ if (!request || typeof request !== "object") return null;
93544
+ const requestId = typeof request.request_id === "string" ? request.request_id.trim() : "";
93545
+ const walletAddress = typeof request.wallet_address === "string" ? request.wallet_address.trim() : "";
93546
+ const dexes = dexList(request.dexes);
93547
+ const openOrdersDexes = dexList(request.open_orders_dexes);
93548
+ const maxAgeSeconds = Number(request.max_age_seconds);
93549
+ if (!requestId || !walletAddress || !dexes || !openOrdersDexes || !Array.isArray(request.order_refs) || !Number.isFinite(maxAgeSeconds) || maxAgeSeconds <= 0) return null;
93550
+ const orderRefs = /* @__PURE__ */ new Map();
93551
+ for (const entry of request.order_refs) {
93552
+ const orderRef = typeof entry?.order_ref === "string" ? entry.order_ref.trim() : "";
93553
+ const dex = typeof entry?.dex === "string" ? entry.dex.trim() : null;
93554
+ if (dex == null || !isEvidenceOrderRef(orderRef)) return null;
93555
+ orderRefs.set(`${dex}|${orderRef.toLowerCase()}`, { orderRef, dex });
93556
+ }
93557
+ return {
93558
+ requestId,
93559
+ walletAddress,
93560
+ dexes,
93561
+ accountMode: request.account_mode === true,
93562
+ openOrdersDexes,
93563
+ orderRefs: [...orderRefs.values()],
93564
+ maxAgeMs: maxAgeSeconds * 1e3
93565
+ };
93566
+ };
93567
+ openOrderRefs = (response) => {
93568
+ if (!Array.isArray(response)) return null;
93569
+ const refs = /* @__PURE__ */ new Set();
93570
+ for (const order of response) {
93571
+ if (!order || typeof order !== "object") continue;
93572
+ const { oid, cloid } = order;
93573
+ if (oid != null && oid !== "") refs.add(String(oid).trim().toLowerCase());
93574
+ if (typeof cloid === "string" && cloid.trim()) refs.add(cloid.trim().toLowerCase());
93575
+ }
93576
+ return refs;
93577
+ };
93578
+ EvidenceReadFailed = class extends Error {
93579
+ };
93580
+ readClientCopyTradingAccountEvidence = async (context) => {
93581
+ const request = normalizeRequest(context.request);
93582
+ if (!request) return { ok: false, reason: "invalid_request" };
93583
+ const trustedWallet = String(context.trustedWalletAddress ?? "").trim();
93584
+ if (!trustedWallet || trustedWallet.toLowerCase() !== request.walletAddress.toLowerCase()) {
93585
+ return { ok: false, reason: "wallet_mismatch" };
93586
+ }
93587
+ if (context.signal?.aborted) return { ok: false, reason: "aborted" };
93588
+ const controller = new AbortController();
93589
+ const parentSignal = context.signal;
93590
+ const cancelReads = () => controller.abort(parentSignal?.reason);
93591
+ parentSignal?.addEventListener("abort", cancelReads, { once: true });
93592
+ const input = evidenceReadInput({ ...context, signal: controller.signal });
93593
+ const user = trustedWallet;
93594
+ let startedAtMonotonicMs = monotonicNowMs();
93595
+ const read = async (body, label2) => {
93596
+ try {
93597
+ const response = await fetchBrowserHyperliquidInfoPayload(input, body, label2);
93598
+ if (response == null) throw new EvidenceReadFailed(label2);
93599
+ return response;
93600
+ } catch (error48) {
93601
+ controller.abort();
93602
+ throw error48;
93603
+ }
93604
+ };
93605
+ const cacheAccountMode = ACCOUNT_MODE_CACHE_MS * 2 <= request.maxAgeMs;
93606
+ const readAccountMode = async (body, label2) => {
93607
+ const calledAtWallMs = Date.now();
93608
+ const calledAtMonotonicMs = monotonicNowMs();
93609
+ try {
93610
+ const { payload, fetchedAtMs } = await fetchBrowserHyperliquidInfoRead({ ...input, cacheAccountMode }, body, label2);
93611
+ if (Number.isFinite(fetchedAtMs) && fetchedAtMs < calledAtWallMs) {
93612
+ startedAtMonotonicMs = Math.min(startedAtMonotonicMs, calledAtMonotonicMs - (calledAtWallMs - fetchedAtMs));
93613
+ }
93614
+ return payload;
93615
+ } catch (error48) {
93616
+ controller.abort();
93617
+ throw error48;
93618
+ }
93619
+ };
93620
+ try {
93621
+ const clearinghouseStates = Promise.all(request.dexes.map(async (dex) => ({
93622
+ dex,
93623
+ response: await read({ type: "clearinghouseState", user, ...dexBody(dex) }, "hyperliquid.clearinghouseState")
93624
+ })));
93625
+ const accountMode = request.accountMode ? (async () => {
93626
+ const userAbstraction = await readAccountMode({ type: "userAbstraction", user }, "hyperliquid.userAbstraction");
93627
+ const mode2 = extractCanonicalHyperliquidAccountMode(userAbstraction);
93628
+ if (!mode2) throw new EvidenceReadFailed("hyperliquid.userAbstraction");
93629
+ const userDexAbstraction = mode2 === "default" || mode2 === "disabled" ? await readAccountMode({ type: "userDexAbstraction", user }, "hyperliquid.userDexAbstraction") : null;
93630
+ return { userAbstraction, userDexAbstraction };
93631
+ })() : Promise.resolve({ userAbstraction: null, userDexAbstraction: null });
93632
+ const openOrders = Promise.all(request.openOrdersDexes.map(async (dex) => {
93633
+ const response = await read({ type: "frontendOpenOrders", user, ...dexBody(dex) }, "hyperliquid.frontendOpenOrders");
93634
+ const refs = openOrderRefs(response);
93635
+ if (!refs) throw new EvidenceReadFailed("hyperliquid.frontendOpenOrders");
93636
+ return { dex, response, refs };
93637
+ }));
93638
+ const orderStatuses = openOrders.then((orders2) => {
93639
+ const openByDex = new Map(orders2.map((order) => [order.dex, order.refs]));
93640
+ return Promise.all(request.orderRefs.filter(({ orderRef, dex }) => !openByDex.get(dex)?.has(orderRef.toLowerCase())).map(async ({ orderRef, dex }) => ({
93641
+ order_ref: orderRef,
93642
+ dex,
93643
+ response: await read(
93644
+ { type: "orderStatus", user, oid: orderStatusOid(orderRef) },
93645
+ "hyperliquid.orderStatus"
93646
+ )
93647
+ })));
93648
+ });
93649
+ const [states, mode, orders, statuses] = await Promise.all([
93650
+ clearinghouseStates,
93651
+ accountMode,
93652
+ openOrders,
93653
+ orderStatuses
93654
+ ]);
93655
+ if (parentSignal?.aborted) return { ok: false, reason: "aborted" };
93656
+ if (monotonicAgeMs(startedAtMonotonicMs) > request.maxAgeMs) return { ok: false, reason: "stale" };
93657
+ return {
93658
+ ok: true,
93659
+ read: {
93660
+ evidence: {
93661
+ request_id: request.requestId,
93662
+ wallet_address: request.walletAddress,
93663
+ source: "live",
93664
+ clearinghouse_states: states,
93665
+ user_abstraction: mode.userAbstraction,
93666
+ user_dex_abstraction: mode.userDexAbstraction,
93667
+ open_orders: orders.map(({ dex, response }) => ({ dex, response })),
93668
+ order_statuses: statuses
93669
+ },
93670
+ startedAtMonotonicMs
93671
+ }
93672
+ };
93673
+ } catch {
93674
+ return { ok: false, reason: parentSignal?.aborted ? "aborted" : "read_failed" };
93675
+ } finally {
93676
+ parentSignal?.removeEventListener("abort", cancelReads);
93677
+ }
93678
+ };
93679
+ accountEvidenceForUpload = (read) => ({
93680
+ ...read.evidence,
93681
+ observed_age_ms: monotonicAgeMs(read.startedAtMonotonicMs)
93682
+ });
93683
+ readCopyOrderStatusEvidence = async (context, orderId) => {
93684
+ const user = String(context.walletAddress ?? "").trim();
93685
+ const orderRef = String(orderId).trim();
93686
+ if (!user || !isEvidenceOrderRef(orderRef) || context.signal?.aborted) return null;
93687
+ const startedAtMonotonicMs = monotonicNowMs();
93688
+ try {
93689
+ const response = await fetchBrowserHyperliquidInfoPayload(
93690
+ evidenceReadInput(context),
93691
+ { type: "orderStatus", user, oid: orderStatusOid(orderRef) },
93692
+ "hyperliquid.orderStatus"
93693
+ );
93694
+ return response == null ? null : { order_ref: orderRef, response, startedAtMonotonicMs };
93695
+ } catch {
93696
+ return null;
93697
+ }
93698
+ };
93699
+ orderStatusEvidenceForAck = (read) => ({
93700
+ order_ref: read.order_ref,
93701
+ response: read.response,
93702
+ observed_age_ms: monotonicAgeMs(read.startedAtMonotonicMs)
93703
+ });
93704
+ }
93705
+ });
93706
+
93129
93707
  // lib/runtime/protective-trigger-price.ts
93130
93708
  var toPositiveNumber, resolveRiskPct, buildTriggerPrice, resolveTrailingStopTightening;
93131
93709
  var init_protective_trigger_price = __esm({
@@ -93330,13 +93908,18 @@ function adjustCopiedTarget(target, longRemovedSince, shortRemovedSince) {
93330
93908
  if (target < -1e-12) return Math.min(0, target + Math.max(0, shortRemovedSince));
93331
93909
  return 0;
93332
93910
  }
93911
+ function copiedTargetBesideOwnPosition(target, copied, actual) {
93912
+ const own = actual - copied;
93913
+ if (Math.abs(own) <= 1e-12 || Math.abs(target) <= 1e-12 || own * target > 0) return target;
93914
+ return Math.min(Math.max(target, Math.min(0, copied)), Math.max(0, copied));
93915
+ }
93333
93916
  function removedByCap(copied, capped) {
93334
93917
  if (copied > 0) return [Math.max(0, copied - Math.max(0, capped)), 0];
93335
93918
  if (copied < 0) return [0, Math.max(0, Math.min(0, capped) - copied)];
93336
93919
  return [0, 0];
93337
93920
  }
93338
- function positionSpaceCopyTarget(reconciliation, recordedTarget, actualPosition) {
93339
- if (!reconciliation || reconciliation.target_space !== "copied") return recordedTarget;
93921
+ function copiedTargetNow(reconciliation, recordedTarget, actualPosition) {
93922
+ if (!reconciliation || reconciliation.target_space !== "copied") return null;
93340
93923
  const copiedServer = Number(reconciliation.copied_now ?? 0) || 0;
93341
93924
  const copiedNow = capCopiedToActual(copiedServer, actualPosition);
93342
93925
  const [deviceLongRemoved, deviceShortRemoved] = removedByCap(copiedServer, copiedNow);
@@ -93347,9 +93930,9 @@ function positionSpaceCopyTarget(reconciliation, recordedTarget, actualPosition)
93347
93930
  longRemovedNow - (Number(reconciliation.external_long_removed_before ?? 0) || 0),
93348
93931
  shortRemovedNow - (Number(reconciliation.external_short_removed_before ?? 0) || 0)
93349
93932
  );
93350
- return actualPosition + (targetNow - copiedNow);
93933
+ return { copiedNow, targetNow, kept: copiedTargetBesideOwnPosition(targetNow, copiedNow, actualPosition) };
93351
93934
  }
93352
- var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, _extractOrderResponseStates, createRuntimeId, _extractFilledSize, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, 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, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, recoverJournaledClientProtectiveAttachments, readPendingEntryMutation, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, executeClientRuntimeDecisionUnlocked, executeClientCopyTradingIntent, executeClientCopyTradingOrderAction;
93935
+ var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, _extractOrderResponseStates, createRuntimeId, _extractFilledSize, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, 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, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, recoverJournaledClientProtectiveAttachments, readPendingEntryMutation, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, executeClientRuntimeDecisionUnlocked, executeClientCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction;
93353
93936
  var init_runtime_execution = __esm({
93354
93937
  "lib/runtime/runtime-execution.ts"() {
93355
93938
  "use strict";
@@ -93370,6 +93953,7 @@ var init_runtime_execution = __esm({
93370
93953
  init_hyperliquid_client();
93371
93954
  init_hyperliquid_market_symbol();
93372
93955
  init_network_debug();
93956
+ init_copy_trading_evidence();
93373
93957
  init_protective_trigger_price();
93374
93958
  init_runtime_redaction();
93375
93959
  init_protective_stop_replacement();
@@ -94410,6 +94994,18 @@ var init_runtime_execution = __esm({
94410
94994
  input.executionContext.takeProfitMode === "usdc" ? input.executionContext.takeProfitUsdc : input.executionContext.takeProfitPct
94411
94995
  ) > 0);
94412
94996
  protectiveAction = (leg) => leg.kind === "sl" ? "AUTO_SL" : "AUTO_TP";
94997
+ executedProtectiveReport = (input) => ({
94998
+ order_id: input.orderId,
94999
+ ...input.clientMutationId !== void 0 ? { client_mutation_id: input.clientMutationId } : {},
95000
+ symbol: input.symbol,
95001
+ action: input.action,
95002
+ status: "executed",
95003
+ execution_metadata: {
95004
+ ...input.metadata,
95005
+ protected_size: input.protectedSize,
95006
+ position_tpsl: input.positionTpsl
95007
+ }
95008
+ });
94413
95009
  isExactClientPositionTpslPair = (legs) => legs.length === 2 && legs.every((leg) => leg.positionTpsl === true) && new Set(legs.map((leg) => leg.kind)).size === 2;
94414
95010
  deviceOwnsClientProtectiveLegKind = (group, kind) => group.deviceOwnedLegKinds == null || group.deviceOwnedLegKinds.includes(kind);
94415
95011
  isAdoptionNarrowedPositionTpslLeg = (group) => group.deviceOwnedLegKinds?.length === 1 && group.legs.length === 1 && group.legs[0].positionTpsl === true && group.legs[0].kind === group.deviceOwnedLegKinds[0];
@@ -94509,19 +95105,18 @@ var init_runtime_execution = __esm({
94509
95105
  if (!terminalShapeMatches) {
94510
95106
  throw new Error("Tracked protective order is absent without exact terminal shape evidence.");
94511
95107
  }
94512
- return {
94513
- order_id: String(leg.orderId),
95108
+ return executedProtectiveReport({
95109
+ orderId: String(leg.orderId),
94514
95110
  symbol: symbol2,
94515
95111
  action: protectiveAction(leg),
94516
- status: "executed",
94517
- execution_metadata: {
95112
+ protectedSize: leg.size,
95113
+ positionTpsl: leg.positionTpsl === true || evidence.isPositionTpsl === true,
95114
+ metadata: {
94518
95115
  trigger_price: leg.triggerPrice,
94519
95116
  reason_code: reasonCode,
94520
- terminal_order_status: evidence.orderStatus,
94521
- protected_size: leg.size,
94522
- position_tpsl: leg.positionTpsl === true || evidence.isPositionTpsl === true
95117
+ terminal_order_status: evidence.orderStatus
94523
95118
  }
94524
- };
95119
+ });
94525
95120
  }
94526
95121
  if (!protectiveLiveShapeMatches({
94527
95122
  shape: {
@@ -95168,20 +95763,19 @@ var init_runtime_execution = __esm({
95168
95763
  const activeLegs = acknowledgedLegs.filter((_leg, index) => acknowledgements[index].state === "active");
95169
95764
  const mixedPositionTpslAcknowledgement = positionTpsl && activeLegs.length === 1 && acknowledgements.some((acknowledgement) => acknowledgement.state === "fulfilled");
95170
95765
  for (let index = 0; index < candidates.length; index += 1) {
95171
- reports.push({
95172
- order_id: acknowledgements[index].orderId,
95173
- client_mutation_id: candidates[index].mutationId,
95766
+ reports.push(executedProtectiveReport({
95767
+ orderId: acknowledgements[index].orderId,
95768
+ clientMutationId: candidates[index].mutationId,
95174
95769
  symbol: symbol2,
95175
95770
  action: candidates[index].kind === "sl" ? "AUTO_SL" : "AUTO_TP",
95176
- status: "executed",
95177
- execution_metadata: {
95771
+ protectedSize: candidates[index].size,
95772
+ positionTpsl,
95773
+ metadata: {
95178
95774
  trigger_price: candidates[index].triggerPrice,
95179
- protected_size: candidates[index].size,
95180
95775
  entry_filled_size: fill.filledSize,
95181
- entry_average_price: fill.averagePrice,
95182
- position_tpsl: positionTpsl
95776
+ entry_average_price: fill.averagePrice
95183
95777
  }
95184
- });
95778
+ }));
95185
95779
  }
95186
95780
  const acknowledgedGroup = activeLegs.length > 0 ? {
95187
95781
  ...activeGroup,
@@ -96180,20 +96774,19 @@ var init_runtime_execution = __esm({
96180
96774
  if (!retired) {
96181
96775
  throw new Error("Terminal protective replacement could not be retired durably.");
96182
96776
  }
96183
- reports.push({
96184
- order_id: String(evidence.orderId ?? replacement.clientOrderId),
96185
- client_mutation_id: replacement.mutationId,
96777
+ reports.push(executedProtectiveReport({
96778
+ orderId: String(evidence.orderId ?? replacement.clientOrderId),
96779
+ clientMutationId: replacement.mutationId,
96186
96780
  symbol: symbol2,
96187
96781
  action: protectiveAction(leg),
96188
- status: "executed",
96189
- execution_metadata: {
96782
+ protectedSize: replacementLeg.size,
96783
+ positionTpsl: replacementLeg.positionTpsl === true,
96784
+ metadata: {
96190
96785
  reason_code: "protective_replacement_terminal_reconciled",
96191
96786
  previous_order_id: replacement.previousOrderId,
96192
- order_status: evidence.orderStatus,
96193
- protected_size: replacementLeg.size,
96194
- position_tpsl: replacementLeg.positionTpsl === true
96787
+ order_status: evidence.orderStatus
96195
96788
  }
96196
- });
96789
+ }));
96197
96790
  continue;
96198
96791
  }
96199
96792
  const ambiguousPositionTpslAuthority = hasAmbiguousClientPositionTpslAuthority(group);
@@ -96237,20 +96830,19 @@ var init_runtime_execution = __esm({
96237
96830
  if (!recovered) {
96238
96831
  throw new Error("Ambiguous position-TPSL replacement could not be bound durably.");
96239
96832
  }
96240
- reports.push({
96241
- order_id: String(replacementOrderId),
96242
- client_mutation_id: replacement.mutationId,
96833
+ reports.push(executedProtectiveReport({
96834
+ orderId: String(replacementOrderId),
96835
+ clientMutationId: replacement.mutationId,
96243
96836
  symbol: symbol2,
96244
96837
  action: protectiveAction(leg),
96245
- status: "executed",
96246
- execution_metadata: {
96838
+ protectedSize: replacement.size,
96839
+ positionTpsl: recoveredLeg.positionTpsl === true,
96840
+ metadata: {
96247
96841
  reason_code: exactLivePositionTpsl ? "protective_replacement_reconciled_for_cleanup" : "protective_replacement_reconciled",
96248
96842
  previous_order_id: replacement.previousOrderId,
96249
- trigger_price: replacement.triggerPrice,
96250
- protected_size: replacement.size,
96251
- position_tpsl: recoveredLeg.positionTpsl === true
96843
+ trigger_price: replacement.triggerPrice
96252
96844
  }
96253
- });
96845
+ }));
96254
96846
  continue;
96255
96847
  }
96256
96848
  if (ambiguousPositionTpslAuthority && classifyHyperliquidOrderStatus(evidence.orderStatus) !== "filled") {
@@ -96283,20 +96875,19 @@ var init_runtime_execution = __esm({
96283
96875
  throw new Error("Fulfilled protective replacement could not be resolved durably.");
96284
96876
  }
96285
96877
  removeTrackedTrailingStop(profileId, symbol2, replacement.previousOrderId);
96286
- reports.push({
96287
- order_id: String(replacementOrderId),
96288
- client_mutation_id: replacement.mutationId,
96878
+ reports.push(executedProtectiveReport({
96879
+ orderId: String(replacementOrderId),
96880
+ clientMutationId: replacement.mutationId,
96289
96881
  symbol: symbol2,
96290
96882
  action: protectiveAction(leg),
96291
- status: "executed",
96292
- execution_metadata: {
96883
+ protectedSize: replacement.size,
96884
+ positionTpsl: leg.positionTpsl === true,
96885
+ metadata: {
96293
96886
  reason_code: "protective_replacement_fulfilled_reconciled",
96294
96887
  previous_order_id: replacement.previousOrderId,
96295
- trigger_price: replacement.triggerPrice,
96296
- protected_size: replacement.size,
96297
- position_tpsl: leg.positionTpsl === true
96888
+ trigger_price: replacement.triggerPrice
96298
96889
  }
96299
- });
96890
+ }));
96300
96891
  continue;
96301
96892
  }
96302
96893
  let shapeMatches = exactShapeMatches && classifyHyperliquidOrderStatus(evidence.orderStatus) === "open";
@@ -96338,21 +96929,20 @@ var init_runtime_execution = __esm({
96338
96929
  if (replacementCleanup == null || !clearClientRuntimeVetoedProtectiveIntent(replacementCleanup)) {
96339
96930
  throw new Error("Unapplied protective replacement could not be abandoned durably.");
96340
96931
  }
96341
- reports.push({
96342
- order_id: String(replacement.previousOrderId),
96343
- client_mutation_id: replacement.mutationId,
96932
+ reports.push(executedProtectiveReport({
96933
+ orderId: String(replacement.previousOrderId),
96934
+ clientMutationId: replacement.mutationId,
96344
96935
  symbol: symbol2,
96345
96936
  action: protectiveAction(effectiveLeg),
96346
- status: "executed",
96347
- execution_metadata: {
96937
+ protectedSize: effectiveLeg.size,
96938
+ positionTpsl: effectiveLeg.positionTpsl === true,
96939
+ metadata: {
96348
96940
  reason_code: "protective_replacement_abandoned_original_filled",
96349
96941
  previous_order_id: replacement.previousOrderId,
96350
96942
  order_status: originalEvidence.orderStatus,
96351
- trigger_price: effectiveLeg.triggerPrice,
96352
- protected_size: effectiveLeg.size,
96353
- position_tpsl: effectiveLeg.positionTpsl === true
96943
+ trigger_price: effectiveLeg.triggerPrice
96354
96944
  }
96355
- });
96945
+ }));
96356
96946
  continue;
96357
96947
  }
96358
96948
  }
@@ -96362,20 +96952,19 @@ var init_runtime_execution = __esm({
96362
96952
  if (replacementCleanup == null || !clearClientRuntimeVetoedProtectiveIntent(replacementCleanup)) {
96363
96953
  throw new Error("Undispatched protective replacement could not be abandoned durably.");
96364
96954
  }
96365
- reports.push({
96366
- order_id: String(replacement.previousOrderId),
96367
- client_mutation_id: replacement.mutationId,
96955
+ reports.push(executedProtectiveReport({
96956
+ orderId: String(replacement.previousOrderId),
96957
+ clientMutationId: replacement.mutationId,
96368
96958
  symbol: symbol2,
96369
96959
  action: protectiveAction(effectiveLeg),
96370
- status: "executed",
96371
- execution_metadata: {
96960
+ protectedSize: effectiveLeg.size,
96961
+ positionTpsl: effectiveLeg.positionTpsl === true,
96962
+ metadata: {
96372
96963
  reason_code: "protective_replacement_abandoned_undispatched",
96373
96964
  previous_order_id: replacement.previousOrderId,
96374
- trigger_price: effectiveLeg.triggerPrice,
96375
- protected_size: effectiveLeg.size,
96376
- position_tpsl: effectiveLeg.positionTpsl === true
96965
+ trigger_price: effectiveLeg.triggerPrice
96377
96966
  }
96378
- });
96967
+ }));
96379
96968
  continue;
96380
96969
  }
96381
96970
  const replayReservation = replacementReservation;
@@ -96443,20 +97032,19 @@ var init_runtime_execution = __esm({
96443
97032
  }
96444
97033
  });
96445
97034
  }
96446
- reports.push({
96447
- order_id: String(replacementOrderId),
96448
- client_mutation_id: replacement.mutationId,
97035
+ reports.push(executedProtectiveReport({
97036
+ orderId: String(replacementOrderId),
97037
+ clientMutationId: replacement.mutationId,
96449
97038
  symbol: symbol2,
96450
97039
  action: protectiveAction(effectiveLeg),
96451
- status: "executed",
96452
- execution_metadata: {
97040
+ protectedSize: replacement.size,
97041
+ positionTpsl: effectiveLeg.positionTpsl === true,
97042
+ metadata: {
96453
97043
  reason_code: acknowledgement.state === "fulfilled" ? "protective_replacement_fulfilled_reconciled" : "protective_replacement_reconciled",
96454
97044
  previous_order_id: replacement.previousOrderId,
96455
- trigger_price: replacement.triggerPrice,
96456
- protected_size: replacement.size,
96457
- position_tpsl: effectiveLeg.positionTpsl === true
97045
+ trigger_price: replacement.triggerPrice
96458
97046
  }
96459
- });
97047
+ }));
96460
97048
  continue;
96461
97049
  }
96462
97050
  }
@@ -96482,20 +97070,19 @@ var init_runtime_execution = __esm({
96482
97070
  if (!bound) {
96483
97071
  throw new Error("Pending protective replacement could not be bound durably.");
96484
97072
  }
96485
- reports.push({
96486
- order_id: String(replacementOrderId),
96487
- client_mutation_id: replacement.mutationId,
97073
+ reports.push(executedProtectiveReport({
97074
+ orderId: String(replacementOrderId),
97075
+ clientMutationId: replacement.mutationId,
96488
97076
  symbol: symbol2,
96489
97077
  action: protectiveAction(effectiveLeg),
96490
- status: "executed",
96491
- execution_metadata: {
97078
+ protectedSize: replacement.size,
97079
+ positionTpsl: canonicalReplacementLeg.positionTpsl === true,
97080
+ metadata: {
96492
97081
  reason_code: "protective_replacement_reconciled",
96493
97082
  previous_order_id: replacement.previousOrderId,
96494
- trigger_price: replacement.triggerPrice,
96495
- protected_size: replacement.size,
96496
- position_tpsl: canonicalReplacementLeg.positionTpsl === true
97083
+ trigger_price: replacement.triggerPrice
96497
97084
  }
96498
- });
97085
+ }));
96499
97086
  } catch (error48) {
96500
97087
  if (replayAttemptStarted && !replayDispatchBoundaryCompleted && replacementCleanup != null) {
96501
97088
  if (isClientRuntimeWindowHandoffBeforePlanDispatch(error48)) {
@@ -96561,19 +97148,18 @@ var init_runtime_execution = __esm({
96561
97148
  if (!replaceExactClientProtectiveGroup(profileId, symbol2, journalGroup, null)) {
96562
97149
  throw new Error("Terminal replacement journal could not be retired durably.");
96563
97150
  }
96564
- reports.push({
96565
- order_id: String(evidence.orderId ?? journalLeg.orderId),
96566
- client_mutation_id: mutationId,
97151
+ reports.push(executedProtectiveReport({
97152
+ orderId: String(evidence.orderId ?? journalLeg.orderId),
97153
+ clientMutationId: mutationId,
96567
97154
  symbol: symbol2,
96568
97155
  action: protectiveAction(journalLeg),
96569
- status: "executed",
96570
- execution_metadata: {
97156
+ protectedSize: journalLeg.size,
97157
+ positionTpsl: journalLeg.positionTpsl === true || evidence.isPositionTpsl === true,
97158
+ metadata: {
96571
97159
  reason_code: "protective_replacement_terminal_reconciled",
96572
- order_status: evidence.orderStatus,
96573
- protected_size: journalLeg.size,
96574
- position_tpsl: journalLeg.positionTpsl === true || evidence.isPositionTpsl === true
97160
+ order_status: evidence.orderStatus
96575
97161
  }
96576
- });
97162
+ }));
96577
97163
  continue;
96578
97164
  }
96579
97165
  const liveShape = {
@@ -97365,22 +97951,21 @@ var init_runtime_execution = __esm({
97365
97951
  return {
97366
97952
  retain: bound ? placedLeg : provisionalLeg,
97367
97953
  group: bound ? placedGroup : provisionalGroup,
97368
- reports: [{
97369
- order_id: String(placedOrderId),
97370
- client_mutation_id: mutationId,
97954
+ reports: [executedProtectiveReport({
97955
+ orderId: String(placedOrderId),
97956
+ clientMutationId: mutationId,
97371
97957
  symbol: symbol2,
97372
97958
  action: protectiveAction(leg),
97373
- status: "executed",
97374
- execution_metadata: {
97959
+ protectedSize: decision.size,
97960
+ positionTpsl: false,
97961
+ metadata: {
97375
97962
  reason_code: decision.reasonCode,
97376
97963
  replaced_order_id: lostOrderId,
97377
97964
  trigger_price: triggerPrice,
97378
- protected_size: decision.size,
97379
97965
  live_position_size: livePositionSize2,
97380
- position_tpsl: false,
97381
97966
  ...acknowledgement.state === "fulfilled" ? { acknowledgement_state: "fulfilled" } : {}
97382
97967
  }
97383
- }]
97968
+ })]
97384
97969
  };
97385
97970
  };
97386
97971
  groupLoop: for (let groupIndex = 0; groupIndex < inspectedGroups.length; groupIndex += 1) {
@@ -97679,19 +98264,18 @@ var init_runtime_execution = __esm({
97679
98264
  } else {
97680
98265
  removeTrackedTrailingStop(profileId, symbol2, leg.orderId);
97681
98266
  }
97682
- reports.push({
97683
- order_id: String(replacementOrderId),
97684
- client_mutation_id: _extractClientMutationId(response),
98267
+ reports.push(executedProtectiveReport({
98268
+ orderId: String(replacementOrderId),
98269
+ clientMutationId: _extractClientMutationId(response),
97685
98270
  symbol: symbol2,
97686
98271
  action: protectiveAction(leg),
97687
- status: "executed",
97688
- execution_metadata: {
98272
+ protectedSize: allowedSize,
98273
+ positionTpsl: replacementLeg.positionTpsl === true,
98274
+ metadata: {
97689
98275
  reason_code: "protective_resized_to_live_exposure",
97690
- previous_order_id: leg.orderId,
97691
- protected_size: allowedSize,
97692
- position_tpsl: replacementLeg.positionTpsl === true
98276
+ previous_order_id: leg.orderId
97693
98277
  }
97694
- });
98278
+ }));
97695
98279
  if (fulfilledDuringResize) {
97696
98280
  reports.push({
97697
98281
  order_id: String(replacementOrderId),
@@ -98141,20 +98725,19 @@ var init_runtime_execution = __esm({
98141
98725
  }
98142
98726
  });
98143
98727
  }
98144
- reports.push({
98145
- order_id: String(replacementOrderId),
98146
- client_mutation_id: _extractClientMutationId(modifyResponse),
98728
+ reports.push(executedProtectiveReport({
98729
+ orderId: String(replacementOrderId),
98730
+ clientMutationId: _extractClientMutationId(modifyResponse),
98147
98731
  symbol: symbol2,
98148
98732
  action: "AUTO_TRAILING_SL",
98149
- status: "executed",
98150
- execution_metadata: {
98733
+ protectedSize: effectiveSize,
98734
+ positionTpsl: record5.positionTpsl === true,
98735
+ metadata: {
98151
98736
  trigger_price: replacementTriggerPrice,
98152
98737
  previous_trigger_price: record5.triggerPrice,
98153
- previous_order_id: record5.orderId,
98154
- protected_size: effectiveSize,
98155
- position_tpsl: record5.positionTpsl === true
98738
+ previous_order_id: record5.orderId
98156
98739
  }
98157
- });
98740
+ }));
98158
98741
  } catch (error48) {
98159
98742
  const cleanup = buildVetoedProtectiveReplacementCleanup(reservation);
98160
98743
  if (!replacementDispatchBoundaryCompleted) {
@@ -100120,22 +100703,21 @@ var init_runtime_execution = __esm({
100120
100703
  }
100121
100704
  );
100122
100705
  }
100123
- executionReports.push({
100124
- order_id: String(triggerOrderId),
100125
- client_mutation_id: _extractClientMutationId(triggerResponse),
100706
+ executionReports.push(executedProtectiveReport({
100707
+ orderId: String(triggerOrderId),
100708
+ clientMutationId: _extractClientMutationId(triggerResponse),
100126
100709
  symbol: input.executionContext.symbol,
100127
100710
  action: triggerInput.label,
100128
- status: "executed",
100129
- execution_metadata: {
100711
+ protectedSize: legSize,
100712
+ positionTpsl: leg.positionTpsl === true,
100713
+ metadata: {
100130
100714
  trigger_price: triggerInput.triggerPrice,
100131
100715
  is_take_profit: triggerInput.isTakeProfit,
100132
100716
  entry_filled_size: protectionSize,
100133
- protected_size: legSize,
100134
- position_tpsl: leg.positionTpsl === true,
100135
100717
  entry_average_price: protectionEntryPrice,
100136
100718
  ..._toExecutionMetadata(triggerResponse)
100137
100719
  }
100138
- });
100720
+ }));
100139
100721
  appendRuntimeDebugEvent({
100140
100722
  label: "execution_auto_sl_tp_submitted",
100141
100723
  note: `symbol=${input.executionContext.symbol} kind=${triggerInput.isTakeProfit ? "tp" : "sl"} side=${exitSide} sizeAsset=${legSize} triggerPrice=${triggerInput.triggerPrice} order_id=${triggerOrderId}`
@@ -100348,6 +100930,7 @@ var init_runtime_execution = __esm({
100348
100930
  let minOrderNotional = 0;
100349
100931
  let executionReferencePrice = Number(intent.source_price);
100350
100932
  let dispatchedOrder = null;
100933
+ let ownPositionHold = {};
100351
100934
  if (reconciliation && typeof reconciliation === "object" && !Array.isArray(reconciliation)) {
100352
100935
  const record5 = reconciliation;
100353
100936
  const copiedNowServed = typeof record5.copied_now === "number" && Number.isFinite(record5.copied_now);
@@ -100375,7 +100958,11 @@ var init_runtime_execution = __esm({
100375
100958
  size: destinationSize,
100376
100959
  roundingMode: "nearest",
100377
100960
  includePrivateContext: desiredPosition != null && Number.isFinite(desiredPosition),
100378
- profileId: input.profileId
100961
+ profileId: input.profileId,
100962
+ // The device reads its own position and mark; the server never reads
100963
+ // a Client wallet.
100964
+ walletAddress: input.walletAddress,
100965
+ signal: input.signal
100379
100966
  });
100380
100967
  if (desiredPosition != null && Number.isFinite(desiredPosition)) {
100381
100968
  const preparedContextMaxAgeMs = Number(
@@ -100397,26 +100984,35 @@ var init_runtime_execution = __esm({
100397
100984
  if (!Number.isFinite(executionReferencePrice) || executionReferencePrice <= 0) {
100398
100985
  throw new Error("Copy Trading private-node execution mark was unavailable.");
100399
100986
  }
100400
- desiredPosition = positionSpaceCopyTarget(
100987
+ const copiedNow = copiedTargetNow(
100401
100988
  reconciliation,
100402
100989
  desiredPosition,
100403
100990
  actualPosition
100404
100991
  );
100992
+ if (copiedNow && Math.abs(copiedNow.targetNow - copiedNow.kept) > 1e-12) {
100993
+ ownPositionHold = {
100994
+ own_position_held_back_target: copiedNow.targetNow,
100995
+ own_position_kept_target: copiedNow.kept
100996
+ };
100997
+ }
100998
+ desiredPosition = copiedNow ? actualPosition + (copiedNow.kept - copiedNow.copiedNow) : desiredPosition;
100405
100999
  const liveDelta = desiredPosition - actualPosition;
100406
101000
  const tolerance = Math.max(1e-12, Math.abs(desiredPosition) * 1e-9);
100407
101001
  if (Math.abs(liveDelta) <= tolerance) {
101002
+ const heldBack = Object.keys(ownPositionHold).length > 0;
100408
101003
  return {
100409
101004
  status: "executed",
100410
101005
  orderId: null,
100411
- message: "Copy Trading destination position is already at target.",
100412
- skipReason: "already_at_target",
101006
+ message: heldBack ? "Copy Trading skipped a copy against your own opposite position." : "Copy Trading destination position is already at target.",
101007
+ skipReason: heldBack ? "own_position_opposite_side" : "already_at_target",
100413
101008
  destinationSize: 0,
100414
101009
  destinationNotional: 0,
100415
101010
  executionMetadata: {
100416
101011
  execution_reference_price: executionReferencePrice,
100417
101012
  desired_destination_position_after: desiredPosition,
100418
101013
  actual_destination_position: actualPosition,
100419
- no_order_required: true
101014
+ no_order_required: true,
101015
+ ...ownPositionHold
100420
101016
  }
100421
101017
  };
100422
101018
  }
@@ -100477,7 +101073,8 @@ var init_runtime_execution = __esm({
100477
101073
  quantized_size: 0,
100478
101074
  sz_decimals: sizePrecision.sizeDecimals,
100479
101075
  rounding_mode: sizePrecision.roundingMode,
100480
- execution_reference_price: referencePrice
101076
+ execution_reference_price: referencePrice,
101077
+ ...ownPositionHold
100481
101078
  }
100482
101079
  };
100483
101080
  }
@@ -100499,7 +101096,8 @@ var init_runtime_execution = __esm({
100499
101096
  rounding_mode: sizePrecision.roundingMode,
100500
101097
  execution_reference_price: referencePrice,
100501
101098
  minimum_usdc: minOrderNotional,
100502
- order_deferred: true
101099
+ order_deferred: true,
101100
+ ...ownPositionHold
100503
101101
  }
100504
101102
  };
100505
101103
  }
@@ -100511,6 +101109,7 @@ var init_runtime_execution = __esm({
100511
101109
  intent.sanitized_metadata?.client_order_id
100512
101110
  );
100513
101111
  dispatchedOrder = {
101112
+ ...ownPositionHold,
100514
101113
  quantized_size: destinationSize,
100515
101114
  ...desiredPosition != null && Number.isFinite(desiredPosition) && actualPosition != null && Number.isFinite(actualPosition) ? {
100516
101115
  desired_destination_position_after: desiredPosition,
@@ -100564,6 +101163,7 @@ var init_runtime_execution = __esm({
100564
101163
  // The server records the executed change in the copied-position
100565
101164
  // ledger from these values.
100566
101165
  ...filledSize != null ? { filled_size: filledSize } : {},
101166
+ ...ownPositionHold,
100567
101167
  ...desiredPosition != null && Number.isFinite(desiredPosition) && actualPosition != null && Number.isFinite(actualPosition) ? {
100568
101168
  desired_destination_position_after: desiredPosition,
100569
101169
  actual_destination_position: actualPosition
@@ -100584,6 +101184,13 @@ var init_runtime_execution = __esm({
100584
101184
  };
100585
101185
  }
100586
101186
  };
101187
+ _copyCancelOrderId = (action) => {
101188
+ const destinationOrderId = action.previous_destination_order_id ?? action.destination_order_id;
101189
+ const numericOrderId = Number(destinationOrderId);
101190
+ if (Number.isSafeInteger(numericOrderId) && numericOrderId > 0) return numericOrderId;
101191
+ const cloid = String(destinationOrderId || "").trim().toLowerCase();
101192
+ return /^0x[0-9a-f]{32}$/.test(cloid) ? cloid : null;
101193
+ };
100587
101194
  executeClientCopyTradingOrderAction = async (input) => {
100588
101195
  throwIfAborted2(input.signal);
100589
101196
  const action = input.action;
@@ -100614,12 +101221,18 @@ var init_runtime_execution = __esm({
100614
101221
  signal: input.signal,
100615
101222
  onExchangeOrderDispatched: () => input.onExchangeOrderDispatched?.("action")
100616
101223
  };
101224
+ const cancelledOrderStatusEvidence = async (orderId) => {
101225
+ if (orderId == null) return {};
101226
+ const evidence = await readCopyOrderStatusEvidence(
101227
+ { config: input.config ?? null, signal: input.signal, walletAddress: input.walletAddress },
101228
+ orderId
101229
+ );
101230
+ return evidence ? { orderStatusEvidence: evidence } : {};
101231
+ };
100617
101232
  try {
100618
101233
  if (action.action_type === "cancel") {
100619
- const destinationOrderId2 = action.previous_destination_order_id ?? action.destination_order_id;
100620
- const numericOrderId = Number(destinationOrderId2);
100621
- const orderId = Number.isSafeInteger(numericOrderId) && numericOrderId > 0 ? numericOrderId : String(destinationOrderId2 || "").trim().toLowerCase();
100622
- if (typeof orderId === "number" && orderId <= 0 || typeof orderId === "string" && !/^0x[0-9a-f]{32}$/.test(orderId)) {
101234
+ const orderId = _copyCancelOrderId(action);
101235
+ if (orderId == null) {
100623
101236
  throw new Error("Copy Trading cancel action is missing a valid destination order id.");
100624
101237
  }
100625
101238
  await executeClientCancelOrder({
@@ -100631,7 +101244,8 @@ var init_runtime_execution = __esm({
100631
101244
  destinationOrderId: String(orderId),
100632
101245
  destinationOrderState: null,
100633
101246
  orderMemberResults: null,
100634
- message: "Copy Trading order cancellation executed."
101247
+ message: "Copy Trading order cancellation executed.",
101248
+ ...await cancelledOrderStatusEvidence(orderId)
100635
101249
  };
100636
101250
  }
100637
101251
  const size = Number(action.destination_size);
@@ -100725,7 +101339,8 @@ var init_runtime_execution = __esm({
100725
101339
  destinationOrderId: action.previous_destination_order_id ?? action.destination_order_id ?? null,
100726
101340
  destinationOrderState: null,
100727
101341
  orderMemberResults: null,
100728
- message: "Copy Trading order was already terminal."
101342
+ message: "Copy Trading order was already terminal.",
101343
+ ...await cancelledOrderStatusEvidence(_copyCancelOrderId(action))
100729
101344
  };
100730
101345
  }
100731
101346
  return {
@@ -103755,7 +104370,7 @@ var require_react = __commonJS({
103755
104370
  });
103756
104371
 
103757
104372
  // lib/runtime/client-runtime-status-store.ts
103758
- var import_react, finiteOrNull2, readMode, orderKey, sameOwnerSeries, hasGenerations, compareClientRuntimeStatusOrder, sameGenerations, LIVENESS_CLOCK_FIELDS, sameValue, sameVisibleState, definedFields, ClientRuntimeStatusStore, clientRuntimeStatusStore;
104373
+ var import_react, finiteOrNull2, readMode, orderKey, sameOwnerSeries, hasGenerations, compareClientRuntimeStatusOrder, sameGenerations, LIVENESS_CLOCK_FIELDS, sameValue, sameVisibleState, definedFields, readServerBackup, PROFILE_FIELDS, keepProfileFields, ClientRuntimeStatusStore, clientRuntimeStatusStore;
103759
104374
  var init_client_runtime_status_store = __esm({
103760
104375
  "lib/runtime/client-runtime-status-store.ts"() {
103761
104376
  "use strict";
@@ -103818,6 +104433,17 @@ var init_client_runtime_status_store = __esm({
103818
104433
  return true;
103819
104434
  };
103820
104435
  definedFields = (status) => Object.fromEntries(Object.entries(status).filter(([, value]) => value !== void 0));
104436
+ readServerBackup = (value) => value && typeof value === "object" && typeof value.active === "boolean" ? value : null;
104437
+ PROFILE_FIELDS = ["execution_mode", "server_backup"];
104438
+ keepProfileFields = (current, incoming) => {
104439
+ const kept = {};
104440
+ for (const field of PROFILE_FIELDS) {
104441
+ if (incoming[field] === void 0 && current[field] !== void 0) {
104442
+ kept[field] = current[field];
104443
+ }
104444
+ }
104445
+ return { ...kept, ...incoming };
104446
+ };
103821
104447
  ClientRuntimeStatusStore = class {
103822
104448
  constructor() {
103823
104449
  this.entries = /* @__PURE__ */ new Map();
@@ -103842,7 +104468,7 @@ var init_client_runtime_status_store = __esm({
103842
104468
  } else {
103843
104469
  const order = compareClientRuntimeStatusOrder(incoming, current);
103844
104470
  if (order < 0) return false;
103845
- next = sameGenerations(incoming, current) || !hasGenerations(orderKey(incoming)) ? { ...current, ...incoming } : incoming;
104471
+ next = sameGenerations(incoming, current) || !hasGenerations(orderKey(incoming)) ? { ...current, ...incoming } : keepProfileFields(current, incoming);
103846
104472
  if (sameVisibleState(next, current)) {
103847
104473
  const clocks = Object.fromEntries(
103848
104474
  Object.entries(next).filter(([field]) => LIVENESS_CLOCK_FIELDS.has(field))
@@ -103859,6 +104485,21 @@ var init_client_runtime_status_store = __esm({
103859
104485
  this.emit();
103860
104486
  return true;
103861
104487
  }
104488
+ /**
104489
+ * Record the server's backup state from an answer that carries only that
104490
+ * (a readiness report's): it updates the profile's entry, and is dropped
104491
+ * when this browser has no status for the profile yet. Returns true when
104492
+ * the entry changed.
104493
+ */
104494
+ recordServerBackup(profileId, backup) {
104495
+ const key = String(profileId ?? "").trim();
104496
+ const current = key ? this.entries.get(key) : void 0;
104497
+ const next = readServerBackup(backup);
104498
+ if (!current || !next || sameValue(current.server_backup, next)) return false;
104499
+ this.entries.set(key, { ...current, server_backup: next });
104500
+ this.emit();
104501
+ return true;
104502
+ }
103862
104503
  get(profileId) {
103863
104504
  const key = String(profileId ?? "").trim();
103864
104505
  return key ? this.entries.get(key) ?? null : null;
@@ -112863,8 +113504,11 @@ ${reviewOutputContract}`;
112863
113504
  startPosition: fill.start_position
112864
113505
  }))
112865
113506
  );
112866
- const perSymbolCap = 500;
112867
- const totalCap = 5e3;
113507
+ const perSymbolCap = Number(input.maxFillsPerSymbol);
113508
+ if (!Number.isInteger(perSymbolCap) || perSymbolCap < 1) {
113509
+ throw new Error("Missing required behavior memory max_fills_per_symbol configuration.");
113510
+ }
113511
+ const totalCap = perSymbolCap * Math.max(selectedSymbols.size, 1);
112868
113512
  const behaviorMemoryEnabled = input.behaviorMemoryEnabled ?? false;
112869
113513
  const rawPerSymbolCounts = /* @__PURE__ */ new Map();
112870
113514
  for (const fill of fillsDescending) {
@@ -114722,6 +115366,7 @@ ${behaviorJson}
114722
115366
  behaviorInstructions: promptBehaviorInstructions,
114723
115367
  lastTrades: asRecord(derivedContext.behavior_last_trades),
114724
115368
  behaviorMemoryEnabled,
115369
+ maxFillsPerSymbol: config2.behavior_memory_max_fills_per_symbol,
114725
115370
  decisionMemory: asRecord(derivedContext.behavior_decision_memory),
114726
115371
  cycleCutoffMs: behaviorMemoryCutoffMs,
114727
115372
  fillHistoryCoverage: behaviorFillCoverage
@@ -116097,7 +116742,7 @@ ${reviewOutputContract}`;
116097
116742
  });
116098
116743
 
116099
116744
  // lib/runtime/engine.ts
116100
- var localAnalysis, getExchangeFailureDiagnostics, getRuntimeFallbackAttempts, sentInvocationAttemptCount, boundRuntimeFallbackAttempts, isProviderFailureDiagnosticsCandidate, getEventBoundProviderLabel, getEventBoundProviderTraceId, getRecentProviderFailureDiagnostics, getClientRuntimeErrorProvenance, getRuntimeProviderSetupDiagnostics, buildProviderSetupErrorDiagnosticFields, buildClientRuntimeErrorProvenanceDiagnosticFields, buildRuntimeRequestErrorDiagnosticFields, getCycleErrorModelCalls, isReturnedModelCall, hasEventBoundProviderFailureEvidence, endsWithNeverSentAttempt, classifyRuntimeErrorStage, buildHyperliquidPublicReadDiagnosticFields, buildRuntimeErrorDiagnostics, positiveNumber, resolveRuntimeEngineOptions, withServerPositionEvents, CLIENT_KILLSWITCH_BLOCK_STORAGE_PREFIX, getClientKillswitchBlockStorageKey, persistClientRuntimeKillswitchBlock, clearClientRuntimeKillswitchBlock, hashRuntimeDebugText2, createRuntimeUuid2, getRuntimeContractIdentityToken, getRuntimeStatusContractIdentityToken, getRuntimeContractBindingTokenFromCycleResult, getRuntimeContractBindingTupleToken, getRuntimeStatusContractBindingTupleToken, isTransientRuntimeConflictError, createRuntimeStartCancelledError, isRuntimeContractMismatchError, isClientExecutionModeMismatchError, isClientRuntimeSessionStoppedError, isClientRuntimeLeaseAuthError, isClientRuntimeReleasedError, deriveFailedStartCleanupOwnershipLossReason, isRuntimeAbortError, isExplicitClientExecutionMode, createStopAbortError, isRuntimeContractIdentityAdvancedAbort, CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON, sanitizeSettingsSnapshotForFallback, preflightClientRuntime, ClientExecutionEngine, createStoppedRuntimeSnapshot, ClientRuntimeRegistry, botEngine;
116745
+ var localAnalysis, getExchangeFailureDiagnostics, getRuntimeFallbackAttempts, sentInvocationAttemptCount, boundRuntimeFallbackAttempts, isProviderFailureDiagnosticsCandidate, getEventBoundProviderLabel, getEventBoundProviderTraceId, CLIENT_RUNTIME_POLICY, getRecentProviderFailureDiagnostics, getClientRuntimeErrorProvenance, getRuntimeProviderSetupDiagnostics, buildProviderSetupErrorDiagnosticFields, buildClientRuntimeErrorProvenanceDiagnosticFields, buildRuntimeRequestErrorDiagnosticFields, getCycleErrorModelCalls, isReturnedModelCall, hasEventBoundProviderFailureEvidence, endsWithNeverSentAttempt, classifyRuntimeErrorStage, buildHyperliquidPublicReadDiagnosticFields, buildRuntimeErrorDiagnostics, positiveNumber, resolveRuntimeEngineOptions, withServerPositionEvents, CLIENT_KILLSWITCH_BLOCK_STORAGE_PREFIX, getClientKillswitchBlockStorageKey, isClientRuntimeKillswitchBlocked, persistClientRuntimeKillswitchBlock, clearClientRuntimeKillswitchBlock, hashRuntimeDebugText2, createRuntimeUuid2, getRuntimeContractIdentityToken, getRuntimeStatusContractIdentityToken, getRuntimeContractBindingTokenFromCycleResult, getRuntimeContractBindingTupleToken, getRuntimeStatusContractBindingTupleToken, isTransientRuntimeConflictError, createRuntimeStartCancelledError, isRuntimeContractMismatchError, isClientExecutionModeMismatchError, isClientRuntimeSessionStoppedError, isClientRuntimeLeaseAuthError, isClientRuntimeReleasedError, deriveFailedStartCleanupOwnershipLossReason, isRuntimeAbortError, isExplicitClientExecutionMode, createStopAbortError, isRuntimeContractIdentityAdvancedAbort, CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON, sanitizeSettingsSnapshotForFallback, preflightClientRuntime, ClientExecutionEngine, createStoppedRuntimeSnapshot, ClientRuntimeRegistry, botEngine;
116101
116746
  var init_engine = __esm({
116102
116747
  "lib/runtime/engine.ts"() {
116103
116748
  "use strict";
@@ -116105,6 +116750,8 @@ var init_engine = __esm({
116105
116750
  init_define_VTX_GROK_POLICY();
116106
116751
  init_define_VTX_PI_MODEL_POLICY();
116107
116752
  init_protective_cutover();
116753
+ init_runtime_policy_generated2();
116754
+ init_constants();
116108
116755
  init_periodic_schedule();
116109
116756
  init_host_storage();
116110
116757
  init_vault();
@@ -116136,6 +116783,7 @@ var init_engine = __esm({
116136
116783
  init_api2();
116137
116784
  init_history_evidence();
116138
116785
  init_portfolio_evidence();
116786
+ init_copy_trading_evidence();
116139
116787
  getExchangeFailureDiagnostics = (error48) => {
116140
116788
  if (error48 instanceof HyperliquidExchangeRejectionError) {
116141
116789
  return {
@@ -116247,6 +116895,7 @@ var init_engine = __esm({
116247
116895
  }
116248
116896
  return null;
116249
116897
  };
116898
+ CLIENT_RUNTIME_POLICY = runtime_policy_generated_default2.trading.engine.client_runtime;
116250
116899
  getRecentProviderFailureDiagnostics = (reason) => {
116251
116900
  const providerLabel = reason === void 0 ? null : getEventBoundProviderLabel(reason);
116252
116901
  const traceId = reason === void 0 ? null : getEventBoundProviderTraceId(reason);
@@ -116254,7 +116903,7 @@ var init_engine = __esm({
116254
116903
  return null;
116255
116904
  }
116256
116905
  const snapshot = getLatestRuntimeProviderFailureTelemetrySnapshot({
116257
- maxAgeMs: 3e4,
116906
+ maxAgeMs: CLIENT_RUNTIME_POLICY.provider_failure_diagnostics_max_age_milliseconds,
116258
116907
  label: providerLabel,
116259
116908
  traceId
116260
116909
  });
@@ -116363,7 +117012,7 @@ var init_engine = __esm({
116363
117012
  runtime_request_transient_network: record5.runtimeRequestTransientNetwork === true,
116364
117013
  runtime_request_deadline_at_ms: numberOrNull(record5.runtimeRequestDeadlineAtMs),
116365
117014
  runtime_request_deadline_exceeded: record5.runtimeRequestDeadlineExceeded === true,
116366
- ...record5.code === "snapshot_stale" && record5.runtimeRequestStatus === 409 ? {
117015
+ ...record5.code === "snapshot_stale" && record5.runtimeRequestStatus === HTTP_STATUS.CONFLICT ? {
116367
117016
  runtime_rejection_reason_code: "snapshot_stale",
116368
117017
  snapshot_age_seconds: numberOrNull(record5.runtimeSnapshotAgeSeconds),
116369
117018
  snapshot_max_age_seconds: numberOrNull(record5.runtimeSnapshotMaxAgeSeconds)
@@ -116545,6 +117194,13 @@ var init_engine = __esm({
116545
117194
  });
116546
117195
  CLIENT_KILLSWITCH_BLOCK_STORAGE_PREFIX = "vtx_client_runtime_killswitch_block_v1:";
116547
117196
  getClientKillswitchBlockStorageKey = (profileId) => `${CLIENT_KILLSWITCH_BLOCK_STORAGE_PREFIX}${profileId.trim()}`;
117197
+ isClientRuntimeKillswitchBlocked = (profileId) => {
117198
+ const storage3 = runtimeHostStorage();
117199
+ if (!storage3 || !profileId.trim()) {
117200
+ return false;
117201
+ }
117202
+ return storage3.getItem(getClientKillswitchBlockStorageKey(profileId)) !== null;
117203
+ };
116548
117204
  persistClientRuntimeKillswitchBlock = (profileId) => {
116549
117205
  const storage3 = runtimeHostStorage();
116550
117206
  if (!storage3 || !profileId.trim()) {
@@ -116613,7 +117269,7 @@ var init_engine = __esm({
116613
117269
  };
116614
117270
  isTransientRuntimeConflictError = (error48) => {
116615
117271
  const structured = error48;
116616
- if (Number(structured?.status) === 409 && structured?.retryable === true && (structured?.code === "profile_runtime_contract_busy" || structured?.code === "runtime_decision_finalizing" || structured?.code === "runtime_trade_sync_finalizing")) {
117272
+ if (Number(structured?.status) === HTTP_STATUS.CONFLICT && structured?.retryable === true && (structured?.code === "profile_runtime_contract_busy" || structured?.code === "runtime_decision_finalizing" || structured?.code === "runtime_trade_sync_finalizing")) {
116617
117273
  return true;
116618
117274
  }
116619
117275
  const hasStructuredMetadata = Number.isFinite(Number(structured?.status)) || typeof structured?.code === "string" || typeof structured?.retryable === "boolean";
@@ -116811,7 +117467,7 @@ var init_engine = __esm({
116811
117467
  this._pendingProtectionRecoveryDispatched = false;
116812
117468
  this._lastPendingProtectionRecoveryAtMs = null;
116813
117469
  this._primaryAnalysisDisabled = false;
116814
- this._loopEarlyReturnRetryDelayMs = 5e3;
117470
+ this._loopEarlyReturnRetryDelayMs = CLIENT_RUNTIME_POLICY.loop_early_return_retry_milliseconds;
116815
117471
  this._executionModeMismatchConsecutiveCount = 0;
116816
117472
  this._expectedExecutionMode = "client";
116817
117473
  this._settleUnreportedModelCalls = null;
@@ -116978,7 +117634,7 @@ var init_engine = __esm({
116978
117634
  signal.removeEventListener("abort", finish);
116979
117635
  resolve14();
116980
117636
  };
116981
- const timeoutId = globalThis.setTimeout(finish, 1e3);
117637
+ const timeoutId = globalThis.setTimeout(finish, CLIENT_RUNTIME_POLICY.window_handoff_cleanup_retry_milliseconds);
116982
117638
  signal.addEventListener("abort", finish, { once: true });
116983
117639
  });
116984
117640
  }
@@ -117120,8 +117776,8 @@ var init_engine = __esm({
117120
117776
  const phase = policy2.phase_seconds;
117121
117777
  const interval = policy2.interval_seconds;
117122
117778
  const valid = phase != null && interval != null && Number.isFinite(phase) && Number.isFinite(interval) && interval > 0 && phase >= 0 && phase < interval && Number.isFinite(status?.server_time) && Number(status?.server_time) > 0;
117123
- const phaseMs = valid ? Math.round(phase * 1e3) : null;
117124
- const intervalMs = valid ? Math.round(interval * 1e3) : null;
117779
+ const phaseMs = valid ? Math.round(phase * MS_PER_SECOND) : null;
117780
+ const intervalMs = valid ? Math.round(interval * MS_PER_SECOND) : null;
117125
117781
  const grace = Number(policy2.dispatch_grace_ms);
117126
117782
  if (!Number.isFinite(grace) || grace < 0) throw new Error("Invalid periodic analysis dispatch grace.");
117127
117783
  const intervalChanged = intervalMs != null && this._loopIntervalMs != null && this._loopIntervalMs !== intervalMs;
@@ -117132,7 +117788,7 @@ var init_engine = __esm({
117132
117788
  phaseMs,
117133
117789
  intervalMs,
117134
117790
  dispatchGraceMs: grace,
117135
- localMinusServerMs: sameAssignment ? previous.localMinusServerMs : valid ? observedAtMs - Number(status?.server_time) * 1e3 : 0
117791
+ localMinusServerMs: sameAssignment ? previous.localMinusServerMs : valid ? observedAtMs - Number(status?.server_time) * MS_PER_SECOND : 0
117136
117792
  };
117137
117793
  if (!sameAssignment) {
117138
117794
  this._lastPeriodicSlotServerMs = null;
@@ -117469,7 +118125,7 @@ var init_engine = __esm({
117469
118125
  lastStopProfileId: this._lastStopProfileId,
117470
118126
  lastRunAt: this._lastRunAt,
117471
118127
  nextRunAtMs: this._primaryAnalysisDisabled ? null : this._nextRunAtMs,
117472
- loopIntervalSeconds: this._loopIntervalMs == null ? null : Math.max(1, Math.round(this._loopIntervalMs / 1e3)),
118128
+ loopIntervalSeconds: this._loopIntervalMs == null ? null : Math.max(1, Math.round(this._loopIntervalMs / MS_PER_SECOND)),
117473
118129
  schedulerPhase: this._getSchedulerPhase(),
117474
118130
  primaryAnalysisDisabled: this._primaryAnalysisDisabled,
117475
118131
  ownershipLossReason: this._ownershipLossReason,
@@ -117517,7 +118173,7 @@ var init_engine = __esm({
117517
118173
  if (!Number.isFinite(parsedSeconds) || parsedSeconds <= 0) {
117518
118174
  throw new Error(`Missing required ${errorLabel}.`);
117519
118175
  }
117520
- return Math.round(parsedSeconds * 1e3);
118176
+ return Math.round(parsedSeconds * MS_PER_SECOND);
117521
118177
  }
117522
118178
  _resolveAnalysisStaleAfterMs(rawSeconds, defaultTimeoutSeconds) {
117523
118179
  const parsedSeconds = Number(rawSeconds);
@@ -117528,7 +118184,7 @@ var init_engine = __esm({
117528
118184
  if (Number.isFinite(parsedDefaultTimeoutSeconds) && parsedDefaultTimeoutSeconds > 0 && parsedSeconds < parsedDefaultTimeoutSeconds) {
117529
118185
  throw new Error("Client runtime stale analysis timeout must be greater than or equal to the default timeout.");
117530
118186
  }
117531
- return Math.round(parsedSeconds * 1e3);
118187
+ return Math.round(parsedSeconds * MS_PER_SECOND);
117532
118188
  }
117533
118189
  _resolveLoopIntervalMs(loopIntervalSeconds, minLoopIntervalSeconds) {
117534
118190
  const parsedSeconds = Number(loopIntervalSeconds);
@@ -117542,7 +118198,7 @@ var init_engine = __esm({
117542
118198
  if (parsedSeconds < parsedMinSeconds) {
117543
118199
  throw new Error(`Client runtime loop interval must be at least ${parsedMinSeconds} seconds.`);
117544
118200
  }
117545
- return Math.round(parsedSeconds * 1e3);
118201
+ return Math.round(parsedSeconds * MS_PER_SECOND);
117546
118202
  }
117547
118203
  _initializeNextRunAnchor(referenceMs = Date.now()) {
117548
118204
  if (this._loopIntervalMs == null) {
@@ -118086,7 +118742,7 @@ var init_engine = __esm({
118086
118742
  this._executionModeMismatchConsecutiveCount = 0;
118087
118743
  const responseNextRunSeconds = Number(grant.runtime?.next_run);
118088
118744
  const responseServerTimeSeconds = Number(grant.runtime?.server_time);
118089
- const assignedNextRunAtMs = grant.runtime?.server_time != null && Number.isFinite(responseServerTimeSeconds) && responseServerTimeSeconds > 0 && Number.isFinite(responseNextRunSeconds) && responseNextRunSeconds > responseServerTimeSeconds ? Date.now() + (responseNextRunSeconds - responseServerTimeSeconds) * 1e3 : responseNextRunSeconds * 1e3;
118745
+ const assignedNextRunAtMs = grant.runtime?.server_time != null && Number.isFinite(responseServerTimeSeconds) && responseServerTimeSeconds > 0 && Number.isFinite(responseNextRunSeconds) && responseNextRunSeconds > responseServerTimeSeconds ? Date.now() + (responseNextRunSeconds - responseServerTimeSeconds) * MS_PER_SECOND : responseNextRunSeconds * MS_PER_SECOND;
118090
118746
  const waitsForAssignedStartPhase = Boolean(this._periodicSchedule) || Number.isFinite(assignedNextRunAtMs) && assignedNextRunAtMs > Date.now();
118091
118747
  if (waitsForAssignedStartPhase) {
118092
118748
  if (this._periodicSchedule) this._initializeNextRunAnchor();
@@ -118786,7 +119442,7 @@ var init_engine = __esm({
118786
119442
  const now = Date.now();
118787
119443
  const observations = this._trailingObservations.filter(({ executionContext }) => {
118788
119444
  const capturedAt = Date.parse(executionContext.decisionSnapshotCapturedAt ?? "");
118789
- const maxAge = Number(executionContext.executionFreshnessMaxAgeSeconds) * 1e3;
119445
+ const maxAge = Number(executionContext.executionFreshnessMaxAgeSeconds) * MS_PER_SECOND;
118790
119446
  const age = now - capturedAt;
118791
119447
  return Number.isFinite(age) && age >= 0 && Number.isFinite(maxAge) && maxAge > 0 && age <= maxAge;
118792
119448
  });
@@ -118861,7 +119517,7 @@ var init_engine = __esm({
118861
119517
  const config2 = await this.getExecutionConfig(profileId);
118862
119518
  const pollSeconds = Number(config2.client_protective_recovery_poll_seconds);
118863
119519
  if (!Number.isFinite(pollSeconds) || pollSeconds <= 0) return;
118864
- if (this._lastPendingProtectionRecoveryAtMs != null && Date.now() - this._lastPendingProtectionRecoveryAtMs < pollSeconds * 1e3) {
119520
+ if (this._lastPendingProtectionRecoveryAtMs != null && Date.now() - this._lastPendingProtectionRecoveryAtMs < pollSeconds * MS_PER_SECOND) {
118865
119521
  return;
118866
119522
  }
118867
119523
  this._lastPendingProtectionRecoveryAtMs = Date.now();
@@ -119115,7 +119771,7 @@ var init_engine = __esm({
119115
119771
  });
119116
119772
  return;
119117
119773
  }
119118
- this._emitLoopBoundaryTelemetry("client_execution_loop_early_return", "reason=analysis_in_flight retry_ms=5000", {
119774
+ this._emitLoopBoundaryTelemetry("client_execution_loop_early_return", `reason=analysis_in_flight retry_ms=${this._loopEarlyReturnRetryDelayMs}`, {
119119
119775
  reason: "analysis_in_flight",
119120
119776
  retry_ms: this._loopEarlyReturnRetryDelayMs
119121
119777
  });
@@ -119410,9 +120066,12 @@ var init_engine = __esm({
119410
120066
  const nowMs2 = Date.now();
119411
120067
  const windowOpensAtMs = error48.nextChangeAtMs != null ? this._periodicNextSlot(error48.nextChangeAtMs, true) ?? error48.nextChangeAtMs : null;
119412
120068
  aiSchedulePauseHasNext = windowOpensAtMs != null;
119413
- aiSchedulePauseMs = windowOpensAtMs != null ? Math.max(1e3, Math.min(windowOpensAtMs - nowMs2, 36e5)) : 6e4;
120069
+ aiSchedulePauseMs = windowOpensAtMs != null ? Math.max(
120070
+ CLIENT_RUNTIME_POLICY.ai_schedule_pause_min_milliseconds,
120071
+ Math.min(windowOpensAtMs - nowMs2, CLIENT_RUNTIME_POLICY.ai_schedule_pause_max_milliseconds)
120072
+ ) : CLIENT_RUNTIME_POLICY.ai_schedule_pause_unknown_milliseconds;
119414
120073
  if (runtimeMode === "trader" && this._loopIntervalMs != null) {
119415
- aiSchedulePauseMs = Math.min(aiSchedulePauseMs, Math.max(1e3, this._loopIntervalMs));
120074
+ aiSchedulePauseMs = Math.min(aiSchedulePauseMs, Math.max(CLIENT_RUNTIME_POLICY.ai_schedule_pause_min_milliseconds, this._loopIntervalMs));
119416
120075
  }
119417
120076
  this._nextRunAtMs = windowOpensAtMs;
119418
120077
  if (!aiSchedulePauseContinuation) {
@@ -119702,7 +120361,7 @@ var init_engine = __esm({
119702
120361
  await this._discardCycleOnContractMismatch("decision", decisionError);
119703
120362
  return;
119704
120363
  }
119705
- if (decisionError instanceof Error && decisionError.status === 409 && (decisionError.code === "snapshot_stale" || decisionError.message.startsWith("Runtime decision rejected by constraints:"))) {
120364
+ if (decisionError instanceof Error && decisionError.status === HTTP_STATUS.CONFLICT && (decisionError.code === "snapshot_stale" || decisionError.message.startsWith("Runtime decision rejected by constraints:"))) {
119706
120365
  Object.assign(decisionError, {
119707
120366
  runtimeInvocationAttempts: result.invocations?.map((attempt) => ({
119708
120367
  ...attempt,
@@ -120185,7 +120844,7 @@ var init_engine = __esm({
120185
120844
  } catch (error48) {
120186
120845
  const errorModelCalls = getCycleErrorModelCalls(error48);
120187
120846
  if (errorModelCalls.length > 0) cycleModelCalls = errorModelCalls;
120188
- const cycleElapsedSeconds = Math.max(0, (performance.now() - runStartedMonotonicMs) / 1e3);
120847
+ const cycleElapsedSeconds = Math.max(0, (performance.now() - runStartedMonotonicMs) / MS_PER_SECOND);
120189
120848
  cycleOutcome = "failed";
120190
120849
  cycleReason = cycleObservation.reason_code ?? "runtime_failed";
120191
120850
  if (isRuntimeAbortError(error48) || analysisAbortController.signal.aborted || this._isStopping || this._state === "stopped" || this._analysisRequestId !== requestId) {
@@ -120303,7 +120962,7 @@ var init_engine = __esm({
120303
120962
  }
120304
120963
  if (hasEventBoundProviderFailureEvidence(error48) && this._expectedExecutionMode === "server") {
120305
120964
  const backoffSeconds = Number((await this.getExecutionConfig(profileId).catch(() => null))?.provider_failure_backoff_seconds);
120306
- if (Number.isFinite(backoffSeconds) && backoffSeconds > 0) providerRetryDelayMs = backoffSeconds * 1e3;
120965
+ if (Number.isFinite(backoffSeconds) && backoffSeconds > 0) providerRetryDelayMs = backoffSeconds * MS_PER_SECOND;
120307
120966
  }
120308
120967
  if (hasEventBoundProviderFailureEvidence(error48)) {
120309
120968
  this.scheduleProviderFailureDiagnosticsTelemetry({
@@ -120357,7 +121016,7 @@ var init_engine = __esm({
120357
121016
  if (this._analysisRequestId === requestId) {
120358
121017
  this._analysisRequestId = null;
120359
121018
  this._analysisStartedAtMs = null;
120360
- if (this._expectedExecutionMode === "server" && this._state === "running") void this.sendHeartbeat();
121019
+ if (this._state === "running") void this.sendHeartbeat();
120361
121020
  }
120362
121021
  const silentEmptyAgentPoll = cycleOutcome === "skipped" && (cycleReason === "agent_instruction_poll_empty" || cycleReason === "ai_schedule_paused" || cycleReason === "ai_schedule_check") && !cycleStartEmitted;
120363
121022
  if (this._state === "running" && this._sessionId === sessionId) {
@@ -120516,7 +121175,7 @@ var init_engine = __esm({
120516
121175
  runtime_live_status: "active",
120517
121176
  runtime_running: true,
120518
121177
  runtime_scheduler_phase: this._getSchedulerPhase(),
120519
- runtime_loop_interval_seconds: this._loopIntervalMs == null ? null : Math.max(1, Math.round(this._loopIntervalMs / 1e3)),
121178
+ runtime_loop_interval_seconds: this._loopIntervalMs == null ? null : Math.max(1, Math.round(this._loopIntervalMs / MS_PER_SECOND)),
120520
121179
  runtime_last_run_at: this._lastRunAt,
120521
121180
  runtime_next_run_at: this._nextRunAtMs == null ? null : new Date(this._nextRunAtMs).toISOString(),
120522
121181
  runtime_next_run_at_ms: this._nextRunAtMs,
@@ -120540,7 +121199,7 @@ var init_engine = __esm({
120540
121199
  if (!profileId) {
120541
121200
  return;
120542
121201
  }
120543
- const delayMs = Math.max(0, options.delayMs ?? 2500);
121202
+ const delayMs = Math.max(0, options.delayMs ?? CLIENT_RUNTIME_POLICY.provider_failure_diagnostics_delay_milliseconds);
120544
121203
  globalThis.setTimeout(() => {
120545
121204
  const diagnostics = buildRuntimeErrorDiagnostics(options.reason);
120546
121205
  const healthProbe = diagnostics.healthProbe && typeof diagnostics.healthProbe === "object" ? diagnostics.healthProbe : null;
@@ -120628,7 +121287,7 @@ var init_engine = __esm({
120628
121287
  eventProvenance?.modelSource ?? providerSetup?.provider ?? options?.modelSource ?? ""
120629
121288
  ).trim().toLowerCase() || null;
120630
121289
  const sanitizedReason = getSanitizedRuntimeErrorMessage(reason) || "Unknown runtime error.";
120631
- const retrySeconds = this._loopIntervalMs == null ? null : Math.max(1, Math.round(this._loopIntervalMs / 1e3));
121290
+ const retrySeconds = this._loopIntervalMs == null ? null : Math.max(1, Math.round(this._loopIntervalMs / MS_PER_SECOND));
120632
121291
  const executionProjection = options?.executionReasonCode ? projectExecutionErrorContract({
120633
121292
  error: sanitizedReason,
120634
121293
  symbol: options.executionSymbol,
@@ -120799,7 +121458,7 @@ var init_engine = __esm({
120799
121458
  const heartbeatLifecycleGeneration = this._lifecycleGeneration;
120800
121459
  const heartbeatLastRunAt = this._lastRunAt;
120801
121460
  const heartbeatNextRunAt = !this._primaryAnalysisDisabled && typeof this._nextRunAtMs === "number" && Number.isFinite(this._nextRunAtMs) ? new Date(this._nextRunAtMs).toISOString() : null;
120802
- const heartbeatLoopIntervalSeconds = this._loopIntervalMs == null ? null : Math.max(1, Math.round(this._loopIntervalMs / 1e3));
121461
+ const heartbeatLoopIntervalSeconds = this._loopIntervalMs == null ? null : Math.max(1, Math.round(this._loopIntervalMs / MS_PER_SECOND));
120803
121462
  const heartbeatSchedulerPhase = this._getSchedulerPhase();
120804
121463
  const heartbeatAnalysisRunId = this._primaryAnalysisDisabled || !this._isAnalysisInFlight() ? null : this._analysisRequestId;
120805
121464
  const heartbeatIsAnalyzing = !this._primaryAnalysisDisabled && (this._isAnalysisInFlight() || this._startupPendingAnalysis && options?.confirmGrant !== true || this._isExecuting);
@@ -120820,9 +121479,11 @@ var init_engine = __esm({
120820
121479
  analysisRunId: heartbeatAnalysisRunId,
120821
121480
  isAnalyzing: heartbeatIsAnalyzing,
120822
121481
  isExecuting: heartbeatIsExecuting,
120823
- // Beats may arrive out of order: the server keeps a node bot's newest
120824
- // analyzing observation, so a cycle's end is never undone by its start.
120825
- ...this._expectedExecutionMode === "server" ? { analyzingObservedAtMs: heartbeatObservedAtMs } : {}
121482
+ // Beats may arrive out of order: the server keeps the owner's newest
121483
+ // analyzing observation (a node bot's status; a Client runtime's
121484
+ // handback to its home device), so a cycle's end is never undone by
121485
+ // its start.
121486
+ analyzingObservedAtMs: heartbeatObservedAtMs
120826
121487
  });
120827
121488
  if (Number(response.protective_actions_pending ?? 0) > 0) {
120828
121489
  notifyClientProtectiveActionsPending(heartbeatProfileId);
@@ -121040,7 +121701,7 @@ var init_engine = __esm({
121040
121701
  }
121041
121702
  this._killswitchIntervalId = setInterval(
121042
121703
  () => void this._runClientKillswitchCheck(),
121043
- Math.max(1e3, Math.round(pollIntervalSeconds * 1e3))
121704
+ Math.max(CLIENT_RUNTIME_POLICY.killswitch_timer_floor_milliseconds, Math.round(pollIntervalSeconds * MS_PER_SECOND))
121044
121705
  );
121045
121706
  }
121046
121707
  async _runClientKillswitchCheck() {
@@ -121081,7 +121742,7 @@ var init_engine = __esm({
121081
121742
  new DOMException("Client killswitch check timed out.", "TimeoutError")
121082
121743
  );
121083
121744
  reject(new Error("Client killswitch check timed out."));
121084
- }, Math.round(checkTimeoutSeconds * 1e3));
121745
+ }, Math.round(checkTimeoutSeconds * MS_PER_SECOND));
121085
121746
  })
121086
121747
  ]);
121087
121748
  if (controller.signal.aborted || this._state !== "running" || this._mode !== "trader" || this._profileId !== profileId || this._sessionId !== sessionId || this._deviceId !== deviceId) {
@@ -121189,9 +121850,9 @@ var init_engine = __esm({
121189
121850
  const activeExecutionLoop = this._executionLoopPromise;
121190
121851
  if (activeExecutionLoop) {
121191
121852
  const executionFenceTimeoutMs = Math.max(
121192
- 1e3,
121853
+ CLIENT_RUNTIME_POLICY.killswitch_timer_floor_milliseconds,
121193
121854
  Math.round(
121194
- Number(config2.client_runtime_killswitch_close_timeout_seconds) * 1e3
121855
+ Number(config2.client_runtime_killswitch_close_timeout_seconds) * MS_PER_SECOND
121195
121856
  )
121196
121857
  );
121197
121858
  let executionFenceTimeoutId = null;
@@ -121246,7 +121907,7 @@ var init_engine = __esm({
121246
121907
  () => refreshController.abort(
121247
121908
  new DOMException("Client killswitch position refresh timed out.", "TimeoutError")
121248
121909
  ),
121249
- Math.round(closeTimeoutSeconds * 1e3)
121910
+ Math.round(closeTimeoutSeconds * MS_PER_SECOND)
121250
121911
  );
121251
121912
  try {
121252
121913
  freshPositions = (await fetchBrowserAccountState2({
@@ -121366,22 +122027,66 @@ var init_engine = __esm({
121366
122027
  try {
121367
122028
  const persistedLease = getPersistedClientRuntimeServerLease(input.profileId);
121368
122029
  const runtimeLeaseToken = persistedLease?.runtimeSessionId === input.runtimeSessionId && persistedLease.deviceId === input.runtimeDeviceId && persistedLease.mode === "trader" ? persistedLease.runtimeLeaseToken : null;
121369
- const pollResponse = await pollCopyTradingRuntimeSource(Number(input.profileId), {
122030
+ const pollOptions = {
121370
122031
  runtimeLeaseToken: runtimeLeaseToken ?? void 0,
121371
122032
  schedulerInstanceId: this._instanceId,
121372
122033
  signal: input.signal
121373
- });
121374
- if (pollResponse.result.recorded_count > 0 || pollResponse.result.skipped_count > 0 || pollResponse.result.error_code) {
121375
- appendRuntimeDebugEvent({
121376
- label: "copy_trading_source_polled",
121377
- note: `observed=${pollResponse.result.observed_count} recorded=${pollResponse.result.recorded_count} skipped=${pollResponse.result.skipped_count} status=${pollResponse.result.latest_status || "none"} reason=${pollResponse.result.latest_skip_reason || pollResponse.result.error_code || "none"}`,
121378
- outcome: pollResponse.result.error_code ? "error" : "ok"
121379
- });
121380
- }
121381
- const copySourceUnavailable = pollResponse.result.error_code === "copy_trading_disabled" || pollResponse.result.error_code === "copy_trading_source_missing";
122034
+ };
122035
+ const logPoll = (response) => {
122036
+ if (response.result.recorded_count > 0 || response.result.skipped_count > 0 || response.result.error_code) {
122037
+ appendRuntimeDebugEvent({
122038
+ label: "copy_trading_source_polled",
122039
+ note: `observed=${response.result.observed_count} recorded=${response.result.recorded_count} skipped=${response.result.skipped_count} status=${response.result.latest_status || "none"} reason=${response.result.latest_skip_reason || response.result.error_code || "none"}`,
122040
+ outcome: response.result.error_code ? "error" : "ok"
122041
+ });
122042
+ }
122043
+ };
122044
+ let trustedWalletRead = null;
122045
+ const readTrustedWallet = () => {
122046
+ trustedWalletRead ??= getFreshPreferences(
122047
+ void 0,
122048
+ Number(input.profileId),
122049
+ input.signal,
122050
+ false,
122051
+ {
122052
+ runtimeLeaseToken: runtimeLeaseToken ?? void 0,
122053
+ schedulerInstanceId: this._instanceId
122054
+ }
122055
+ ).then((preferences) => String(
122056
+ preferences.preferences?.hyperliquid_wallet_address || ""
122057
+ ).trim() || null);
122058
+ return trustedWalletRead;
122059
+ };
122060
+ let pollResponse = await pollCopyTradingRuntimeSource(Number(input.profileId), pollOptions);
122061
+ logPoll(pollResponse);
121382
122062
  if (pollResponse.result.error_code === "self_copy_blocked") {
121383
122063
  return;
121384
122064
  }
122065
+ if (pollResponse.account_evidence_request) {
122066
+ if (this._windowHandoffRequested) {
122067
+ return;
122068
+ }
122069
+ const followUp = await this._sendClientCopyTradingAccountEvidence({
122070
+ profileId: input.profileId,
122071
+ request: pollResponse.account_evidence_request,
122072
+ // Unread preferences leave no trusted wallet: no evidence is read.
122073
+ trustedWalletAddress: await readTrustedWallet().catch((error48) => {
122074
+ if (input.signal.aborted) throw error48;
122075
+ return null;
122076
+ }),
122077
+ config: input.config,
122078
+ signal: input.signal,
122079
+ pollOptions
122080
+ });
122081
+ if (followUp) {
122082
+ pollResponse = followUp;
122083
+ logPoll(pollResponse);
122084
+ if (pollResponse.result.error_code === "self_copy_blocked") {
122085
+ return;
122086
+ }
122087
+ }
122088
+ }
122089
+ const copySourceUnavailable = pollResponse.result.error_code === "copy_trading_disabled" || pollResponse.result.error_code === "copy_trading_source_missing";
121385
122090
  const copyOrderActions = copySourceUnavailable ? [] : await getPendingClientCopyTradingOrderActions(Number(input.profileId), {
121386
122091
  runtimeLeaseToken: runtimeLeaseToken ?? void 0,
121387
122092
  schedulerInstanceId: this._instanceId,
@@ -121397,19 +122102,7 @@ var init_engine = __esm({
121397
122102
  ) : pendingCopyIntents;
121398
122103
  let expectedWalletAddress = null;
121399
122104
  if (copyOrderActions.length > 0 || copyIntents.length > 0) {
121400
- const referencePreferences = await getFreshPreferences(
121401
- void 0,
121402
- Number(input.profileId),
121403
- input.signal,
121404
- false,
121405
- {
121406
- runtimeLeaseToken: runtimeLeaseToken ?? void 0,
121407
- schedulerInstanceId: this._instanceId
121408
- }
121409
- );
121410
- expectedWalletAddress = String(
121411
- referencePreferences.preferences?.hyperliquid_wallet_address || ""
121412
- ).trim() || null;
122105
+ expectedWalletAddress = await readTrustedWallet();
121413
122106
  if (!expectedWalletAddress) {
121414
122107
  throw new Error(
121415
122108
  "runtime_wallet_assignment_mismatch: copy trading has no trusted wallet assignment"
@@ -121456,7 +122149,8 @@ var init_engine = __esm({
121456
122149
  order_id: actionResult.destinationOrderId,
121457
122150
  order_state: actionResult.destinationOrderState,
121458
122151
  order_member_results: actionResult.orderMemberResults,
121459
- error_message: actionResult.status === "executed" ? null : actionResult.message
122152
+ error_message: actionResult.status === "executed" ? null : actionResult.message,
122153
+ ...actionResult.orderStatusEvidence ? { order_status_evidence: orderStatusEvidenceForAck(actionResult.orderStatusEvidence) } : {}
121460
122154
  },
121461
122155
  {
121462
122156
  runtimeLeaseToken: runtimeLeaseToken ?? void 0,
@@ -121540,6 +122234,55 @@ var init_engine = __esm({
121540
122234
  });
121541
122235
  }
121542
122236
  }
122237
+ /**
122238
+ * Read the follower account evidence a copy poll asked for and send it on
122239
+ * one follow-up poll. Fails closed: when any read fails or the wallet is not
122240
+ * the trusted one, nothing is sent and the check-in continues on the first
122241
+ * poll (null). A report the server cannot use still answers the poll, with
122242
+ * its reason in account_evidence_status, which is logged here.
122243
+ */
122244
+ async _sendClientCopyTradingAccountEvidence(input) {
122245
+ const requestId = String(input.request.request_id ?? "").trim().slice(0, 80) || "none";
122246
+ const evidence = await readClientCopyTradingAccountEvidence({
122247
+ request: input.request,
122248
+ trustedWalletAddress: input.trustedWalletAddress,
122249
+ config: input.config,
122250
+ signal: input.signal
122251
+ });
122252
+ if (!evidence.ok) {
122253
+ appendRuntimeDebugEvent({
122254
+ label: "copy_trading_account_evidence_skipped",
122255
+ note: `profile_id=${input.profileId} request_id=${requestId} reason=${evidence.reason}`,
122256
+ outcome: "error"
122257
+ });
122258
+ return null;
122259
+ }
122260
+ try {
122261
+ const response = await pollCopyTradingRuntimeSource(Number(input.profileId), {
122262
+ ...input.pollOptions,
122263
+ accountEvidence: accountEvidenceForUpload(evidence.read)
122264
+ });
122265
+ const status = response.account_evidence_status ?? null;
122266
+ if (status !== "applied") {
122267
+ appendRuntimeDebugEvent({
122268
+ label: "copy_trading_account_evidence_rejected",
122269
+ note: `profile_id=${input.profileId} request_id=${requestId} reason=${String(status ?? "missing").slice(0, 80)}`,
122270
+ outcome: "error"
122271
+ });
122272
+ }
122273
+ return response;
122274
+ } catch (error48) {
122275
+ if (input.signal.aborted) {
122276
+ throw error48;
122277
+ }
122278
+ appendRuntimeDebugEvent({
122279
+ label: "copy_trading_account_evidence_rejected",
122280
+ note: `profile_id=${input.profileId} request_id=${requestId} error=${getSanitizedRuntimeErrorMessage(error48) || "unknown"}`,
122281
+ outcome: "error"
122282
+ });
122283
+ return null;
122284
+ }
122285
+ }
121543
122286
  _resetRuntimeState(options) {
121544
122287
  this._clearExecutionLoopTimer();
121545
122288
  this._clearClientKillswitchMonitor();
@@ -121952,6 +122695,99 @@ var init_reconcile = __esm({
121952
122695
  }
121953
122696
  });
121954
122697
 
122698
+ // lib/runtime/host/local-ai-preflight.ts
122699
+ var normalizeModelSource, isLocalModelSource2, getLocalAiBaseUrlFromPreferences, canReachLocalAiEndpoint;
122700
+ var init_local_ai_preflight = __esm({
122701
+ "lib/runtime/host/local-ai-preflight.ts"() {
122702
+ "use strict";
122703
+ init_define_VTX_EXO_POLICY();
122704
+ init_define_VTX_GROK_POLICY();
122705
+ init_define_VTX_PI_MODEL_POLICY();
122706
+ init_api2();
122707
+ init_local_ai();
122708
+ init_vault();
122709
+ normalizeModelSource = (value) => String(value ?? "").trim().toLowerCase();
122710
+ isLocalModelSource2 = (value) => {
122711
+ const normalized = normalizeModelSource(value);
122712
+ return normalized === "local" || normalized === "localai" || normalized === "local ai" || normalized === "local-ai" || normalized === "local_ai";
122713
+ };
122714
+ getLocalAiBaseUrlFromPreferences = (preferences) => {
122715
+ const record5 = preferences && typeof preferences === "object" && !Array.isArray(preferences) ? preferences : {};
122716
+ const direct = typeof record5.local_ai_base_url === "string" ? record5.local_ai_base_url.trim() : "";
122717
+ if (direct) {
122718
+ return direct;
122719
+ }
122720
+ const localAi = record5.local_ai && typeof record5.local_ai === "object" && !Array.isArray(record5.local_ai) ? record5.local_ai : null;
122721
+ const remembered = Array.isArray(localAi?.remembered_endpoints) ? localAi.remembered_endpoints : [];
122722
+ for (const endpoint of remembered) {
122723
+ if (!endpoint || typeof endpoint !== "object" || Array.isArray(endpoint)) {
122724
+ continue;
122725
+ }
122726
+ const baseUrl = typeof endpoint.baseUrl === "string" ? String(endpoint.baseUrl).trim() : "";
122727
+ if (baseUrl) {
122728
+ return baseUrl;
122729
+ }
122730
+ }
122731
+ return null;
122732
+ };
122733
+ canReachLocalAiEndpoint = async (preferences, profileId, timeoutMs, signal) => {
122734
+ const baseUrl = getLocalAiBaseUrlFromPreferences(preferences);
122735
+ if (!baseUrl) {
122736
+ return { ok: false, detail: "local_ai_endpoint_missing" };
122737
+ }
122738
+ let rawServerType = resolveLocalAiServerTypeInput(preferences);
122739
+ if (!rawServerType) {
122740
+ try {
122741
+ const secrets = await ClientVault.getSecrets(String(profileId));
122742
+ rawServerType = resolveLocalAiServerTypeInput(preferences, secrets?.localAi?.serverType);
122743
+ } catch {
122744
+ return { ok: false, detail: "local_ai_settings_unavailable" };
122745
+ }
122746
+ }
122747
+ const serverType = rawServerType ? normalizeLocalAiServerType(rawServerType) : "openai-compatible";
122748
+ if (!serverType) {
122749
+ return { ok: false, detail: "local_ai_reconnect_required" };
122750
+ }
122751
+ const endpoint = buildLocalAiModelsEndpointForServerType(baseUrl, serverType);
122752
+ if (!endpoint) {
122753
+ return { ok: false, detail: "local_ai_endpoint_missing" };
122754
+ }
122755
+ const headers = { Accept: "application/json" };
122756
+ try {
122757
+ const secret = await getLocalAiEndpointSecret(baseUrl, profileId, signal);
122758
+ const apiKey = typeof secret?.api_key === "string" ? secret.api_key.trim() : "";
122759
+ if (secret?.found && apiKey) {
122760
+ headers.Authorization = `Bearer ${apiKey}`;
122761
+ }
122762
+ } catch {
122763
+ }
122764
+ const controller = new AbortController();
122765
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
122766
+ const onAbort = () => controller.abort();
122767
+ signal?.addEventListener("abort", onAbort, { once: true });
122768
+ try {
122769
+ const response = await fetch(endpoint, {
122770
+ method: "GET",
122771
+ headers,
122772
+ signal: controller.signal
122773
+ });
122774
+ return {
122775
+ ok: response.ok,
122776
+ detail: response.ok ? "ok" : `status_${response.status}`
122777
+ };
122778
+ } catch (error48) {
122779
+ return {
122780
+ ok: false,
122781
+ detail: error48 instanceof Error && error48.name === "AbortError" ? "timeout" : "fetch_failed"
122782
+ };
122783
+ } finally {
122784
+ clearTimeout(timeout);
122785
+ signal?.removeEventListener("abort", onAbort);
122786
+ }
122787
+ };
122788
+ }
122789
+ });
122790
+
121955
122791
  // lib/agent-core/headless-runtime.ts
121956
122792
  import { randomUUID as randomUUID15 } from "node:crypto";
121957
122793
  import { setTimeout as sleep3 } from "node:timers/promises";
@@ -122195,6 +123031,11 @@ async function runHeadlessRuntime(options) {
122195
123031
  if (stored && stored.runtimeSessionId !== identity2.sessionId) return;
122196
123032
  await clearRuntimeState(options.statePath);
122197
123033
  };
123034
+ const readOwnStatus = async (signal = stopController.signal) => (await getClientRuntimeStatuses(
123035
+ [options.profileId],
123036
+ signal,
123037
+ { runtimeViewer: { deviceId: identity2.deviceId, sessionId: identity2.sessionId } }
123038
+ )).statuses?.[String(options.profileId)] ?? null;
122198
123039
  const stopRuntime = async (reason) => {
122199
123040
  if (engine.active) await engine.stop({ skipRemote: true, reason });
122200
123041
  try {
@@ -122210,6 +123051,8 @@ async function runHeadlessRuntime(options) {
122210
123051
  requestTimeoutMs: options.stopRequestTimeoutMs ?? STOP_REQUEST_TIMEOUT_MS
122211
123052
  });
122212
123053
  } catch (error48) {
123054
+ const backupRuns = await readOwnStatus(AbortSignal.timeout(options.stopRequestTimeoutMs ?? STOP_REQUEST_TIMEOUT_MS)).then((status) => status?.server_backup?.active === true, () => false);
123055
+ if (backupRuns) return;
122213
123056
  const detail = error48 instanceof Error ? error48.message : String(error48);
122214
123057
  throw new Error(`VTX could not stop this profile's runtime on the server (${detail}); it may still be set to run.`);
122215
123058
  }
@@ -122229,6 +123072,120 @@ async function runHeadlessRuntime(options) {
122229
123072
  }
122230
123073
  if (kind === "explicit") await clearOwnState().catch(() => void 0);
122231
123074
  };
123075
+ const readyToTakeBack = async (status) => {
123076
+ const profileId = String(options.profileId);
123077
+ const desiredMode = String(status.desired_runtime_mode || "").trim().toLowerCase();
123078
+ if (desiredMode && desiredMode !== identity2.mode) return false;
123079
+ if (identity2.mode === "trader" && isClientRuntimeKillswitchBlocked(profileId)) return false;
123080
+ try {
123081
+ const [config2, preferences] = await Promise.all([
123082
+ getLLMConfig(void 0, options.profileId, stopController.signal),
123083
+ getPreferences(void 0, options.profileId, stopController.signal)
123084
+ ]);
123085
+ if (config2.agent_headless_client_runtime_enabled !== true) return false;
123086
+ const prefs = preferences?.preferences;
123087
+ if (isLocalModelSource2(prefs?.preferred_model_source)) {
123088
+ return (await canReachLocalAiEndpoint(prefs, options.profileId, LOCAL_AI_PREFLIGHT_TIMEOUT_MS, stopController.signal)).ok;
123089
+ }
123090
+ return true;
123091
+ } catch {
123092
+ return false;
123093
+ }
123094
+ };
123095
+ const readWaitStatus = async () => {
123096
+ try {
123097
+ const response = await getClientRuntimeStatuses(
123098
+ [options.profileId],
123099
+ stopController.signal,
123100
+ { runtimeViewer: { deviceId: identity2.deviceId, sessionId: identity2.sessionId } }
123101
+ );
123102
+ const status = response.statuses?.[String(options.profileId)];
123103
+ if (status) return { status };
123104
+ const error48 = String(response.errors?.[String(options.profileId)] ?? "");
123105
+ return !error48 || /temporarily unavailable/iu.test(error48) ? "retry" : "ended";
123106
+ } catch (error48) {
123107
+ return classifyReconcileRequestError(error48) === "transient" ? "retry" : { refused: error48 };
123108
+ }
123109
+ };
123110
+ const waitForServerBackup = async () => {
123111
+ if (options.once || stopController.signal.aborted) return "not_backup";
123112
+ let status = null;
123113
+ for (let attempt = 0; ; attempt += 1) {
123114
+ const read = await readWaitStatus();
123115
+ if (read === "ended" || typeof read === "object" && "refused" in read) return "not_backup";
123116
+ status = read === "retry" ? null : read.status;
123117
+ if (status || attempt >= BACKUP_FIRST_READ_RETRY_MS.length || stopController.signal.aborted) break;
123118
+ try {
123119
+ await sleep3(BACKUP_FIRST_READ_RETRY_MS[attempt], void 0, { signal: stopController.signal });
123120
+ } catch {
123121
+ break;
123122
+ }
123123
+ }
123124
+ if (!status?.server_backup?.active) return "not_backup";
123125
+ const stored = await readRuntimeState(options.statePath).catch(() => null);
123126
+ const ownDevices = new Set([identity2.deviceId, stored?.deviceId].filter(Boolean).map(String));
123127
+ let offered = false;
123128
+ const stopped = new Promise((resolve14) => {
123129
+ if (stopController.signal.aborted) resolve14(false);
123130
+ else stopController.signal.addEventListener("abort", () => resolve14(false), { once: true });
123131
+ });
123132
+ const withdraw = async () => {
123133
+ if (!offered) return;
123134
+ await reportServerBackupReadiness(
123135
+ options.profileId,
123136
+ false,
123137
+ identity2.deviceId,
123138
+ AbortSignal.timeout(options.stopRequestTimeoutMs ?? STOP_REQUEST_TIMEOUT_MS)
123139
+ ).catch(() => void 0);
123140
+ };
123141
+ process.stderr.write("VTX CLI: Server Mode Backup runs this profile; waiting to take it back.\n");
123142
+ for (; ; ) {
123143
+ if (status) {
123144
+ const backup = status.server_backup;
123145
+ if (!backup?.active) {
123146
+ return String(status.execution_mode || "").trim().toLowerCase() === "client" ? "returned" : "not_backup";
123147
+ }
123148
+ if (backup.enabled && ownDevices.has(String(backup.return_device_id || "").trim())) {
123149
+ const ready = await Promise.race([readyToTakeBack(status), stopped]);
123150
+ if (!stopController.signal.aborted) {
123151
+ offered = true;
123152
+ await reportServerBackupReadiness(options.profileId, ready, identity2.deviceId, stopController.signal).catch(() => void 0);
123153
+ }
123154
+ }
123155
+ }
123156
+ if (options.shouldYieldForUpdate && await options.shouldYieldForUpdate()) {
123157
+ await withdraw();
123158
+ return "yielded_for_update";
123159
+ }
123160
+ try {
123161
+ await sleep3(options.serverBackupWaitMs ?? BACKUP_WAIT_TICK_MS, void 0, { signal: stopController.signal });
123162
+ } catch {
123163
+ await withdraw();
123164
+ return "stopped";
123165
+ }
123166
+ const read = await readWaitStatus();
123167
+ if (read === "ended") {
123168
+ await withdraw();
123169
+ return "not_backup";
123170
+ }
123171
+ if (typeof read === "object" && "refused" in read) {
123172
+ await withdraw();
123173
+ throw read.refused;
123174
+ }
123175
+ status = read === "retry" ? null : read.status;
123176
+ if (stopController.signal.aborted) {
123177
+ await withdraw();
123178
+ return "stopped";
123179
+ }
123180
+ }
123181
+ };
123182
+ const waitOutServerBackup = async () => {
123183
+ const waited = await waitForServerBackup();
123184
+ if (waited === "returned") return "resume";
123185
+ if (waited === "stopped") return result("stopped");
123186
+ if (waited === "yielded_for_update") return result("yielded_for_update");
123187
+ return null;
123188
+ };
122232
123189
  let handoffLease = resume?.handoffLease ?? null;
122233
123190
  const start = async (kind) => {
122234
123191
  attached = false;
@@ -122275,11 +123232,21 @@ async function runHeadlessRuntime(options) {
122275
123232
  await clearOwnState();
122276
123233
  throw error48;
122277
123234
  }
122278
- if (!stopController.signal.aborted) throw error48;
122279
- await stopRuntime("agent_cli:stop");
122280
- return result("stopped");
123235
+ if (!stopController.signal.aborted) {
123236
+ const waited = await waitOutServerBackup();
123237
+ if (waited === null && !stopController.signal.aborted) throw error48;
123238
+ if (waited !== null && waited !== "resume") return waited;
123239
+ if (waited === "resume") push({ kind: "resume", immediate: true });
123240
+ else {
123241
+ await stopRuntime("agent_cli:stop");
123242
+ return result("stopped");
123243
+ }
123244
+ } else {
123245
+ await stopRuntime("agent_cli:stop");
123246
+ return result("stopped");
123247
+ }
122281
123248
  }
122282
- stopProtection = firstAttached();
123249
+ if (attached) stopProtection = firstAttached();
122283
123250
  }
122284
123251
  let resumesWithoutCycle = 0;
122285
123252
  let lastResumeError = null;
@@ -122312,6 +123279,18 @@ async function runHeadlessRuntime(options) {
122312
123279
  if (event.kind === "engine_stopped") {
122313
123280
  if (stopController.signal.aborted || !engineEnded()) continue;
122314
123281
  if (snapshot.ownershipLossReason) {
123282
+ const waited = await waitOutServerBackup();
123283
+ if (waited === "resume") {
123284
+ resumesWithoutCycle = 0;
123285
+ lastResumeError = null;
123286
+ push({ kind: "resume", immediate: true });
123287
+ continue;
123288
+ }
123289
+ if (waited) return waited;
123290
+ if (stopController.signal.aborted) {
123291
+ await stopRuntime("agent_cli:stop");
123292
+ return result("stopped");
123293
+ }
122315
123294
  await clearOwnState();
122316
123295
  throw new Error(
122317
123296
  `Client runtime ownership moved (${snapshot.ownershipLossReason})${snapshot.lastError ? `: ${snapshot.lastError}` : ""}.`
@@ -122352,6 +123331,18 @@ async function runHeadlessRuntime(options) {
122352
123331
  await stopRuntime("agent_cli:stop");
122353
123332
  return result("stopped");
122354
123333
  }
123334
+ const waited = await waitOutServerBackup();
123335
+ if (waited !== null) {
123336
+ if (waited !== "resume") return waited;
123337
+ resumesWithoutCycle = 0;
123338
+ lastResumeError = null;
123339
+ push({ kind: "resume", immediate: true });
123340
+ continue;
123341
+ }
123342
+ if (stopController.signal.aborted) {
123343
+ await stopRuntime("agent_cli:stop");
123344
+ return result("stopped");
123345
+ }
122355
123346
  if (classifyReconcileRequestError(error48) !== "transient") throw error48;
122356
123347
  lastResumeError = error48;
122357
123348
  push({ kind: "resume", immediate: false });
@@ -122372,7 +123363,7 @@ async function runHeadlessRuntime(options) {
122372
123363
  }
122373
123364
  }
122374
123365
  }
122375
- var HeadlessRuntimeTakeoverRequiredError, HEADLESS_RUNTIME_AGENT_SCOPES, DEFAULT_MAX_CLAIM_WAITS, STOP_REQUEST_TIMEOUT_MS, PROTECTION_IDLE_RECHECK_MS, PROTECTION_RETRY_MS, MAX_RESUMES_WITHOUT_A_CYCLE, RESUME_BACKOFF_MS;
123366
+ var HeadlessRuntimeTakeoverRequiredError, HEADLESS_RUNTIME_AGENT_SCOPES, DEFAULT_MAX_CLAIM_WAITS, STOP_REQUEST_TIMEOUT_MS, PROTECTION_IDLE_RECHECK_MS, PROTECTION_RETRY_MS, MAX_RESUMES_WITHOUT_A_CYCLE, RESUME_BACKOFF_MS, BACKUP_WAIT_TICK_MS, LOCAL_AI_PREFLIGHT_TIMEOUT_MS, BACKUP_FIRST_READ_RETRY_MS;
122376
123367
  var init_headless_runtime = __esm({
122377
123368
  "lib/agent-core/headless-runtime.ts"() {
122378
123369
  "use strict";
@@ -122391,6 +123382,7 @@ var init_headless_runtime = __esm({
122391
123382
  init_engine();
122392
123383
  init_server_runtime_lease();
122393
123384
  init_reconcile();
123385
+ init_local_ai_preflight();
122394
123386
  HeadlessRuntimeTakeoverRequiredError = class extends Error {
122395
123387
  constructor(response) {
122396
123388
  const owner2 = objectOrNull2(response.owner);
@@ -122409,9 +123401,12 @@ var init_headless_runtime = __esm({
122409
123401
  DEFAULT_MAX_CLAIM_WAITS = 10;
122410
123402
  STOP_REQUEST_TIMEOUT_MS = 1e4;
122411
123403
  PROTECTION_IDLE_RECHECK_MS = runtime_policy_generated_default2.trading.engine.client_runtime.protective_actions.idle_recheck_seconds * 1e3;
122412
- PROTECTION_RETRY_MS = 15e3;
123404
+ PROTECTION_RETRY_MS = runtime_policy_generated_default2.trading.engine.client_runtime.protective_actions.retry_delay_seconds * 1e3;
122413
123405
  MAX_RESUMES_WITHOUT_A_CYCLE = 5;
122414
123406
  RESUME_BACKOFF_MS = [1e3, 5e3, 15e3, 3e4, 6e4];
123407
+ BACKUP_WAIT_TICK_MS = runtime_policy_generated_default2.trading.engine.client_runtime.reconcile.tick_interval_seconds * 1e3;
123408
+ LOCAL_AI_PREFLIGHT_TIMEOUT_MS = runtime_policy_generated_default2.trading.engine.client_runtime.reconcile.local_ai_preflight_timeout_ms;
123409
+ BACKUP_FIRST_READ_RETRY_MS = [1e3, 5e3];
122415
123410
  }
122416
123411
  });
122417
123412