@simplexai/localmodels-darwin-x64 0.1.0-dev.101 → 0.1.0-dev.103

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 (57) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +56 -37
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +3 -1
  5. package/modules/localmodels/app.py +35 -7
  6. package/modules/localmodels/catalog.json +306 -1
  7. package/modules/localmodels/cli_parser.py +4 -0
  8. package/modules/localmodels/debug_stub_server.py +280 -7
  9. package/modules/localmodels/download-mirrors.json +76 -0
  10. package/modules/localmodels/engine_adapters/suite_plan.py +4 -2
  11. package/modules/localmodels/engines-speechcpp-v0.11.3.json +84 -0
  12. package/modules/localmodels/library_serve.py +46 -26
  13. package/modules/localmodels/remote_ops_common.py +12 -2
  14. package/modules/localmodels/sidecar_downloads.py +426 -0
  15. package/modules/localmodels/sidecar_http.py +396 -0
  16. package/modules/localmodels/sidecar_state.py +466 -0
  17. package/modules/localmodels/speech_admission.py +13 -0
  18. package/modules/localmodels/speech_jobs.py +81 -370
  19. package/modules/localmodels/speech_server.py +17 -8
  20. package/modules/localmodels/speech_state.py +87 -454
  21. package/modules/localmodels/speech_workers.py +41 -163
  22. package/modules/localmodels/stack.py +18 -0
  23. package/modules/localmodels/stack_capacity.py +37 -1
  24. package/modules/localmodels/stack_cli.py +1 -0
  25. package/modules/localmodels/stack_down.py +19 -14
  26. package/modules/localmodels/stack_hardware.py +18 -16
  27. package/modules/localmodels/stack_plan.py +21 -0
  28. package/modules/localmodels/stack_ports.py +1 -0
  29. package/modules/localmodels/stack_progress.py +15 -0
  30. package/modules/localmodels/stack_run.py +25 -2
  31. package/modules/localmodels/stack_suite.py +54 -12
  32. package/modules/localmodels/stack_up.py +51 -1
  33. package/modules/localmodels/strata_poly_server.py +140 -3
  34. package/modules/localmodels/suite.py +10 -1
  35. package/modules/localmodels/tts-moss.txt +321 -0
  36. package/modules/localmodels/tts_admission.py +396 -0
  37. package/modules/localmodels/tts_backend_speechcpp.py +487 -0
  38. package/modules/localmodels/tts_catalog.py +251 -0
  39. package/modules/localmodels/tts_cli.py +333 -0
  40. package/modules/localmodels/tts_http.py +617 -0
  41. package/modules/localmodels/tts_jobs.py +496 -0
  42. package/modules/localmodels/tts_model.py +591 -0
  43. package/modules/localmodels/tts_moss_presets.json +1 -0
  44. package/modules/localmodels/tts_serve.py +451 -0
  45. package/modules/localmodels/tts_sidecar.py +750 -0
  46. package/modules/localmodels/tts_state.py +395 -0
  47. package/modules/localmodels/tts_worker_kokoro.py +463 -0
  48. package/modules/localmodels/tts_worker_moss.py +748 -0
  49. package/modules/localmodels/tts_workers.py +696 -0
  50. package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/METADATA +1 -1
  51. package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/RECORD +53 -34
  52. package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/NOTICE +29 -0
  53. package/package.json +1 -1
  54. package/tool.json +1 -1
  55. /package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/WHEEL +0 -0
  56. /package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/entry_points.txt +0 -0
  57. /package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -28,17 +28,43 @@ from localmodels import (
28
28
  engines,
29
29
  frontend,
30
30
  http_local,
31
+ sidecar_http,
31
32
  speech_admission,
32
33
  speech_jobs,
33
34
  speech_state,
34
35
  speech_worker_sensevoice,
35
- windows_job,
36
36
  )
37
37
  from localmodels.probe import HostFacts
38
+ from localmodels.sidecar_http import (
39
+ GPU_OOM_SIGNATURES as GPU_OOM_SIGNATURES,
40
+ )
41
+ from localmodels.sidecar_http import (
42
+ WINDOWS_CREATE_NO_WINDOW as WINDOWS_CREATE_NO_WINDOW,
43
+ )
44
+ from localmodels.sidecar_http import (
45
+ WORKER_READY_TIMEOUT_S as WORKER_READY_TIMEOUT_S,
46
+ )
47
+ from localmodels.sidecar_http import (
48
+ WORKER_STOP_GRACE_S as WORKER_STOP_GRACE_S,
49
+ )
50
+ from localmodels.sidecar_http import (
51
+ ChildWatchdog as ChildWatchdog,
52
+ )
53
+ from localmodels.sidecar_http import (
54
+ SidecarWorkerError,
55
+ )
56
+ from localmodels.sidecar_http import (
57
+ is_gpu_oom_error as is_gpu_oom_error,
58
+ )
59
+ from localmodels.sidecar_http import (
60
+ stop_subprocess as stop_subprocess,
61
+ )
38
62
  from localmodels.speech_admission import DeviceDecision
