@simplexai/localmodels-darwin-x64 0.1.0-dev.60 → 0.1.0-dev.62

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 (79) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +78 -64
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +5 -3
  5. package/modules/localmodels/auth_proxy.py +185 -19
  6. package/modules/localmodels/catalog.json +363 -0
  7. package/modules/localmodels/catalog.py +1 -1
  8. package/modules/localmodels/catalog_add.py +5 -5
  9. package/modules/localmodels/catalog_license.py +2 -0
  10. package/modules/localmodels/catalog_recipes.py +2 -0
  11. package/modules/localmodels/cli_parser.py +6 -2
  12. package/modules/localmodels/context_policy.py +40 -4
  13. package/modules/localmodels/custom_hub_http.py +27 -104
  14. package/modules/localmodels/debug_mode.py +13 -0
  15. package/modules/localmodels/debug_stub_server.py +156 -1
  16. package/modules/localmodels/deploy.py +11 -2
  17. package/modules/localmodels/download-mirrors.json +12 -0
  18. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  19. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  20. package/modules/localmodels/gateway_app_bifrost.py +14 -14
  21. package/modules/localmodels/gateway_bifrost.py +4 -1
  22. package/modules/localmodels/gateway_cli.py +14 -80
  23. package/modules/localmodels/gateway_server.py +88 -16
  24. package/modules/localmodels/gpu_specs.py +35 -1
  25. package/modules/localmodels/harness.py +1 -2
  26. package/modules/localmodels/hf_repo.py +12 -4
  27. package/modules/localmodels/install.py +4 -4
  28. package/modules/localmodels/library_jobs.py +4 -0
  29. package/modules/localmodels/library_serve.py +69 -13
  30. package/modules/localmodels/memcalc_load.py +9 -4
  31. package/modules/localmodels/npm_transport.py +4 -58
  32. package/modules/localmodels/recommend_cli.py +2 -1
  33. package/modules/localmodels/remote_ops.py +120 -713
  34. package/modules/localmodels/remote_ops_common.py +670 -0
  35. package/modules/localmodels/remote_ops_download.py +399 -381
  36. package/modules/localmodels/remote_ops_mirrors.py +27 -66
  37. package/modules/localmodels/remote_ops_prepare.py +43 -35
  38. package/modules/localmodels/remote_ops_ranges.py +102 -63
  39. package/modules/localmodels/remote_ops_redirect.py +393 -0
  40. package/modules/localmodels/remote_ops_remove.py +30 -22
  41. package/modules/localmodels/remote_ops_service.py +102 -95
  42. package/modules/localmodels/remote_ops_verify.py +94 -63
  43. package/modules/localmodels/runtime_cli.py +15 -5
  44. package/modules/localmodels/runtime_io.py +54 -1
  45. package/modules/localmodels/source_cli.py +136 -23
  46. package/modules/localmodels/speech-sv.txt +93 -0
  47. package/modules/localmodels/speech_admission.py +437 -0
  48. package/modules/localmodels/speech_catalog.py +170 -0
  49. package/modules/localmodels/speech_cli.py +273 -0
  50. package/modules/localmodels/speech_jobs.py +776 -0
  51. package/modules/localmodels/speech_model.py +404 -0
  52. package/modules/localmodels/speech_serve.py +287 -0
  53. package/modules/localmodels/speech_server.py +837 -0
  54. package/modules/localmodels/speech_state.py +697 -0
  55. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  56. package/modules/localmodels/speech_workers.py +783 -0
  57. package/modules/localmodels/stack.py +0 -33
  58. package/modules/localmodels/stack_auto.py +5 -3
  59. package/modules/localmodels/stack_aux_gpu.py +45 -4
  60. package/modules/localmodels/stack_capacity.py +77 -8
  61. package/modules/localmodels/stack_cli.py +16 -1
  62. package/modules/localmodels/stack_compose.py +1 -1
  63. package/modules/localmodels/stack_down.py +24 -1
  64. package/modules/localmodels/stack_hardware.py +57 -88
  65. package/modules/localmodels/stack_hardware_text.py +4 -59
  66. package/modules/localmodels/stack_memory.py +13 -3
  67. package/modules/localmodels/stack_suite.py +9 -10
  68. package/modules/localmodels/stack_summary.py +4 -4
  69. package/modules/localmodels/stack_view_llm.py +1 -1
  70. package/modules/localmodels/transport.py +4 -2
  71. package/modules/localmodels/tui_views.py +2 -2
  72. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/METADATA +1 -1
  73. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/RECORD +75 -61
  74. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/NOTICE +9 -0
  75. package/package.json +1 -1
  76. package/tool.json +1 -1
  77. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/WHEEL +0 -0
  78. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/entry_points.txt +0 -0
  79. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,697 @@
