@simplexai/localmodels-darwin-x64 0.1.0-dev.63 → 0.1.0-dev.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +140 -130
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +2 -2
  5. package/modules/localmodels/app.py +15 -2
  6. package/modules/localmodels/approval.py +5 -3
  7. package/modules/localmodels/bifrost_checks.py +2 -1
  8. package/modules/localmodels/catalog.json +36 -0
  9. package/modules/localmodels/catalog.py +28 -5
  10. package/modules/localmodels/catalog_recipes.py +40 -1
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/context_policy.py +7 -2
  13. package/modules/localmodels/custom_probe.py +5 -5
  14. package/modules/localmodels/debug_mode.py +85 -103
  15. package/modules/localmodels/deploy.py +129 -18
  16. package/modules/localmodels/deployment_lifecycle.py +167 -0
  17. package/modules/localmodels/download-mirrors.json +126 -6
  18. package/modules/localmodels/draft_spec.py +164 -0
  19. package/modules/localmodels/engine_adapters/__init__.py +4 -0
  20. package/modules/localmodels/engine_adapters/auxiliary.py +27 -0
  21. package/modules/localmodels/engine_adapters/base.py +40 -0
  22. package/modules/localmodels/engine_adapters/strata_poly.py +57 -0
  23. package/modules/localmodels/engine_adapters/suite_plan.py +394 -0
  24. package/modules/localmodels/engines-prism-b12178-03ec600.json +7 -7
  25. package/modules/localmodels/gateway.py +124 -13
  26. package/modules/localmodels/gateway_accept.py +1 -6
  27. package/modules/localmodels/gateway_cli.py +13 -24
  28. package/modules/localmodels/gateway_ops.py +185 -0
  29. package/modules/localmodels/gateway_server.py +3 -2
  30. package/modules/localmodels/harness.py +13 -16
  31. package/modules/localmodels/harness_core.py +4 -9
  32. package/modules/localmodels/harness_gateway.py +4 -3
  33. package/modules/localmodels/hosts.py +22 -34
  34. package/modules/localmodels/install.py +15 -0
  35. package/modules/localmodels/library_convert.py +5 -11
  36. package/modules/localmodels/library_custom.py +6 -6
  37. package/modules/localmodels/library_elastic.py +24 -127
  38. package/modules/localmodels/library_jobs.py +14 -5
  39. package/modules/localmodels/library_order.py +4 -3
  40. package/modules/localmodels/library_poly.py +5 -4
  41. package/modules/localmodels/library_pricing.py +80 -255
  42. package/modules/localmodels/library_serve.py +13 -14
  43. package/modules/localmodels/library_smoke.py +8 -1
  44. package/modules/localmodels/library_status.py +16 -16
  45. package/modules/localmodels/llm_rank.py +1 -1
  46. package/modules/localmodels/magpie_legacy.py +160 -0
  47. package/modules/localmodels/magpie_setup.py +6 -1
  48. package/modules/localmodels/memcalc_cli.py +2 -2
  49. package/modules/localmodels/pi_profile.py +3 -7
  50. package/modules/localmodels/plan_envelope.py +1 -1
  51. package/modules/localmodels/planning/__init__.py +3 -0
  52. package/modules/localmodels/{budget.py → planning/budget.py} +48 -30
  53. package/modules/localmodels/{stack_llm_ram.py → planning/llm_ram.py} +11 -1
  54. package/modules/localmodels/{memcalc_load.py → planning/memcalc_load.py} +1 -1
  55. package/modules/localmodels/planning/memory_pools.py +403 -0
  56. package/modules/localmodels/{sizecalc.py → planning/sizecalc.py} +1 -1
  57. package/modules/localmodels/recommend.py +1 -1
  58. package/modules/localmodels/recommend_cli.py +3 -4
  59. package/modules/localmodels/residency_host.py +1 -1
  60. package/modules/localmodels/service_control.py +4 -4
  61. package/modules/localmodels/service_deployment.py +3 -2
  62. package/modules/localmodels/service_wiring.py +17 -19
  63. package/modules/localmodels/setup_inspection.py +1 -1
  64. package/modules/localmodels/setup_inspection_harness.py +1 -1
  65. package/modules/localmodels/setup_upgrade.py +3 -12
  66. package/modules/localmodels/sizecalc_cli.py +10 -2
  67. package/modules/localmodels/speech_admission.py +1 -1
  68. package/modules/localmodels/speech_jobs.py +2 -1
  69. package/modules/localmodels/speech_model.py +2 -0
  70. package/modules/localmodels/speech_server.py +130 -9
  71. package/modules/localmodels/speech_state.py +11 -0
  72. package/modules/localmodels/speech_worker_sensevoice.py +38 -0
  73. package/modules/localmodels/speech_workers.py +5 -1
  74. package/modules/localmodels/stack.py +4 -9
  75. package/modules/localmodels/stack_arena.py +2 -2
  76. package/modules/localmodels/stack_auto.py +5 -5
  77. package/modules/localmodels/stack_aux_gpu.py +5 -3
  78. package/modules/localmodels/stack_binding.py +24 -143
  79. package/modules/localmodels/stack_capacity.py +1 -1
  80. package/modules/localmodels/stack_card.py +3 -3
  81. package/modules/localmodels/stack_cleanup.py +6 -5
  82. package/modules/localmodels/stack_client_settings.py +9 -2
  83. package/modules/localmodels/stack_compose.py +43 -6
  84. package/modules/localmodels/stack_console.py +2 -2
  85. package/modules/localmodels/stack_debug.py +1 -1
  86. package/modules/localmodels/stack_decision.py +1 -1
  87. package/modules/localmodels/stack_doctor.py +10 -7
  88. package/modules/localmodels/stack_down.py +3 -3
  89. package/modules/localmodels/stack_gpu_memory.py +1 -1
  90. package/modules/localmodels/stack_hardware.py +3 -3
  91. package/modules/localmodels/stack_hardware_text.py +1 -1
  92. package/modules/localmodels/stack_ledger.py +2 -1
  93. package/modules/localmodels/stack_lifecycle.py +7 -7
  94. package/modules/localmodels/stack_mcp.py +1 -1
  95. package/modules/localmodels/stack_memory.py +4 -4
  96. package/modules/localmodels/stack_mlx.py +1 -1
  97. package/modules/localmodels/stack_plan.py +18 -13
  98. package/modules/localmodels/stack_ports.py +2 -2
  99. package/modules/localmodels/stack_preflight.py +4 -3
  100. package/modules/localmodels/stack_remove.py +13 -6
  101. package/modules/localmodels/stack_review.py +3 -5
  102. package/modules/localmodels/stack_rollback.py +1 -1
  103. package/modules/localmodels/stack_route.py +5 -4
  104. package/modules/localmodels/stack_run.py +16 -0
  105. package/modules/localmodels/stack_suite.py +14 -6
  106. package/modules/localmodels/stack_summary.py +1 -1
  107. package/modules/localmodels/stack_try.py +10 -14
  108. package/modules/localmodels/stack_up.py +25 -39
  109. package/modules/localmodels/stack_update.py +2 -1
  110. package/modules/localmodels/stack_verify.py +4 -30
  111. package/modules/localmodels/stack_view.py +6 -4
  112. package/modules/localmodels/stack_view_apply.py +2 -2
  113. package/modules/localmodels/stack_view_llm.py +12 -7
  114. package/modules/localmodels/stack_view_text.py +2 -6
  115. package/modules/localmodels/stack_view_tick.py +2 -2
  116. package/modules/localmodels/stack_view_words.py +5 -2
  117. package/modules/localmodels/stack_warm.py +7 -4
  118. package/modules/localmodels/stack_whatif.py +1 -1
  119. package/modules/localmodels/suite.py +6 -334
  120. package/modules/localmodels/tui_views.py +28 -7
  121. package/modules/localmodels/web/index.html +595 -226
  122. package/modules/localmodels/web/sizecalc/app.js +34 -40
  123. package/modules/localmodels/web/sizecalc/calc.js +3 -3
  124. package/modules/localmodels/web/sizecalc/page.html +4 -3
  125. package/modules/localmodels/web/view/fleet.html +18 -3
  126. package/modules/localmodels/web/view/fleet.js +135 -14
  127. package/modules/localmodels/web/view/i18n.js +4 -0
  128. package/modules/localmodels/web/view/index.html +16 -0
  129. package/modules/localmodels/web/view/nav.js +49 -0
  130. package/modules/localmodels/web/view/theme.js +1 -1
  131. package/modules/localmodels/web/view/view.css +51 -15
  132. package/modules/localmodels/web/view/view.js +22 -4
  133. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/METADATA +1 -1
  134. package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/RECORD +137 -127
  135. package/package.json +1 -1
  136. package/tool.json +1 -1
  137. package/modules/localmodels/library_vram.py +0 -123
  138. /package/modules/localmodels/{memcalc.py → planning/memcalc.py} +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/WHEEL +0 -0
  140. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/entry_points.txt +0 -0
  141. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/NOTICE +0 -0
  142. /package/modules/{simplex_localmodels-0.1.0.dev63.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -5,20 +5,11 @@ from __future__ import annotations
5
5
  from collections.abc import Callable
6
6
  from typing import TypedDict
7
7
 
8
- from localmodels import (
9
- budget,
10
- catalog,
11
- catalog_recipes,
12
- harness,
13
- library_vram,
14
- llm_rank,
15
- stack,
16
- stack_review,
17
- win_probe,
18
- )
8
+ from localmodels import catalog, catalog_recipes, harness, llm_rank, stack, stack_review, win_probe
19
9
  from localmodels.contracts import decode
20
10
  from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
21
11
  from localmodels.plan_envelope import PlanError
12
+ from localmodels.planning import budget, memory_pools
22
13
  from localmodels.probe import HostFacts
23
14
  from localmodels.setup_text import Lang, text
24
15
  from localmodels.stack_plan import StackError, StackOptions, StackPlan, deployments
@@ -150,6 +141,6 @@ def upgrade_hint(
150
141
  return None
151
142
  hint: StackUpgrade = {"plan": roomy_plan, "summary": summary, "reasons": reasons}
152
143
  if any(r["code"] == "gpu-memory-required" for r in reasons):
153
- if apps := library_vram.closeable_gpu_apps(facts):
144
+ if apps := memory_pools.closeable_gpu_apps(facts):
154
145
  hint["gpuApps"] = apps
155
146
  return hint
@@ -9,8 +9,16 @@ from collections.abc import Mapping
9
9
  from pathlib import Path
10
10
  from typing import Any
11
11
 
12
- from localmodels import catalog, cli_help, sizecalc
13
- from localmodels.memcalc import GIB, KIB, MemcalcError, parse_params, parse_size, parse_tokens
12
+ from localmodels import catalog, cli_help
13
+ from localmodels.planning import sizecalc
14
+ from localmodels.planning.memcalc import (
15
+ GIB,
16
+ KIB,
17
+ MemcalcError,
18
+ parse_params,
19
+ parse_size,
20
+ parse_tokens,
21
+ )
14
22
 
15
23
  PAGE_DIR = Path(__file__).parent / "web" / "sizecalc"
16
24
  _VERDICT = {"fits": "fits", "offload": "fits with system RAM", "no": "-"}
@@ -21,7 +21,6 @@ from pathlib import Path
21
21
 
22
22
  from localmodels import (
23
23
  app,
24
- budget,
25
24
  engines,
26
25
  hosts,
27
26
  library_state,
@@ -30,6 +29,7 @@ from localmodels import (
30
29
  speech_catalog,
31
30
  speech_state,
32
31
  )
32
+ from localmodels.planning import budget
33
33
  from localmodels.probe import GPU, HostFacts
34
34
  from localmodels.speech_catalog import SpeechModelSpec
35
35
  from localmodels.speech_model import EffectiveDevice, FallbackReason, RequestedDevice
@@ -21,6 +21,7 @@ from localmodels import (
21
21
  app,
22
22
  debug_mode,
23
23
  deploy,
24
+ deployment_lifecycle,
24
25
  engines,
25
26
  hosts,
26
27
  library_jobs,
@@ -670,7 +671,7 @@ def _engine_in_use_elsewhere(
670
671
  if other and os.path.realpath(os.path.expanduser(other)) == target:
671
672
  return True
672
673
  for owned in hosts.load_owned()["deployments"].values():
673
- if not owned.get("removed"):
674
+ if deployment_lifecycle.holds_service(owned):
674
675
  for path in owned.get("files") or ():
675
676
  if os.path.realpath(os.path.expanduser(path)).startswith(target):
676
677
  return True
@@ -188,6 +188,7 @@ class SpeechRuntime(TypedDict):
188
188
  keep_loaded_seconds: int
189
189
  idle_remaining_seconds: int | None
190
190
  active_sessions: int
191
+ error: SpeechModelError | None
191
192
 
192
193
 
193
194
  class SpeechModelRow(TypedDict):
@@ -268,6 +269,7 @@ def stopped_runtime(config: SpeechConfig) -> SpeechRuntime:
268
269
  "keep_loaded_seconds": config["keep_loaded_seconds"],
269
270
  "idle_remaining_seconds": None,
270
271
  "active_sessions": 0,
272
+ "error": None,
271
273
  }
272
274
 
273
275
 
@@ -21,10 +21,12 @@ import json
21
21
  import math
22
22
  import os
23
23
  import signal
24
+ import subprocess
24
25
  import threading
25
26
  import time
26
27
  import urllib.parse
27
28
  from collections.abc import Callable, Mapping
29
+ from dataclasses import dataclass
28
30
  from http import HTTPStatus
29
31
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
30
32
  from pathlib import Path
@@ -42,9 +44,11 @@ from localmodels import (
42
44
  from localmodels.speech_admission import DeviceDecision
43
45
  from localmodels.speech_catalog import SpeechModelSpec
44
46
  from localmodels.speech_model import (
47
+ DETAIL_LIMIT,
45
48
  FallbackReason,
46
49
  SpeechConfig,
47
50
  SpeechError,
51
+ SpeechModelError,
48
52
  SpeechRuntime,
49
53
  SpeechRuntimeState,
50
54
  parse_bool_flag,
@@ -76,6 +80,8 @@ from localmodels.speech_workers import (
76
80
  )
77
81
 
78
82
  __all__ = [
83
+ "CRASH_LATCH_COUNT",
84
+ "CRASH_WINDOW_S",
79
85
  "ChildWatchdog",
80
86
  "DEMOTE_WAIT_S",
81
87
  "DEFAULT_SWEEP_INTERVAL_S",
@@ -108,6 +114,24 @@ MAX_UPLOAD_BYTES = 50 << 20 # 50 MiB bounded multipart upload
108
114
  DEMOTE_WAIT_S = 3.0
109
115
  DEFAULT_SWEEP_INTERVAL_S = 5.0
110
116
  _GPU_EFFECTIVE_DEVICES = frozenset(("cuda", "metal", "vulkan", "directml"))
117
+ # A worker that exits on its own with the same status this many times in a row, within
118
+ # CRASH_WINDOW_S, for the same model and requested device, is treated as a deterministic
119
+ # crash: the sidecar stays in state ``error`` and stops respawning it on every request until
120
+ # ``config``, ``load``, ``unload`` or a sidecar restart. One crash still retries, so a
121
+ # transient failure (a lost port race, a killed child) does not need the user to act.
122
+ CRASH_LATCH_COUNT = 2
123
+ CRASH_WINDOW_S = 120.0
124
+
125
+ _WorkerTarget = tuple[str, str] # (model_id, requested_device)
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class _CrashStreak:
130
+ target: _WorkerTarget
131
+ exit_status: int
132
+ count: int
133
+ first_at: float
134
+
111
135
 
112
136
  DeviceDecider = Callable[[SpeechModelSpec, bool], DeviceDecision]
113
137
 
@@ -116,6 +140,27 @@ def _decide_real_device(spec: SpeechModelSpec, use_gpu: bool) -> DeviceDecision:
116
140
  return speech_admission.decide_speech_device(spec, use_gpu)
117
141
 
118
142
 
143
+ def _stderr_tail(detail: str, limit: int = DETAIL_LIMIT) -> str:
144
+ """Last ``limit`` characters of worker stderr, starting at a line boundary when cut."""
145
+ text = detail.strip()
146
+ if len(text) <= limit:
147
+ return text
148
+ tail = text[-limit:]
149
+ newline = tail.find("\n")
150
+ return tail[newline + 1 :] if 0 <= newline < len(tail) - 1 else tail
151
+
152
+
153
+ def _exit_status_after_failure(worker: WorkerHandle, wait_s: float = 0.5) -> int | None:
154
+ """Exit status of a worker whose request just failed, or None while it still runs.
155
+
156
+ The connection drops as the child dies, slightly before it can be reaped, so wait briefly.
157
+ """
158
+ try:
159
+ return worker.proc.wait(timeout=wait_s)
160
+ except subprocess.TimeoutExpired:
161
+ return None
162
+
163
+
119
164
  class SpeechSidecar:
120
165
  """Thread-safe standby-first speech sidecar controller managing one isolated child worker."""
121
166
 
@@ -156,6 +201,9 @@ class SpeechSidecar:
156
201
  self._last_used: float = self._clock()
157
202
  self._last_fallback_reason: FallbackReason | None = None
158
203
  self._last_fallback_detail: dict[str, object] | None = None
204
+ self._last_error: SpeechModelError | None = None
205
+ self._crash_streak: _CrashStreak | None = None
206
+ self._latched_target: _WorkerTarget | None = None
159
207
  self._stop_event = threading.Event()
160
208
  self._sweeper: threading.Thread | None = None
161
209
 
@@ -241,8 +289,15 @@ class SpeechSidecar:
241
289
  "keep_loaded_seconds": self._config["keep_loaded_seconds"],
242
290
  "idle_remaining_seconds": self._idle_remaining_locked(),
243
291
  "active_sessions": self._active_sessions,
292
+ "error": self._error_payload_locked(),
244
293
  }
245
294
 
295
+ def _error_payload_locked(self) -> SpeechModelError | None:
296
+ err = self._last_error
297
+ if self._state != "error" or err is None:
298
+ return None
299
+ return {"code": err["code"], "message": err["message"]}
300
+
246
301
  def persist_runtime(self) -> None:
247
302
  with self._cond:
248
303
  rt = self.runtime_payload()
@@ -273,17 +328,58 @@ class SpeechSidecar:
273
328
  if worker is not None:
274
329
  worker.stop(grace_s=self._stop_grace_s)
275
330
 
331
+ def _clear_failure_locked(self) -> None:
332
+ self._last_error = None
333
+ self._crash_streak = None
334
+ self._latched_target = None
335
+ if self._state == "error" and self._worker is None:
336
+ self._state = "standby"
337
+
338
+ def _note_worker_failure_locked(
339
+ self, target: _WorkerTarget, exc: WorkerError, exit_status: int | None
340
+ ) -> WorkerError:
341
+ """Record a failed worker as ``error``, latch a repeated identical crash, and return the
342
+ error to raise in place of ``exc`` (it names the model and carries the stderr tail)."""
343
+ model_id = target[0]
344
+ tail = _stderr_tail(exc.detail)
345
+ message = f"{model_id}: {exc}" + (f": {tail}" if tail and tail != str(exc) else "")
346
+ if exit_status is not None:
347
+ now = self._clock()
348
+ prev = self._crash_streak
349
+ if (
350
+ prev is not None
351
+ and prev.target == target
352
+ and prev.exit_status == exit_status
353
+ and now - prev.first_at <= CRASH_WINDOW_S
354
+ ):
355
+ streak = _CrashStreak(target, exit_status, prev.count + 1, prev.first_at)
356
+ else:
357
+ streak = _CrashStreak(target, exit_status, 1, now)
358
+ self._crash_streak = streak
359
+ count = streak.count
360
+ if count >= CRASH_LATCH_COUNT:
361
+ self._latched_target = target
362
+ message = (
363
+ f"{model_id} worker crashed {count} times in a row with exit status "
364
+ f"{exit_status}; not restarting it until the speech configuration is changed, "
365
+ "a load is requested or the speech sidecar restarts"
366
+ + (f": {tail}" if tail else "")
367
+ )
368
+ self._last_error = {"code": "RUNTIME_ERROR", "message": message}
369
+ self._state = "error"
370
+ self.persist_runtime()
371
+ return WorkerError(message, detail=exc.detail, exit_status=exit_status)
372
+
276
373
  def _spawn_with_fallback_locked(self, spec: SpeechModelSpec, use_gpu: bool) -> WorkerHandle:
277
374
  decision = self._device_decider(spec, use_gpu)
278
375
  self._state = "loading"
279
376
  self.persist_runtime()
377
+ target: _WorkerTarget = (spec.id, "gpu" if use_gpu else "cpu")
280
378
  try:
281
379
  return self._worker_factory(spec, decision, self.base_dir, self.state_dir)
282
380
  except WorkerError as exc:
283
381
  if decision.effective_device == "cpu":
284
- self._state = "error"
285
- self.persist_runtime()
286
- raise
382
+ raise self._note_worker_failure_locked(target, exc, exc.exit_status) from exc
287
383
  reason: FallbackReason = (
288
384
  "runtime_oom_fallback" if is_gpu_oom_error(exc.detail) else "gpu_init_failed"
289
385
  )
@@ -299,10 +395,10 @@ class SpeechSidecar:
299
395
  )
300
396
  try:
301
397
  return self._worker_factory(spec, cpu_decision, self.base_dir, self.state_dir)
302
- except WorkerError:
303
- self._state = "error"
304
- self.persist_runtime()
305
- raise
398
+ except WorkerError as cpu_exc:
399
+ raise self._note_worker_failure_locked(
400
+ target, cpu_exc, cpu_exc.exit_status
401
+ ) from cpu_exc
306
402
 
307
403
  def _ensure_loaded_locked(self, model_id: str, use_gpu: bool) -> WorkerHandle:
308
404
  try:
@@ -318,9 +414,16 @@ class SpeechSidecar:
318
414
  ):
319
415
  self._state = "loaded"
320
416
  return self._worker
417
+ if self._latched_target == (spec.id, requested):
418
+ self._state = "error"
419
+ message = self._last_error["message"] if self._last_error else "worker crash loop"
420
+ self.persist_runtime()
421
+ raise WorkerError(message)
321
422
  self._wait_idle_locked()
322
423
  self._stop_worker_locked()
323
424
  worker = self._spawn_with_fallback_locked(spec, use_gpu)
425
+ self._latched_target = None
426
+ self._last_error = None
324
427
  self._worker = worker
325
428
  self._state = "loaded"
326
429
  self._last_used = self._clock()
@@ -340,6 +443,7 @@ class SpeechSidecar:
340
443
  self._config["model_id"] if not model_id or model_id == "default" else model_id
341
444
  )
342
445
  target_gpu = self._config["use_gpu"] if use_gpu is None else use_gpu
446
+ self._clear_failure_locked()
343
447
  self._ensure_loaded_locked(target_model, target_gpu)
344
448
  return self.runtime_payload()
345
449
 
@@ -353,6 +457,7 @@ class SpeechSidecar:
353
457
  )
354
458
  speech_state.save_config(validated, self.state_dir)
355
459
  self._config = validated
460
+ self._clear_failure_locked()
356
461
  if self._worker is not None and (
357
462
  changed_worker or validated["keep_loaded_seconds"] == 0
358
463
  ):
@@ -366,6 +471,7 @@ class SpeechSidecar:
366
471
  with self._cond:
367
472
  self._wait_idle_locked()
368
473
  self._stop_worker_locked()
474
+ self._clear_failure_locked()
369
475
  self.persist_runtime()
370
476
  return self.runtime_payload()
371
477
 
@@ -543,7 +649,22 @@ class SpeechSidecar:
543
649
  response_format=response_format,
544
650
  )
545
651
  else:
546
- raise
652
+ exit_status = _exit_status_after_failure(worker)
653
+ if exit_status is None:
654
+ raise
655
+ with self._cond:
656
+ if self._worker is worker:
657
+ self._stop_worker_locked(keep_fallback=True)
658
+ raise self._note_worker_failure_locked(
659
+ (resolved_model, "gpu" if target_gpu else "cpu"),
660
+ WorkerError(
661
+ f"{worker.engine} worker exited with status {exit_status}: {exc}",
662
+ detail=worker.stderr_tail() or exc.detail,
663
+ ),
664
+ exit_status,
665
+ ) from exc
666
+ with self._cond:
667
+ self._crash_streak = None
547
668
  return {
548
669
  "text": out["text"],
549
670
  "language": out["language"],
@@ -558,7 +679,7 @@ class SpeechSidecar:
558
679
  with self._cond:
559
680
  self._active_sessions = max(0, self._active_sessions - 1)
560
681
  self._last_used = self._clock()
561
- if self._active_sessions == 0 and effective_keep == 0:
682
+ if self._active_sessions == 0 and effective_keep == 0 and self._worker is not None:
562
683
  self._stop_worker_locked()
563
684
  self.persist_runtime()
564
685
  self._cond.notify_all()
@@ -30,6 +30,7 @@ from localmodels.plan_envelope import utc_now
30
30
  from localmodels.speech_catalog import V1_SPEECH_MODEL_IDS
31
31
  from localmodels.speech_model import (
32
32
  EFFECTIVE_DEVICES,
33
+ ERROR_CODES,
33
34
  FALLBACK_REASONS,
34
35
  REQUESTED_DEVICES,
35
36
  SPEECH_RUNTIME_STATES,
@@ -331,6 +332,15 @@ def _nonneg_int(value: object, default: int = 0) -> int:
331
332
  return default
332
333
 
333
334
 
335
+ def _runtime_error(value: object) -> SpeechModelError | None:
336
+ if not isinstance(value, dict):
337
+ return None
338
+ code, message = value.get("code"), value.get("message")
339
+ if not isinstance(code, str) or code not in ERROR_CODES or not isinstance(message, str):
340
+ return None
341
+ return {"code": code, "message": message}
342
+
343
+
334
344
  def _coerce_runtime(
335
345
  raw: Mapping[str, Any],
336
346
  config: SpeechConfig,
@@ -392,6 +402,7 @@ def _coerce_runtime(
392
402
  "keep_loaded_seconds": keep,
393
403
  "idle_remaining_seconds": idle_rem,
394
404
  "active_sessions": _nonneg_int(raw.get("active_sessions")),
405
+ "error": _runtime_error(raw.get("error")),
395
406
  }
396
407
 
397
408
 
@@ -11,7 +11,9 @@ from __future__ import annotations
11
11
 
12
12
  import argparse
13
13
  import array
14
+ import ctypes
14
15
  import importlib
16
+ import importlib.util
15
17
  import io
16
18
  import json
17
19
  import os
@@ -100,10 +102,46 @@ class Recognizer(Protocol):
100
102
  ) -> dict[str, object]: ...
101
103
 
102
104
 
105
+ def _preload_windows_onnxruntime() -> None:
106
+ """Load sherpa-onnx's bundled onnxruntime.dll by absolute path before importing it.
107
+
108
+ A process created with the PreferSystem32 image-load mitigation (Linger launched from a
109
+ Firefox-family browser's download panel passes it to its whole process tree) resolves the
110
+ bare name ``onnxruntime.dll`` to Windows 11 24H2+'s inbox System32 copy (ORT 1.17), which
111
+ lacks the API version sherpa-onnx needs, and the worker crashes with 0xC0000005. A module
112
+ already loaded by full path wins over the search order, so the import then binds the
113
+ bundled DLL. ``find_spec`` locates the package without importing it.
114
+ """
115
+ if sys.platform != "win32":
116
+ return
117
+ if "sherpa_onnx" in sys.modules:
118
+ return
119
+ spec = importlib.util.find_spec("sherpa_onnx")
120
+ if spec is None:
121
+ raise RuntimeError("sherpa_onnx is not installed in the SenseVoice runtime venv")
122
+ search_roots: list[Path] = []
123
+ if spec.submodule_search_locations:
124
+ search_roots.extend(Path(location) for location in spec.submodule_search_locations)
125
+ elif spec.origin:
126
+ search_roots.append(Path(spec.origin).resolve().parent)
127
+ candidates = [root / "lib" / "onnxruntime.dll" for root in search_roots]
128
+ for ort_dll in candidates:
129
+ if ort_dll.is_file():
130
+ ctypes.WinDLL(str(ort_dll))
131
+ return
132
+ searched = ", ".join(str(path) for path in candidates) or "<no package location>"
133
+ raise RuntimeError(
134
+ "sherpa-onnx's bundled onnxruntime.dll is missing (searched: "
135
+ f"{searched}); reinstall the SenseVoice runtime instead of falling back to the "
136
+ "System32 copy"
137
+ )
138
+
139
+
103
140
  class SenseVoiceRecognizer:
104
141
  """Thread-safe sherpa-onnx OfflineRecognizer wrapper for SenseVoice Small INT8."""
105
142
 
106
143
  def __init__(self, model: Path, tokens: Path, *, threads: int = 4) -> None:
144
+ _preload_windows_onnxruntime()
107
145
  sherpa_onnx = importlib.import_module("sherpa_onnx")
108
146
  self._recognizer: Any = sherpa_onnx.OfflineRecognizer.from_sense_voice(
109
147
  model=str(model),
@@ -202,9 +202,12 @@ def normalize_whisper_language(raw: str) -> str:
202
202
  class WorkerError(RuntimeError):
203
203
  """Raised when an isolated speech engine child fails to start or process audio."""
204
204
 
205
- def __init__(self, message: str, *, detail: str = "") -> None:
205
+ def __init__(self, message: str, *, detail: str = "", exit_status: int | None = None) -> None:
206
206
  super().__init__(message)
207
207
  self.detail = detail or message
208
+ # Set when the child exited on its own (before readiness or mid-request); a timeout or a
209
+ # launch failure leaves it None. The sidecar uses it to spot deterministic crash loops.
210
+ self.exit_status = exit_status
208
211
 
209
212
 
210
213
  def is_gpu_oom_error(message: str) -> bool:
@@ -474,6 +477,7 @@ def wait_worker_ready(
474
477
  raise WorkerError(
475
478
  f"{engine} worker exited with status {code}",
476
479
  detail=tail or f"exit code {code}",
480
+ exit_status=code,
477
481
  )
478
482
  for path in paths:
479
483
  req = urllib.request.Request(
@@ -21,11 +21,12 @@ from localmodels import (
21
21
  gateway,
22
22
  harness,
23
23
  hosts,
24
+ library_convert,
25
+ magpie_legacy,
24
26
  stack_events,
25
27
  stack_journal,
26
28
  stack_preflight,
27
29
  stack_run,
28
- stack_up,
29
30
  stack_update,
30
31
  )
31
32
  from localmodels import stack_decision as decide
@@ -94,7 +95,7 @@ def build(
94
95
  resolver = deploy.catalog_pins if options.get("offline") else deploy.resolve_files
95
96
  context = approved
96
97
  if context is None:
97
- accepted = stack_up._accepted()
98
+ accepted = stack_run.accepted()
98
99
  if (
99
100
  accepted
100
101
  and Path(accepted["options"]["base_dir"]).expanduser()
@@ -343,8 +344,6 @@ def _deploy_aux(task: str, part: Plan, key: str, log: Log, do: Effects) -> Compo
343
344
 
344
345
  def _sync_library(plan: StackPlan, attempt_id: str | None) -> None:
345
346
  """Keep an already-used model library in step with a newly accepted stack apply."""
346
- from localmodels import library_convert
347
-
348
347
  if library_convert.initialized():
349
348
  library_convert.sync_stack(plan, attempt_id=attempt_id, if_initialized=True)
350
349
 
@@ -514,11 +513,7 @@ def _run_components(
514
513
  wired = do.wire(
515
514
  plan["harness"], keys["llm"], keys.get("decision") if decision_ok else None, served
516
515
  )
517
- name = (
518
- "Bifrost"
519
- if harness.gateway_kind(plan["harness"]["gateway"]) == "bifrost"
520
- else "Magpie"
521
- )
516
+ name = magpie_legacy.of(plan["harness"]["gateway"]).label
522
517
  parts["gateway"] = _ok("gateway", f"{name} gateway ({state}): " + "; ".join(wired))
523
518
  except harness.HarnessError as exc:
524
519
  parts["gateway"] = _failed("gateway", str(exc))
@@ -29,7 +29,7 @@ from dataclasses import dataclass, field
29
29
  from pathlib import Path
30
30
  from typing import Literal, TypedDict
31
31
 
32
- from localmodels import cli_help, console, hosts, http_local, stack_up, stack_verify
32
+ from localmodels import cli_help, console, hosts, http_local, stack_run, stack_up, stack_verify
33
33
  from localmodels.plan_envelope import utc_now
34
34
  from localmodels.records import Plan
35
35
  from localmodels.stack_plan import StackError, command
@@ -343,7 +343,7 @@ def _resolve_targets(args: argparse.Namespace) -> tuple[ArenaTarget, ArenaTarget
343
343
  ):
344
344
  return _explicit_targets(args)
345
345
  by_name = {r["plan"]["name"]: r["plan"] for r in hosts.records(hosts.LOCAL_ID) if r.get("ok")}
346
- plan = stack_up.accepted()
346
+ plan = stack_run.accepted()
347
347
  if plan is not None and plan.get("llm_fast") is not None:
348
348
  if stack_up.drift(plan):
349
349
  raise StackError(
@@ -2,7 +2,7 @@
2
2
 
3
3
  The caller supplies the resident llama.cpp score and id. The validated recipe order, tie band,
4
4
  RAM fit and generated-pack refusals are the same policy formerly in stack_compose; local reads
5
- are supplied through the planner's readers and suite.build_plan. No state is saved or applied.
5
+ are supplied through the planner's readers and suite_plan.build_plan. No state is saved or applied.
6
6
  """
7
7
 
8
8
  from __future__ import annotations
@@ -22,7 +22,6 @@ from localmodels import (
22
22
  preparation,
23
23
  reuse,
24
24
  stack_capacity,
25
- stack_llm_ram,
26
25
  stack_ports,
27
26
  stack_suite,
28
27
  stack_warm_store,
@@ -31,10 +30,11 @@ from localmodels import (
31
30
  from localmodels import stack_aux_gpu as aux_gpu
32
31
  from localmodels import stack_decision as decide
33
32
  from localmodels import stack_gpu_memory as gpu_memory
34
- from localmodels.budget import HARNESS_RAM, RAM_FLOOR, gpu_conflicts, host_ram
35
33
  from localmodels.context_policy import AgentPosture
36
34
  from localmodels.estimator import HardwareBudget
37
35
  from localmodels.plan_envelope import PlanError
36
+ from localmodels.planning import llm_ram
37
+ from localmodels.planning.budget import HARNESS_RAM, RAM_FLOOR, gpu_conflicts, host_ram
38
38
  from localmodels.probe import HostFacts
39
39
  from localmodels.records import PinnedFile, Plan
40
40
  from localmodels.stack_plan import (
@@ -354,7 +354,7 @@ def llama_ram_fits(
354
354
  hf_download_endpoint=merged["hf_endpoint"],
355
355
  hf_api_endpoint=merged["hf_endpoint"],
356
356
  engine_path="llama-server",
357
- agent=posture if mtp else replace(posture, mtp_draft_depth=0),
357
+ agent=posture if mtp else replace(posture, mtp_draft_depth=0, draft="off"),
358
358
  quant=str(merged.get("quant") or ""),
359
359
  ),
360
360
  entries=entries,
@@ -390,7 +390,7 @@ def llama_ram_fits(
390
390
  decision_ram = 0 if merged.get("defer_services") else decide.host_ram(choice)
391
391
  min_cache_bytes = (posture.prompt_cache_min_mib << 20) if posture.prompt_cache_mib > 0 else 0
392
392
  needed = (
393
- stack_llm_ram.own_bytes(final_llm, entries, running=False, metal=False)
393
+ llm_ram.own_bytes(final_llm, entries, running=False, metal=False)
394
394
  + min_cache_bytes
395
395
  + decision_ram
396
396
  + HARNESS_RAM
@@ -14,8 +14,9 @@ from dataclasses import replace
14
14
 
15
15
  from localmodels import component, hosts, metal, suite
16
16
  from localmodels import stack_decision as decide
17
- from localmodels.budget import gib
17
+ from localmodels.engine_adapters import suite_plan
18
18
  from localmodels.plan_envelope import PlanError
19
+ from localmodels.planning.budget import gib
19
20
  from localmodels.probe import GPU, HostFacts
20
21
  from localmodels.records import Plan
21
22
  from localmodels.stack_plan import HARNESS_RAM, DecisionChoice, ram_floor
@@ -61,11 +62,12 @@ def _metal_keep_aux(
61
62
  aux: list[Plan],
62
63
  price_llm: decide.PriceLLM,
63
64
  ) -> Plan:
64
- """Step optional Metal ubatch/MTP back to 512/0 when unified-memory auxiliaries need the RAM."""
65
+ """Step optional Metal ubatch/MTP/draft back when unified-memory auxiliaries need the RAM."""
65
66
  launch = llm["launch"]
66
67
  if not aux or (
67
68
  int(str(launch.get("ubatch") or 512)) <= 512
68
69
  and int(str(launch.get("mtp_draft_depth") or 0)) <= 0
70
+ and int(str(launch.get("draft_n_max") or 0)) <= 0
69
71
  ):
70
72
  return llm
71
73
  needed = (
@@ -132,7 +134,7 @@ def place(
132
134
  out.append(part)
133
135
  continue
134
136
  try:
135
- gpu_part = suite.build_plan(
137
+ gpu_part = suite_plan.build_plan(
136
138
  hosts.LOCAL_ID,
137
139
  facts,
138
140
  recipe,