39
63
  from localmodels.speech_catalog import SpeechModelSpec
40
64
  from localmodels.speech_model import EffectiveDevice, SpeechError
41
65
 
66
+ WorkerError = SidecarWorkerError
67
+
42
68
  SENSEVOICE_REQUIREMENTS = "speech-sv.txt"
43
69
  # Simplified-Chinese prompt injected ONLY when language == "zh" and speech is present.
44
70
  ZH_SIMPLIFIED_PROMPT = "\u4ee5\u4e0b\u662f\u666e\u901a\u8bdd\u7684\u53e5\u5b50\u3002"
@@ -50,33 +76,7 @@ _ZH_PROMPT_LEAD_RE = re.compile(rf"^(?:\s*{re.escape(ZH_SIMPLIFIED_PROMPT)})+\s*
50
76
  _ZH_PROMPT_TRAIL_RE = re.compile(rf"\s*(?:{re.escape(ZH_SIMPLIFIED_PROMPT)}\s*)+$")
51
77
  _LINE_BREAK_RE = re.compile(r"\s*\n\s*")
52
78
  SILENCE_RMS_THRESHOLD = 150.0 # int16 RMS noise floor (~-46.8 dBFS)
53
- WORKER_STOP_GRACE_S = 3.0 # whisper-server b5454 hangs on SIGTERM -> SIGKILL after 3s
54
- WORKER_READY_TIMEOUT_S = 60.0
55
79
  WORKER_REQUEST_TIMEOUT_S = 300.0
56
- WINDOWS_CREATE_NO_WINDOW = 0x08000000
57
-
58
- _POSIX_WATCHDOG_SH = (
59
- 'read _; kill -TERM "$0" 2>/dev/null; n=0; '
60
- 'while kill -0 "$0" 2>/dev/null && [ "$n" -lt 3 ]; do sleep 1; n=$((n+1)); done; '
61
- 'kill -KILL "$0" 2>/dev/null'
62
- )
63
- GPU_OOM_SIGNATURES: tuple[str, ...] = (
64
- "oom",
65
- "out of memory",
66
- "cuda",
67
- "cublas",
68
- "metal",
69
- "vulkan",
70
- "vkresult",
71
- "directml",
72
- "failed to allocate",
73
- "unable to allocate",
74
- "not enough memory",
75
- "insufficient memory",
76
- "bad_alloc",
77
- "kioreturnnomemory",
78
- "newbufferwithlength",
79
- )
80
80
 
81
81
  _BOUNDARY_RE = re.compile(r'boundary=(?:"([^"]+)"|([^;\s]+))', re.IGNORECASE)
82
82
  _DISPOSITION_PARAM_RE = re.compile(r'([a-zA-Z0-9_-]+)="([^"]*)"')
@@ -207,23 +207,6 @@ def normalize_whisper_language(raw: str) -> str:
207
207
  return _WHISPER_LANGUAGE_TO_ISO.get(cleaned, cleaned)
208
208
 
209
209
 
210
- class WorkerError(RuntimeError):
211
- """Raised when an isolated speech engine child fails to start or process audio."""
212
-
213
- def __init__(self, message: str, *, detail: str = "", exit_status: int | None = None) -> None:
214
- super().__init__(message)
215
- self.detail = detail or message
216
- # Set when the child exited on its own (before readiness or mid-request); a timeout or a
217
- # launch failure leaves it None. The sidecar uses it to spot deterministic crash loops.
218
- self.exit_status = exit_status
219
-
220
-
221
- def is_gpu_oom_error(message: str) -> bool:
222
- """Return True when ``message`` matches any known GPU or OOM failure signature."""
223
- lowered = message.lower()
224
- return any(sig in lowered for sig in GPU_OOM_SIGNATURES)
225
-
226
-
227
210
  def validate_wav_and_rms(data: bytes) -> tuple[float, float]:
228
211
  """Validate 16-bit mono PCM WAV bytes and return ``(duration_seconds, int16_rms)``."""
229
212
  samples, _rate, duration = speech_worker_sensevoice.read_pcm16_wav(data)
@@ -305,12 +288,7 @@ def build_multipart_body(
305
288
 
306
289
  def ensure_run_dir(state_dir: Path | None) -> Path:
307
290
  """Ensure ``$LOCALMODELS_STATE/speech/run`` exists with 0700 permissions."""
308
- path = speech_state.run_dir(state_dir)
309
- path.mkdir(parents=True, exist_ok=True)
310
- if os.name != "nt":
311
- with contextlib.suppress(OSError):
312
- path.chmod(0o700)
313
- return path
291
+ return speech_state.STORE.ensure_run_dir(state_dir)
314
292
 
315
293
 
316
294
  def whisper_argv(
@@ -424,69 +402,6 @@ def _resolve_qwen3_asr_paths(spec: SpeechModelSpec, base_dir: str) -> tuple[str,
424
402
  return str(conv), str(enc), str(dec), str(vocab.parent)
425
403
 
426
404
 
427
- class ChildWatchdog:
428
- """Binds a child worker's lifetime to this sidecar via POSIX pipe guard or Windows Job."""
429
-
430
- def __init__(self, proc: subprocess.Popen[bytes]) -> None:
431
- self._guard: subprocess.Popen[bytes] | None = None
432
- self._write_fd: int | None = None
433
- if sys.platform == "win32":
434
- handle = getattr(proc, "_handle", None)
435
- if isinstance(handle, int):
436
- windows_job.end_with_this_process(handle)
437
- return
438
- if os.name == "posix":
439
- read_fd, write_fd = os.pipe()
440
- try:
441
- self._guard = subprocess.Popen(
442
- ["/bin/sh", "-c", _POSIX_WATCHDOG_SH, str(proc.pid)],
443
- stdin=read_fd,
444
- stdout=subprocess.DEVNULL,
445
- stderr=subprocess.DEVNULL,
446
- )
447
- self._write_fd = write_fd
448
- except OSError:
449
- os.close(write_fd)
450
- finally:
451
- os.close(read_fd)
452
-
453
- def close(self) -> None:
454
- """Stop the POSIX watchdog before closing its pipe so it does not signal a reused PID."""
455
- if self._guard is not None:
456
- with contextlib.suppress(OSError):
457
- self._guard.kill()
458
- with contextlib.suppress(OSError, subprocess.TimeoutExpired):
459
- self._guard.wait(timeout=2.0)
460
- self._guard = None
461
- if self._write_fd is not None:
462
- with contextlib.suppress(OSError):
463
- os.close(self._write_fd)
464
- self._write_fd = None
465
-
466
-
467
- def stop_subprocess(
468
- proc: subprocess.Popen[bytes],
469
- watchdog: ChildWatchdog | None = None,
470
- *,
471
- grace_s: float = WORKER_STOP_GRACE_S,
472
- ) -> None:
473
- """Terminate ``proc`` with ``SIGTERM -> grace_s -> SIGKILL`` and release its watchdog."""
474
- try:
475
- if proc.poll() is None:
476
- with contextlib.suppress(OSError):
477
- proc.terminate()
478
- try:
479
- proc.wait(timeout=max(0.1, grace_s))
480
- except subprocess.TimeoutExpired:
481
- with contextlib.suppress(OSError):
482
- proc.kill()
483
- with contextlib.suppress(OSError, subprocess.TimeoutExpired):
484
- proc.wait(timeout=5.0)
485
- finally:
486
- if watchdog is not None:
487
- watchdog.close()
488
-
489
-
490
405
  @dataclass
491
406
  class WorkerHandle:
492
407
  """Live isolated engine child subprocess owned by ``SpeechSidecar``."""
@@ -526,34 +441,10 @@ def wait_worker_ready(
526
441
  timeout_s: float = WORKER_READY_TIMEOUT_S,
527
442
  ) -> None:
528
443
  """Wait until the child engine answers loopback HTTP 200 or exits early."""
529
- deadline = time.monotonic() + timeout_s
530
444
  paths = ("/health", "/") if engine == "whisper.cpp" else ("/health",)
531
- opener = http_local.no_proxy_opener(allow_redirects=False)
532
- while time.monotonic() < deadline:
533
- code = proc.poll()
534
- if code is not None:
535
- tail = ""
536
- with contextlib.suppress(OSError):
537
- tail = stderr_path.read_text(encoding="utf-8", errors="replace")[-1200:].strip()
538
- raise WorkerError(
539
- f"{engine} worker exited with status {code}",
540
- detail=tail or f"exit code {code}",
541
- exit_status=code,
542
- )
543
- for path in paths:
544
- req = urllib.request.Request(
545
- f"http://127.0.0.1:{port}{path}",
546
- headers={"Connection": "close"},
547
- method="GET",
548
- )
549
- try:
550
- with opener.open(req, timeout=1.0) as resp:
551
- if 200 <= getattr(resp, "status", 200) < 300:
552
- return
553
- except (urllib.error.URLError, OSError, http.client.HTTPException):
554
- continue
555
- time.sleep(0.1)
556
- raise WorkerError(f"{engine} worker did not become ready within {timeout_s:.0f}s")
445
+ sidecar_http.wait_worker_ready(
446
+ proc, port, engine, stderr_path, timeout_s=timeout_s, paths=paths
447
+ )
557
448
 
558
449
 
559
450
  def resolve_whisper_binary(
@@ -612,29 +503,16 @@ def _launch_worker_process(
612
503
  """Spawn, watchdog-bind, and health-check a worker child process."""
613
504
  run_cwd = ensure_run_dir(state_dir)
614
505
  stderr_path = run_cwd / f"worker-{spec.id}-{port}.stderr.log"
615
- kwargs: dict[str, Any] = {"cwd": str(run_cwd), "env": env}
616
- if sys.platform == "win32":
617
- kwargs["creationflags"] = WINDOWS_CREATE_NO_WINDOW
618
-
619
- with stderr_path.open("wb") as err_stream:
620
- try:
621
- proc = subprocess.Popen(
622
- argv,
623
- stdin=subprocess.DEVNULL,
624
- stdout=subprocess.DEVNULL,
625
- stderr=err_stream,
626
- **kwargs,
627
- )
628
- except OSError as exc:
629
- raise WorkerError(f"failed to launch {spec.engine} worker: {exc}") from None
630
-
631
- watchdog = ChildWatchdog(proc)
632
- try:
633
- wait_worker_ready(proc, port, spec.engine, stderr_path)
634
- except Exception:
635
- stop_subprocess(proc, watchdog)
636
- raise
637
-
506
+ paths = ("/health", "/") if spec.engine == "whisper.cpp" else ("/health",)
507
+ proc, watchdog = sidecar_http.launch_worker_subprocess(
508
+ argv,
509
+ env,
510
+ run_cwd,
511
+ stderr_path,
512
+ port,
513
+ spec.engine,
514
+ ready_paths=paths,
515
+ )
638
516
  return WorkerHandle(
639
517
  model_id=spec.id,
640
518
  engine=spec.engine,
@@ -46,6 +46,7 @@ from localmodels.stack_plan import (
46
46
  StackPlan,
47
47
  StackRecord,
48
48
  StackReplanError,
49
+ VramShortError,
49
50
  default_options,
50
51
  platform_error,
51
52
  )
@@ -247,6 +248,22 @@ WRONG_CODE = "the --approve value is not this plan's approval code"
247
248
  EDITED_PLAN = "the plan file was changed after it was saved: it no longer matches its approval code"
248
249
 
249
250
 
251
+ def _raise_if_vram_short(plan: StackPlan, replan: BaseException) -> None:
252
+ """A shared card with too little free VRAM now fails planning again before it fails the
253
+ check before start. Name it for what it is: the check's own VramShortError
254
+ (STACK_VRAM_INSUFFICIENT, with the free and required bytes), not STACK_REPLAN_FAILED, whose
255
+ only reason was in the text (MR !781 homewin acceptance, 2026-12-01)."""
256
+ check = hardware.shared_start_guard(plan["llm"], plan["options"], reserve_decision=True)
257
+ if check is None:
258
+ return
259
+ try:
260
+ check()
261
+ except VramShortError as short:
262
+ raise short from replan
263
+ except (PlanError, StackError, OSError):
264
+ return # the replan's own failure stands
265
+
266
+
250
267
  def apply(
251
268
  plan: StackPlan,
252
269
  approval: str,
@@ -283,6 +300,7 @@ def apply(
283
300
  else build(plan["options"], approved=plan)
284
301
  )
285
302
  except (PlanError, StackError) as exc:
303
+ _raise_if_vram_short(plan, exc)
286
304
  raise StackReplanError(
287
305
  f"planning again from this computer's current state failed: {exc}. "
288
306
  "This computer changed, or the plan was made on another machine or "
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
  from dataclasses import replace
11
11
 
12
12
  from localmodels import catalog as cat
13
- from localmodels import component, context_policy, gpu_specs, llm_rank, metal
13
+ from localmodels import component, context_policy, gpu_specs, llm_rank, metal, suite
14
14
  from localmodels.context_policy import AGENT, AgentPosture, cache_floor_bytes, posture_for
15
15
  from localmodels.deploy import DEFAULT_BASE_DIR
16
16
  from localmodels.engine_adapters import llama_cpp
@@ -23,6 +23,7 @@ from localmodels.estimator import (
23
23
  from localmodels.plan_envelope import PlanError
24
24
  from localmodels.planning.budget import gib
25
25
  from localmodels.probe import GPU, HostFacts
26
+ from localmodels.records import Plan
26
27
  from localmodels.stack_plan import CapacityFit, Hardware, StackOptions
27
28
 
28
29
  WDDM_NOTE = (
@@ -48,6 +49,41 @@ def decision_reserve(card_budget_bytes: int, options: StackOptions) -> int:
48
49
  return min(fitting) if fitting else 0
49
50
 
50
51
 
52
+ def start_floor(part: Plan) -> int:
53
+ """The least free VRAM a part's engine starts in, 0 when its recipe sets none. A PolyStrata
54
+ expert cache shrinks to what is free above ``launch.min_vram_free_bytes``, so its
55
+ ``vram_bytes`` is a ceiling. A plan saved before plans carried the floor takes the catalog
56
+ recipe's by model id."""
57
+ launch = part["launch"]
58
+ if "min_vram_free_bytes" in launch:
59
+ return int(str(launch["min_vram_free_bytes"]))
60
+ try:
61
+ recipe = suite.recipe(part["model"].get("id", ""))
62
+ except PlanError:
63
+ return 0
64
+ return suite.gpu_bytes(recipe, str(launch.get("vision", "off")))[1]
65
+
66
+
67
+ def start_need(vram_bytes: int, floor: int, card: GPU, options: StackOptions | None) -> int:
68
+ """Free VRAM a GPU part needs on ``card`` to start: the one measure for planning a shared
69
+ Strata card, every recipe (stack_suite), the check before ``stack apply`` starts a part and
70
+ ``stack up``.
71
+ ``options`` adds the smallest decision model kept beside the LLM (``stack apply``'s LLM and
72
+ planning); ``stack up`` starts each part on its own and passes None.
73
+
74
+ With a floor (``start_floor``): the floor, the decision reserve and VRAM_MARGIN. The engine's
75
+ own ``--vram-reserve-mib`` already keeps the display and its overshoot out of the expert
76
+ cache, so the 1 GiB agent reserve is not added again. Without one, ``vram_bytes`` with the
77
+ agent reserve (``stack apply``) or VRAM_MARGIN (``stack up``), as before."""
78
+ reserve = (
79
+ decision_reserve(component.auto_budget(card["total_bytes"]), options) if options else 0
80
+ )
81
+ if floor > 0:
82
+ return floor + reserve + component.VRAM_MARGIN
83
+ margin = AGENT_VRAM_RESERVE_BYTES if options is not None else component.VRAM_MARGIN
84
+ return vram_bytes + margin + reserve
85
+
86
+
51
87
  def device(facts: HostFacts, index: int) -> GPU:
52
88
  """Card ``index`` of ``cards``: an NVIDIA card, or a Mac's Metal GPU."""
53
89
  found = metal.device(facts)
@@ -144,6 +144,7 @@ def apply_cli(
144
144
  plan_id=plan_id,
145
145
  attempt_id=attempt_ids[-1] if attempt_ids else None,
146
146
  cause=stack_run.cause_of(exc, started=bool(attempt_ids)),
147
+ counts=stack_run.cause_counts(exc),
147
148
  )
148
149
 
149
150
  def emit_progress(event: stack_events.ProgressEvent) -> None:
@@ -19,6 +19,7 @@ from localmodels import (
19
19
  deployment_lifecycle,
20
20
  hosts,
21
21
  speech_state,
22
+ tts_state,
22
23
  )
23
24
  from localmodels import stack_lifecycle as lifecycle
24
25
  from localmodels.stack_plan import StackError, platform_error
@@ -80,20 +81,24 @@ def _down(out: Out) -> DownReport:
80
81
  f"{'✗' if failed else '…'} {plan['name']} {'failed to stop' if failed else 'stopped'}"
81
82
  )
82
83
  parts.append(row)
83
- speech_action, speech_detail = speech_state.stop_sidecar_if_recorded()
84
- if speech_action == "stopped" or speech_action == "failed":
85
- parts.append(
86
- {
87
- "name": "speech-sidecar",
88
- "task": "stt",
89
- "action": speech_action,
90
- "detail": speech_detail,
91
- }
92
- )
93
- out(
94
- f"{'✗' if speech_action == 'failed' else '…'} speech-sidecar "
95
- f"{'failed to stop' if speech_action == 'failed' else 'stopped'}"
96
- )
84
+ for sidecar_name, task_name, stop_fn in (
85
+ ("speech-sidecar", "stt", speech_state.stop_sidecar_if_recorded),
86
+ ("tts-sidecar", "tts", tts_state.stop_sidecar_if_recorded),
87
+ ):
88
+ action, detail = stop_fn()
89
+ if action == "stopped" or action == "failed":
90
+ parts.append(
91
+ {
92
+ "name": sidecar_name,
93
+ "task": task_name,
94
+ "action": action,
95
+ "detail": detail,
96
+ }
97
+ )
98
+ out(
99
+ f"{'✗' if action == 'failed' else '…'} {sidecar_name} "
100
+ f"{'failed to stop' if action == 'failed' else 'stopped'}"
101
+ )
97
102
  return {
98
103
  "schema": SCHEMA,
99
104
  "ok": all(p["action"] != "failed" for p in parts),
@@ -10,7 +10,6 @@ from typing import Any, cast
10
10
  from localmodels import catalog as cat
11
11
  from localmodels import (
12
12
  catalog_recipes,
13
- component,
14
13
  gpu_specs,
15
14
  llm_rank,
16
15
  metal,
@@ -20,7 +19,6 @@ from localmodels import (
20
19
  suite,
21
20
  )
22
21
  from localmodels.context_policy import AgentPosture, posture_for
23
- from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES
24
22
  from localmodels.planning.budget import (
25
23
  gib,
26
24
  holders,
@@ -33,6 +31,8 @@ from localmodels.records import Plan
33
31
  from localmodels.stack_capacity import decision_reserve as decision_reserve
34
32
  from localmodels.stack_capacity import device as device
35
33
  from localmodels.stack_capacity import llm_budget as llm_budget
34
+ from localmodels.stack_capacity import start_floor as start_floor
35
+ from localmodels.stack_capacity import start_need as start_need
36
36
  from localmodels.stack_picks import picks
37
37
  from localmodels.stack_plan import (
38
38
  Card,
@@ -41,6 +41,7 @@ from localmodels.stack_plan import (
41
41
  LlmFit,
42
42
  StackError,
43
43
  StackOptions,
44
+ VramShortError,
44
45
  default_options,
45
46
  platform_error,
46
47
  )
@@ -181,7 +182,8 @@ def check_shared_start(
181
182
  part: Plan, facts: HostFacts, *, options: StackOptions | None = None
182
183
  ) -> None:
183
184
  """Recheck free VRAM before starting. Shared or not, an unknown owner of other GPU work no
184
- longer refuses (roadmap decision 60): the card's free memory, less the margins, decides."""
185
+ longer refuses (roadmap decision 60): the card's free memory against ``start_need`` decides;
186
+ too little raises VramShortError (STACK_VRAM_INSUFFICIENT)."""
185
187
  from localmodels import hosts, stack_lifecycle
186
188
 
187
189
  for record in hosts.records("local"):
@@ -198,24 +200,24 @@ def check_shared_start(
198
200
  and rows[0]["health"] in ("ok", "ready")
199
201
  ):
200
202
  return # The verified healthy backend is already resident; no new allocation.
201
- needed = int(str(part["launch"].get("vram_bytes") or 0))
203
+ vram = int(str(part["launch"].get("vram_bytes") or 0))
204
+ floor = start_floor(part)
202
205
  assigned = cast(list[dict[str, Any]], part["placement"].get("gpus") or [])
203
- if needed <= 0 or not assigned:
206
+ if vram <= 0 or not assigned:
204
207
  raise StackError("the GPU-sharing model has no VRAM budget or no approved GPU placement")
205
208
  for target in assigned:
206
209
  card = next((g for g in facts.get("gpus") or [] if g["uuid"] == target["uuid"]), None)
207
- reserve = (
208
- decision_reserve(component.auto_budget(card["total_bytes"]), options)
209
- if card and options
210
- else 0
211
- )
212
- margin = AGENT_VRAM_RESERVE_BYTES if options is not None else component.VRAM_MARGIN
213
- if card is None or card["free_bytes"] < needed + margin + reserve:
214
- free = gib(card["free_bytes"]) if card else "no such card"
210
+ if card is None:
215
211
  raise StackError(
216
- f"free VRAM too low for the approved shared model ({free} free, "
217
- f"{gib(needed + margin + reserve)} needed); close programs that use the GPU "
218
- "and retry"
212
+ "the approved GPU of the model is not on this computer now; plan again"
213
+ )
214
+ needed = start_need(vram, floor, card, options)
215
+ if card["free_bytes"] < needed:
216
+ raise VramShortError(
217
+ f"free VRAM too low for the approved model ({gib(card['free_bytes'])} free, "
218
+ f"{gib(needed)} needed); close programs that use the GPU and retry",
219
+ free_bytes=card["free_bytes"],
220
+ required_bytes=needed,
219
221
  )
220
222
 
221
223
 
@@ -130,8 +130,29 @@ class StackReplanError(StackGuardError, PlanError):
130
130
  """A guarded rebuild still satisfies the existing PlanError catch contract."""
131
131
 
132
132
 
133
+ class VramShortError(StackGuardError):
134
+ """Too little free VRAM to start an approved GPU part; carries only the two byte counts."""
135
+
136
+ def __init__(self, message: str, *, free_bytes: int, required_bytes: int) -> None:
137
+ super().__init__(
138
+ message,
139
+ cause_code="STACK_VRAM_INSUFFICIENT",
140
+ public_message="free VRAM is too low to start the model; close programs that use "
141
+ "the GPU and retry",
142
+ )
143
+ self.free_bytes = free_bytes
144
+ self.required_bytes = required_bytes
145
+
146
+
133
147
  def guard_details(exc: BaseException) -> dict[str, object]:
134
148
  """Project only typed guard metadata; the lower event layer validates its values."""
149
+ if isinstance(exc, VramShortError):
150
+ return {
151
+ "causeCode": exc.cause_code,
152
+ "changedFields": exc.changed_fields,
153
+ "freeBytes": exc.free_bytes,
154
+ "requiredBytes": exc.required_bytes,
155
+ }
135
156
  if isinstance(exc, StackGuardError):
136
157
  return {"causeCode": exc.cause_code, "changedFields": exc.changed_fields}
137
158
  return {}
@@ -119,6 +119,7 @@ AUXILIARY_PORTS = {
119
119
  "reranker": (18351, *range(18400, 18432)),
120
120
  "stt": (18370, *range(18464, 18496)),
121
121
  }
122
+ TTS_PORTS: tuple[int, ...] = (18380, *range(18528, 18560))
122
123
 
123
124
 
124
125
  class PortUnavailableError(PlanError):
@@ -18,6 +18,16 @@ __all__ = ["JsonlObserver", "ProgressObserver", "PublicProgress", "forward", "re
18
18
 
19
19
  # Shared section names; approval.py continues to own the authorization checks.
20
20
  ERROR_PLAN_FIELDS = frozenset(STACK_PLAN_SECTIONS)
21
+ _MAX_SAFE_INT = (1 << 53) - 1 # JavaScript's safe integer range
22
+
23
+
24
+ def byte_counts(metadata: Mapping[str, object]) -> dict[str, int]:
25
+ """``freeBytes`` and ``requiredBytes`` of a STACK_VRAM_INSUFFICIENT guard, only when both
26
+ are plain non-negative integers in JavaScript's safe range; else none."""
27
+ counts = {key: metadata.get(key) for key in ("freeBytes", "requiredBytes")}
28
+ if all(type(v) is int and 0 <= v <= _MAX_SAFE_INT for v in counts.values()):
29
+ return {key: int(str(v)) for key, v in counts.items()}
30
+ return {}
21
31
 
22
32
 
23
33
  class JsonlObserver:
@@ -84,11 +94,13 @@ def error(code: int, details: Mapping[str, object] | None = None) -> int:
84
94
  cause = "STACK_APPLY_INTERRUPTED" if code == 130 else "STACK_APPLY_FAILED"
85
95
  category = "interrupted" if code == 130 else "execution"
86
96
  fields: list[str] | None = None
97
+ counts: dict[str, int] = {}
87
98
  guards = {
88
99
  "STACK_PLAN_CHANGED",
89
100
  "STACK_APPROVAL_MISMATCH",
90
101
  "STACK_REPLAN_FAILED",
91
102
  "STACK_APPLY_LOCKED",
103
+ "STACK_VRAM_INSUFFICIENT",
92
104
  }
93
105
  metadata = details if isinstance(details, Mapping) else {}
94
106
  cause_code = metadata.get("causeCode")
@@ -105,6 +117,8 @@ def error(code: int, details: Mapping[str, object] | None = None) -> int:
105
117
  ):
106
118
  cause, category = cause_code, "guard"
107
119
  fields = [field for field in changed if field in ERROR_PLAN_FIELDS] or None
120
+ if cause_code == "STACK_VRAM_INSUFFICIENT":
121
+ counts = byte_counts(metadata)
108
122
  event = {
109
123
  "schema": "localmodels.stack-error/v1",
110
124
  "event": "error",
@@ -112,6 +126,7 @@ def error(code: int, details: Mapping[str, object] | None = None) -> int:
112
126
  "category": category,
113
127
  "causeCode": cause,
114
128
  **({"changedFields": fields} if fields is not None else {}),
129
+ **counts,
115
130
  }
116
131
  print(json.dumps(event), flush=True)
117
132
  return code
@@ -11,7 +11,7 @@ from datetime import datetime, timezone
11
11
  from typing import Any, Literal
12
12
  from uuid import UUID, uuid4
13
13
 
14
- from localmodels import console, hosts
14
+ from localmodels import console, hosts, stack_progress
15
15
  from localmodels.approval import digest
16
16
  from localmodels.contracts import decode
17
17
  from localmodels.plan_envelope import utc_now
@@ -25,6 +25,7 @@ from localmodels.stack_plan import (
25
25
  StackRecord,
26
26
  command,
27
27
  deployments,
28
+ guard_details,
28
29
  )
29
30
 
30
31
  RunState = Literal["running", "completed", "failed", "interrupted"]
@@ -470,6 +471,10 @@ CAUSES = {
470
471
  "STACK_REPLAN_FAILED": "planning again from this computer's current state failed; "
471
472
  "run stack plan again on this computer",
472
473
  "STACK_APPLY_LOCKED": "another stack apply is running",
474
+ # Raised before a GPU part starts, also after execution began; free_bytes and
475
+ # required_bytes say by how much.
476
+ "STACK_VRAM_INSUFFICIENT": "free VRAM is too low to start the model; close programs that "
477
+ "use the GPU and retry",
473
478
  "STACK_APPLY_INTERRUPTED": "interrupted",
474
479
  "STACK_APPLY_REJECTED": "the plan could not be loaded or checked; "
475
480
  "run the same command without --json to see why",
@@ -601,6 +606,10 @@ def component_failure(record: StackRecord) -> tuple[list[str], tuple[str, str]]
601
606
  return failed, ("STACK_COMPONENT_FAILED", CAUSES["STACK_COMPONENT_FAILED"])
602
607
 
603
608
 
609
+ # Guard codes that keep their own cause when raised after execution started.
610
+ _AFTER_START = frozenset({"STACK_VRAM_INSUFFICIENT"})
611
+
612
+
604
613
  def cause_of(exc: BaseException, *, started: bool) -> tuple[str, str]:
605
614
  """(cause code, fixed message) for an apply that raised ``exc``: a guard's own code (and its
606
615
  literal public sentence when it has one), else interrupted, failed after starting, or
@@ -608,13 +617,25 @@ def cause_of(exc: BaseException, *, started: bool) -> tuple[str, str]:
608
617
  if isinstance(exc, KeyboardInterrupt):
609
618
  return "STACK_APPLY_INTERRUPTED", CAUSES["STACK_APPLY_INTERRUPTED"]
610
619
  code = getattr(exc, "cause_code", None)
611
- if isinstance(code, str) and code in CAUSES and not started:
620
+ if isinstance(code, str) and code in CAUSES and (not started or code in _AFTER_START):
612
621
  public = getattr(exc, "public_message", "")
613
622
  return code, public if isinstance(public, str) and public else CAUSES[code]
614
623
  code = "STACK_APPLY_FAILED" if started else "STACK_APPLY_REJECTED"
615
624
  return code, CAUSES[code]
616
625
 
617
626
 
627
+ def cause_counts(exc: BaseException) -> dict[str, int]:
628
+ """``free_bytes`` and ``required_bytes`` of a STACK_VRAM_INSUFFICIENT guard, else none."""
629
+ if getattr(exc, "cause_code", None) != "STACK_VRAM_INSUFFICIENT":
630
+ return {}
631
+ counts = stack_progress.byte_counts(guard_details(exc))
632
+ return (
633
+ {"free_bytes": counts["freeBytes"], "required_bytes": counts["requiredBytes"]}
634
+ if counts
635
+ else {}
636
+ )
637
+
638
+
618
639
  def machine_result(
619
640
  record: StackRecord | None,
620
641
  state: str,
@@ -624,6 +645,7 @@ def machine_result(
624
645
  attempt_id: str | None = None,
625
646
  plan: StackPlan | None = None,
626
647
  cause: tuple[str, str] | None = None,
648
+ counts: Mapping[str, int] | None = None,
627
649
  ) -> int:
628
650
  view = project(record, plan)
629
651
  if record is not None and (view is None or (state == "completed" and not view["ok"])):
@@ -662,6 +684,7 @@ def machine_result(
662
684
  else {}
663
685
  ),
664
686
  **({"cause_code": cause[0], "message": cause[1]} if cause else {}),
687
+ **(counts if cause and counts else {}),
665
688
  },
666
689
  separators=(",", ":"),
667
690
  )