1
+ """Persistent state under ``$LOCALMODELS_STATE/speech/`` and sidecar loopback HTTP client.
2
+
3
+ Layout:
4
+ - ``config.json`` (0600): user speech configuration (model_id, use_gpu, keep_loaded_seconds, language)
5
+ - ``runtime.json`` (0600): live sidecar receipt (base_url, key_file, pid, pool, device telemetry)
6
+ - ``models/<id>.json`` (0600): installed speech model weight/engine record
7
+ - ``jobs/<id>.json``, ``jobs/<id>.pid``, ``jobs/<id>.cancel``: active or failed download jobs
8
+ - ``.lock``: cross-platform exclusive file lock mirroring ``library_state.py``
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import json
15
+ import os
16
+ import re
17
+ import secrets
18
+ import time
19
+ import urllib.error
20
+ import urllib.request
21
+ import uuid
22
+ from collections.abc import Iterator, Mapping
23
+ from contextlib import contextmanager
24
+ from pathlib import Path
25
+ from typing import Any, Literal, TypedDict, cast
26
+
27
+ from localmodels import hosts, http_local, library_state, process_identity
28
+ from localmodels.contracts import decode
29
+ from localmodels.plan_envelope import utc_now
30
+ from localmodels.speech_catalog import V1_SPEECH_MODEL_IDS
31
+ from localmodels.speech_model import (
32
+ EFFECTIVE_DEVICES,
33
+ FALLBACK_REASONS,
34
+ REQUESTED_DEVICES,
35
+ SPEECH_RUNTIME_STATES,
36
+ STOP_SCHEMA,
37
+ DownloadStep,
38
+ EffectiveDevice,
39
+ FallbackReason,
40
+ RequestedDevice,
41
+ SpeechConfig,
42
+ SpeechError,
43
+ SpeechModelError,
44
+ SpeechRuntime,
45
+ SpeechRuntimeState,
46
+ SpeechStopDocument,
47
+ default_config,
48
+ stopped_runtime,
49
+ validate_keep_loaded_seconds,
50
+ validate_language,
51
+ )
52
+
53
+ MODEL_RECORD_SCHEMA = "localmodels.speech-model/v1"
54
+ JOB_SCHEMA = "localmodels.speech-job/v1"
55
+ CONFIG_FILE_SCHEMA = "localmodels.speech-config-store/v1"
56
+ RUNTIME_FILE_SCHEMA = "localmodels.speech-runtime-record/v1"
57
+ JOB_WRITE_EVERY_S = 1.0
58
+
59
+
60
+ class _SpeechModelRecordOptional(TypedDict, total=False):
61
+ engine_dir: str | None
62
+ engine_backend: str | None
63
+ error: SpeechModelError
64
+
65
+
66
+ class SpeechModelRecord(_SpeechModelRecordOptional):
67
+ schema: str
68
+ id: str
69
+ base_dir: str
70
+ model_dir: str
71
+ files: list[str]
72
+ state: str
73
+ updated_at: str
74
+
75
+
76
+ class _SpeechJobOptional(TypedDict, total=False):
77
+ error: SpeechModelError
78
+
79
+
80
+ class SpeechJob(_SpeechJobOptional):
81
+ schema: str
82
+ id: str
83
+ kind: str
84
+ model: str
85
+ base_dir: str
86
+ files: list[str]
87
+ step: str
88
+ done_bytes: int
89
+ total_bytes: int
90
+ bytes_per_second: int
91
+ source: str
92
+ connections: int
93
+ started_at: str
94
+ updated_at: str
95
+
96
+
97
+ def root(state_dir: Path | None = None) -> Path:
98
+ base = hosts.state_dir() if state_dir is None else state_dir
99
+ return base / "speech"
100
+
101
+
102
+ def _safe_name(model_id: str) -> str:
103
+ return re.sub(r"[^A-Za-z0-9._-]+", "_", model_id)
104
+
105
+
106
+ def config_path(state_dir: Path | None = None) -> Path:
107
+ return root(state_dir) / "config.json"
108
+
109
+
110
+ def runtime_path(state_dir: Path | None = None) -> Path:
111
+ return root(state_dir) / "runtime.json"
112
+
113
+
114
+ def api_key_path(state_dir: Path | None = None) -> Path:
115
+ return root(state_dir) / "api-key"
116
+
117
+
118
+ def run_dir(state_dir: Path | None = None) -> Path:
119
+ return root(state_dir) / "run"
120
+
121
+
122
+ def server_pid_path(state_dir: Path | None = None) -> Path:
123
+ return root(state_dir) / "server.pid"
124
+
125
+
126
+ def server_log_path(state_dir: Path | None = None) -> Path:
127
+ return root(state_dir) / "server.log"
128
+
129
+
130
+ def ensure_api_key(state_dir: Path | None = None) -> tuple[Path, str]:
131
+ """Return ``(key_path, token)``, creating a 0600 bearer key if missing or empty."""
132
+ path = api_key_path(state_dir)
133
+ existing = read_api_key(str(path))
134
+ if existing:
135
+ return path, existing
136
+ token = secrets.token_urlsafe(32)
137
+ http_local.write_private_text(path, token + "\n")
138
+ return path, token
139
+
140
+
141
+ def clear_server_pid(state_dir: Path | None = None) -> None:
142
+ pp = server_pid_path(state_dir)
143
+ for path in (pp, Path(str(pp) + ".identity.json")):
144
+ path.unlink(missing_ok=True)
145
+
146
+
147
+ def record_path(model_id: str, state_dir: Path | None = None) -> Path:
148
+ return root(state_dir) / "models" / f"{_safe_name(model_id)}.json"
149
+
150
+
151
+ def job_path(model_id: str, state_dir: Path | None = None) -> Path:
152
+ return root(state_dir) / "jobs" / f"{_safe_name(model_id)}.json"
153
+
154
+
155
+ def pid_path(model_id: str, state_dir: Path | None = None) -> Path:
156
+ return root(state_dir) / "jobs" / f"{_safe_name(model_id)}.pid"
157
+
158
+
159
+ def cancel_path(model_id: str, state_dir: Path | None = None) -> Path:
160
+ return root(state_dir) / "jobs" / f"{_safe_name(model_id)}.cancel"
161
+
162
+
163
+ @contextmanager
164
+ def locked(state_dir: Path | None = None) -> Iterator[None]:
165
+ """Exclusive cross-platform lock serializing speech state transitions."""
166
+ with hosts.file_lock(root(state_dir) / ".lock"):
167
+ yield
168
+
169
+
170
+ # ---------------------------------------------------------------------------- config
171
+
172
+
173
+ def validate_config(raw: Mapping[str, object]) -> SpeechConfig:
174
+ """Validate and normalize a speech configuration mapping."""
175
+ base = default_config()
176
+ model_id = raw.get("model_id", base["model_id"])
177
+ if not isinstance(model_id, str) or model_id not in V1_SPEECH_MODEL_IDS:
178
+ raise SpeechError("MODEL_UNKNOWN", f"unknown speech model: {model_id}")
179
+ use_gpu = raw.get("use_gpu", base["use_gpu"])
180
+ if not isinstance(use_gpu, bool):
181
+ raise SpeechError("INVALID_CONFIG", "use_gpu must be a boolean")
182
+ keep_raw = raw.get("keep_loaded_seconds", base["keep_loaded_seconds"])
183
+ if isinstance(keep_raw, bool) or not isinstance(keep_raw, int):
184
+ raise SpeechError("INVALID_CONFIG", "keep_loaded_seconds must be an integer")
185
+ keep = validate_keep_loaded_seconds(keep_raw)
186
+ lang_raw = raw.get("language", base["language"])
187
+ if not isinstance(lang_raw, str):
188
+ raise SpeechError("INVALID_CONFIG", "language must be a string")
189
+ lang = validate_language(lang_raw)
190
+ return {
191
+ "model_id": model_id,
192
+ "use_gpu": use_gpu,
193
+ "keep_loaded_seconds": keep,
194
+ "language": lang,
195
+ }
196
+
197
+
198
+ def load_config(state_dir: Path | None = None) -> SpeechConfig:
199
+ """Load saved speech configuration, falling back cleanly to defaults."""
200
+ path = config_path(state_dir)
201
+ try:
202
+ raw = json.loads(path.read_text(encoding="utf-8"))
203
+ if not isinstance(raw, dict):
204
+ return default_config()
205
+ return validate_config(raw)
206
+ except (OSError, ValueError, SpeechError):
207
+ return default_config()
208
+
209
+
210
+ def save_config(config: SpeechConfig, state_dir: Path | None = None) -> Path:
211
+ """Validate and atomically save ``config.json`` with 0600 permissions."""
212
+ validated = validate_config(config)
213
+ payload = {
214
+ "schema": CONFIG_FILE_SCHEMA,
215
+ **validated,
216
+ "updated_at": utc_now(),
217
+ }
218
+ return hosts.save_private(config_path(state_dir), payload)
219
+
220
+
221
+ # ---------------------------------------------------------------------------- runtime & loopback HTTP
222
+
223
+
224
+ def load_runtime_record(state_dir: Path | None = None) -> dict[str, Any] | None:
225
+ """Read ``runtime.json`` if present and valid JSON."""
226
+ try:
227
+ raw = json.loads(runtime_path(state_dir).read_text(encoding="utf-8"))
228
+ return raw if isinstance(raw, dict) else None
229
+ except (OSError, ValueError):
230
+ return None
231
+
232
+
233
+ def save_runtime_record(record: Mapping[str, Any], state_dir: Path | None = None) -> Path:
234
+ """Atomically persist ``runtime.json`` with 0600 permissions."""
235
+ payload = {
236
+ "schema": RUNTIME_FILE_SCHEMA,
237
+ **record,
238
+ "updated_at": utc_now(),
239
+ }
240
+ return hosts.save_private(runtime_path(state_dir), payload)
241
+
242
+
243
+ def clear_runtime_record(state_dir: Path | None = None) -> None:
244
+ runtime_path(state_dir).unlink(missing_ok=True)
245
+
246
+
247
+ def read_api_key(key_file: str | None) -> str | None:
248
+ """Read the loopback bearer token from ``key_file`` when present."""
249
+ if not key_file:
250
+ return None
251
+ try:
252
+ token = Path(key_file).expanduser().read_text(encoding="utf-8").strip()
253
+ return token or None
254
+ except OSError:
255
+ return None
256
+
257
+
258
+ def sidecar_request_detail(
259
+ base_url: str,
260
+ path: str,
261
+ *,
262
+ method: str = "GET",
263
+ key_file: str | None = None,
264
+ payload: Mapping[str, object] | None = None,
265
+ timeout: float = 2.0,
266
+ ) -> tuple[int, dict[str, Any] | None]:
267
+ """Authenticated loopback request returning ``(http_status, parsed_json_or_none)``.
268
+
269
+ Returns ``(0, None)`` when the sidecar is unreachable. Uses
270
+ ``no_proxy_opener(allow_redirects=False)`` and ``Connection: close`` to prevent proxy
271
+ hijacking, credential redirects, and Windows loopback keep-alive resets.
272
+ """
273
+ url = base_url.rstrip("/") + "/" + path.lstrip("/")
274
+ headers: dict[str, str] = {"Connection": "close"}
275
+ token = read_api_key(key_file)
276
+ if token:
277
+ headers["Authorization"] = f"Bearer {token}"
278
+ body: bytes | None = None
279
+ if payload is not None:
280
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
281
+ headers["Content-Type"] = "application/json"
282
+ req = urllib.request.Request(url, data=body, headers=headers, method=method)
283
+ opener = http_local.no_proxy_opener(allow_redirects=False)
284
+ try:
285
+ with opener.open(req, timeout=timeout) as resp:
286
+ status = int(getattr(resp, "status", 200))
287
+ raw = resp.read().decode("utf-8", "replace").strip()
288
+ if not raw:
289
+ return status, {}
290
+ parsed = json.loads(raw)
291
+ return status, parsed if isinstance(parsed, dict) else None
292
+ except urllib.error.HTTPError as exc:
293
+ try:
294
+ raw = exc.read().decode("utf-8", "replace").strip()
295
+ parsed = json.loads(raw) if raw else None
296
+ return int(exc.code), parsed if isinstance(parsed, dict) else None
297
+ except (OSError, ValueError):
298
+ return int(exc.code), None
299
+ except (urllib.error.URLError, OSError, ValueError):
300
+ return 0, None
301
+
302
+
303
+ def sidecar_request(
304
+ base_url: str,
305
+ path: str,
306
+ *,
307
+ method: str = "GET",
308
+ key_file: str | None = None,
309
+ payload: Mapping[str, object] | None = None,
310
+ timeout: float = 2.0,
311
+ ) -> dict[str, Any] | None:
312
+ """Best-effort authenticated loopback request returning parsed JSON on 2xx, else ``None``."""
313
+ status, parsed = sidecar_request_detail(
314
+ base_url,
315
+ path,
316
+ method=method,
317
+ key_file=key_file,
318
+ payload=payload,
319
+ timeout=timeout,
320
+ )
321
+ return parsed if 200 <= status < 300 else None
322
+
323
+
324
+ def _opt_str(value: object) -> str | None:
325
+ return value if isinstance(value, str) and value else None
326
+
327
+
328
+ def _nonneg_int(value: object, default: int = 0) -> int:
329
+ if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
330
+ return value
331
+ return default
332
+
333
+
334
+ def _coerce_runtime(
335
+ raw: Mapping[str, Any],
336
+ config: SpeechConfig,
337
+ base_url: str,
338
+ key_file: str | None,
339
+ ) -> SpeechRuntime:
340
+ """Normalize a live sidecar status/health payload into the frozen ``SpeechRuntime`` shape."""
341
+ state_raw = raw.get("state")
342
+ state: SpeechRuntimeState = (
343
+ cast(SpeechRuntimeState, state_raw)
344
+ if isinstance(state_raw, str) and state_raw in SPEECH_RUNTIME_STATES
345
+ else "standby"
346
+ )
347
+ req_raw = raw.get("requested_device")
348
+ req_dev: RequestedDevice = (
349
+ cast(RequestedDevice, req_raw)
350
+ if isinstance(req_raw, str) and req_raw in REQUESTED_DEVICES
351
+ else ("gpu" if config["use_gpu"] else "cpu")
352
+ )
353
+ eff_raw = raw.get("effective_device")
354
+ eff_dev: EffectiveDevice | None = (
355
+ cast(EffectiveDevice, eff_raw)
356
+ if isinstance(eff_raw, str) and eff_raw in EFFECTIVE_DEVICES
357
+ else None
358
+ )
359
+ fb_raw = raw.get("fallback_reason")
360
+ fb_reason: FallbackReason | None = (
361
+ cast(FallbackReason, fb_raw)
362
+ if isinstance(fb_raw, str) and fb_raw in FALLBACK_REASONS
363
+ else None
364
+ )
365
+ fb_detail = raw.get("fallback_detail")
366
+ detail_dict: dict[str, object] | None = dict(fb_detail) if isinstance(fb_detail, dict) else None
367
+ keep_raw = raw.get("keep_loaded_seconds")
368
+ keep = (
369
+ keep_raw
370
+ if isinstance(keep_raw, int) and not isinstance(keep_raw, bool) and -1 <= keep_raw <= 86400
371
+ else config["keep_loaded_seconds"]
372
+ )
373
+ idle_raw = raw.get("idle_remaining_seconds")
374
+ idle_rem = (
375
+ idle_raw
376
+ if isinstance(idle_raw, int) and not isinstance(idle_raw, bool) and idle_raw >= 0
377
+ else None
378
+ )
379
+ return {
380
+ "running": True,
381
+ "state": state,
382
+ "base_url": _opt_str(raw.get("base_url")) or base_url,
383
+ "key_file": _opt_str(raw.get("key_file")) or key_file,
384
+ "active_model": _opt_str(raw.get("active_model")),
385
+ "engine": _opt_str(raw.get("engine")),
386
+ "requested_device": req_dev,
387
+ "effective_device": eff_dev,
388
+ "fallback_reason": fb_reason,
389
+ "fallback_detail": detail_dict,
390
+ "vram_used_bytes": _nonneg_int(raw.get("vram_used_bytes")),
391
+ "ram_used_bytes": _nonneg_int(raw.get("ram_used_bytes")),
392
+ "keep_loaded_seconds": keep,
393
+ "idle_remaining_seconds": idle_rem,
394
+ "active_sessions": _nonneg_int(raw.get("active_sessions")),
395
+ }
396
+
397
+
398
+ def probe_live_runtime(
399
+ config: SpeechConfig,
400
+ state_dir: Path | None = None,
401
+ *,
402
+ timeout: float = 1.5,
403
+ ) -> SpeechRuntime:
404
+ """Probe the running sidecar named by ``runtime.json``, else return a stopped runtime."""
405
+ rec = load_runtime_record(state_dir)
406
+ if rec is None:
407
+ return stopped_runtime(config)
408
+ base_url = _opt_str(rec.get("base_url"))
409
+ if not base_url:
410
+ return stopped_runtime(config)
411
+ key_file = _opt_str(rec.get("key_file"))
412
+ live = sidecar_request(base_url, "/v1/speech/status", key_file=key_file, timeout=timeout)
413
+ if live is not None:
414
+ return _coerce_runtime(live, config, base_url, key_file)
415
+ health = sidecar_request(base_url, "/health", timeout=timeout)
416
+ if health is not None and health.get("status") == "ok":
417
+ merged: dict[str, Any] = {**rec, **health}
418
+ return _coerce_runtime(merged, config, base_url, key_file)
419
+ return stopped_runtime(config)
420
+
421
+
422
+ def _wait_server_pid_exit(pid_file: Path, timeout_s: float) -> bool:
423
+ deadline = time.monotonic() + timeout_s
424
+ while time.monotonic() < deadline:
425
+ state, _pid = process_identity.status(pid_file)
426
+ if state == "inactive":
427
+ return True
428
+ time.sleep(0.05)
429
+ return process_identity.status(pid_file)[0] == "inactive"
430
+
431
+
432
+ def stop_sidecar(
433
+ state_dir: Path | None = None,
434
+ *,
435
+ http_timeout_s: float = 1.0,
436
+ poll_s: float = 1.0,
437
+ grace_s: float = 3.0,
438
+ ) -> SpeechStopDocument:
439
+ """Stop the speech sidecar cleanly (HTTP shutdown -> verified ``process_identity.stop``)."""
440
+ cfg = load_config(state_dir)
441
+ rec = load_runtime_record(state_dir)
442
+ pid_file = server_pid_path(state_dir)
443
+ was_running = False
444
+
445
+ if rec is not None and isinstance(base_url := rec.get("base_url"), str) and base_url:
446
+ key_file = rec.get("key_file")
447
+ status_code, _parsed = sidecar_request_detail(
448
+ base_url,
449
+ "/v1/speech/shutdown",
450
+ method="POST",
451
+ key_file=key_file if isinstance(key_file, str) else None,
452
+ payload={},
453
+ timeout=http_timeout_s,
454
+ )
455
+ if 200 <= status_code < 300:
456
+ was_running = True
457
+ _wait_server_pid_exit(pid_file, poll_s)
458
+
459
+ if os.path.lexists(pid_file):
460
+ outcome = process_identity.stop(pid_file, grace=grace_s)
461
+ if outcome == "stopped":
462
+ was_running = True
463
+
464
+ clear_runtime_record(state_dir)
465
+ clear_server_pid(state_dir)
466
+ return {
467
+ "schema": STOP_SCHEMA,
468
+ "ok": True,
469
+ "stopped": was_running,
470
+ "detail": "stopped" if was_running else "not-running",
471
+ "runtime": stopped_runtime(cfg),
472
+ }
473
+
474
+
475
+ def stop_sidecar_if_recorded(
476
+ state_dir: Path | None = None,
477
+ ) -> tuple[Literal["none", "stopped", "not-running", "failed"], str]:
478
+ """Stop any speech sidecar recorded under ``state_dir`` for ``stack down``."""
479
+ rec = load_runtime_record(state_dir)
480
+ pid_file = server_pid_path(state_dir)
481
+ if rec is None and not os.path.lexists(pid_file):
482
+ return "none", ""
483
+ try:
484
+ doc = stop_sidecar(state_dir)
485
+ except (RuntimeError, SpeechError, OSError) as exc:
486
+ return "failed", str(exc)[-300:]
487
+ return ("stopped" if doc["stopped"] else "not-running"), ""
488
+
489
+
490
+ # ---------------------------------------------------------------------------- model records
491
+
492
+
493
+ def load_record(model_id: str, state_dir: Path | None = None) -> SpeechModelRecord | None:
494
+ try:
495
+ raw = json.loads(record_path(model_id, state_dir).read_text(encoding="utf-8"))
496
+ return decode(raw, SpeechModelRecord)
497
+ except (OSError, ValueError):
498
+ return None
499
+
500
+
501
+ def records(state_dir: Path | None = None) -> list[SpeechModelRecord]:
502
+ found: list[SpeechModelRecord] = []
503
+ models_dir = root(state_dir) / "models"
504
+ if not models_dir.is_dir():
505
+ return found
506
+ for path in sorted(models_dir.glob("*.json")):
507
+ try:
508
+ found.append(decode(json.loads(path.read_text(encoding="utf-8")), SpeechModelRecord))
509
+ except (OSError, ValueError):
510
+ continue
511
+ return found
512
+
513
+
514
+ def save_record(record: SpeechModelRecord, state_dir: Path | None = None) -> Path:
515
+ record["updated_at"] = utc_now()
516
+ return hosts.save_private(record_path(record["id"], state_dir), record)
517
+
518
+
519
+ def forget_record(model_id: str, state_dir: Path | None = None) -> None:
520
+ record_path(model_id, state_dir).unlink(missing_ok=True)
521
+
522
+
523
+ # ---------------------------------------------------------------------------- download jobs
524
+
525
+
526
+ def read_job(model_id: str, state_dir: Path | None = None) -> SpeechJob | None:
527
+ try:
528
+ raw = json.loads(job_path(model_id, state_dir).read_text(encoding="utf-8"))
529
+ return decode(raw, SpeechJob)
530
+ except (OSError, ValueError):
531
+ return None
532
+
533
+
534
+ def job_alive(model_id: str, state_dir: Path | None = None) -> bool:
535
+ try:
536
+ state, pid = process_identity.status(pid_path(model_id, state_dir))
537
+ except (OSError, RuntimeError, ValueError):
538
+ return False
539
+ return state == "active" and pid is not None and read_job(model_id, state_dir) is not None
540
+
541
+
542
+ def jobs(state_dir: Path | None = None) -> dict[str, tuple[SpeechJob, bool]]:
543
+ found: dict[str, tuple[SpeechJob, bool]] = {}
544
+ jobs_dir = root(state_dir) / "jobs"
545
+ if not jobs_dir.is_dir():
546
+ return found
547
+ for path in sorted(jobs_dir.glob("*.json")):
548
+ try:
549
+ job = decode(json.loads(path.read_text(encoding="utf-8")), SpeechJob)
550
+ except (OSError, ValueError):
551
+ continue
552
+ found[job["model"]] = (job, job_alive(job["model"], state_dir))
553
+ return found
554
+
555
+
556
+ def receipt(model_id: str, state_dir: Path | None = None) -> process_identity.Identity | None:
557
+ try:
558
+ ident_path = Path(str(pid_path(model_id, state_dir)) + ".identity.json")
559
+ return decode(json.loads(ident_path.read_text(encoding="utf-8")), process_identity.Identity)
560
+ except (OSError, ValueError):
561
+ return None
562
+
563
+
564
+ def mark_cancelled(job: SpeechJob, state_dir: Path | None = None) -> None:
565
+ path = cancel_path(job["model"], state_dir)
566
+ path.parent.mkdir(parents=True, exist_ok=True)
567
+ path.write_text(str(job["id"]), encoding="utf-8")
568
+
569
+
570
+ def is_cancelled(job: SpeechJob, state_dir: Path | None = None) -> bool:
571
+ try:
572
+ return cancel_path(job["model"], state_dir).read_text(encoding="utf-8") == str(job["id"])
573
+ except OSError:
574
+ return False
575
+
576
+
577
+ def clear_job(model_id: str, state_dir: Path | None = None) -> None:
578
+ jp = job_path(model_id, state_dir)
579
+ pp = pid_path(model_id, state_dir)
580
+ for path in (
581
+ jp,
582
+ jp.with_name(jp.name + ".tmp"),
583
+ cancel_path(model_id, state_dir),
584
+ pp,
585
+ Path(str(pp) + ".identity.json"),
586
+ ):
587
+ path.unlink(missing_ok=True)
588
+
589
+
590
+ def fail_job(job: SpeechJob, error: SpeechModelError, state_dir: Path | None = None) -> None:
591
+ job["error"] = error
592
+ job["updated_at"] = utc_now()
593
+ hosts.save_private(job_path(job["model"], state_dir), job)
594
+ pp = pid_path(job["model"], state_dir)
595
+ for path in (cancel_path(job["model"], state_dir), pp, Path(str(pp) + ".identity.json")):
596
+ path.unlink(missing_ok=True)
597
+
598
+
599
+ def current_job(job: SpeechJob, state_dir: Path | None = None) -> bool:
600
+ found = read_job(job["model"], state_dir)
601
+ return found is not None and found["id"] == job["id"]
602
+
603
+
604
+ def acquire_job(
605
+ model_id: str,
606
+ base_dir: str,
607
+ files: list[str],
608
+ total_bytes: int,
609
+ *,
610
+ state_dir: Path | None = None,
611
+ ) -> SpeechJob:
612
+ """Under ``locked()``: claim an exclusive download job for ``model_id``."""
613
+ existing = read_job(model_id, state_dir)
614
+ if existing is not None and job_alive(model_id, state_dir):
615
+ raise SpeechError("JOB_RUNNING", f"{model_id} already has a running download")
616
+ clear_job(model_id, state_dir)
617
+ library_state.become_leader()
618
+ now = utc_now()
619
+ job: SpeechJob = {
620
+ "schema": JOB_SCHEMA,
621
+ "id": uuid.uuid4().hex,
622
+ "kind": "download",
623
+ "model": model_id,
624
+ "base_dir": base_dir,
625
+ "files": list(files),
626
+ "step": "download",
627
+ "done_bytes": 0,
628
+ "total_bytes": max(0, int(total_bytes)),
629
+ "bytes_per_second": 0,
630
+ "source": "huggingface",
631
+ "connections": 0,
632
+ "started_at": now,
633
+ "updated_at": now,
634
+ }
635
+ hosts.save_private(job_path(model_id, state_dir), job)
636
+ try:
637
+ process_identity.save(pid_path(model_id, state_dir), os.getpid())
638
+ except (OSError, RuntimeError) as exc:
639
+ clear_job(model_id, state_dir)
640
+ raise SpeechError("INVALID_STATE", f"cannot record speech job process: {exc}") from None
641
+ return job
642
+
643
+
644
+ @contextmanager
645
+ def held_job(claims: list[SpeechJob], state_dir: Path | None = None) -> Iterator[None]:
646
+ """Release claimed speech jobs on exit unless already cleared or replaced."""
647
+ try:
648
+ yield
649
+ finally:
650
+ with locked(state_dir):
651
+ for job in claims:
652
+ if current_job(job, state_dir):
653
+ clear_job(job["model"], state_dir)
654
+
655
+
656
+ def stop_job_process(saved: process_identity.Identity, grace: float = 20.0) -> str:
657
+ """Stop a download process group on POSIX or process tree on Windows."""
658
+ return library_state.stop_process(saved, grace=grace)
659
+
660
+
661
+ class SpeechJobHandle:
662
+ """Throttled disk progress writer so ``speech status`` observes live downloads."""
663
+
664
+ def __init__(self, job: SpeechJob, state_dir: Path | None = None) -> None:
665
+ self.job = job
666
+ self.state_dir = state_dir
667
+ self._written = 0.0
668
+
669
+ def update(
670
+ self,
671
+ step: DownloadStep,
672
+ done_bytes: int,
673
+ total_bytes: int,
674
+ bytes_per_second: int = 0,
675
+ *,
676
+ source: str = "huggingface",
677
+ connections: int = 0,
678
+ ) -> None:
679
+ total = max(0, int(total_bytes))
680
+ done = min(max(0, int(done_bytes)), total)
681
+ changed = (
682
+ self.job["step"] != step
683
+ or self.job["source"] != source
684
+ or self.job["total_bytes"] != total
685
+ )
686
+ self.job["step"] = step
687
+ self.job["done_bytes"] = done
688
+ self.job["total_bytes"] = total
689
+ self.job["bytes_per_second"] = max(0, int(bytes_per_second))
690
+ self.job["source"] = source or "custom"
691
+ self.job["connections"] = max(0, int(connections))
692
+ now = time.monotonic()
693
+ if changed or now - self._written >= JOB_WRITE_EVERY_S or done >= total:
694
+ self._written = now
695
+ self.job["updated_at"] = utc_now()
696
+ with contextlib.suppress(OSError):
697
+ hosts.save_private(job_path(self.job["model"], self.state_dir), self.job)