@simplexai/localmodels-linux-x64 0.1.0-dev.36 → 0.1.0-dev.38

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 (134) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +132 -110
  3. package/kit.py +1 -0
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +9 -3
  6. package/modules/localmodels/bifrost_checks.py +9 -6
  7. package/modules/localmodels/bifrost_config.py +203 -0
  8. package/modules/localmodels/bifrost_datasheet.py +12 -2
  9. package/modules/localmodels/budget.py +13 -2
  10. package/modules/localmodels/catalog.json +137 -2
  11. package/modules/localmodels/catalog.py +70 -321
  12. package/modules/localmodels/catalog_add.py +2 -8
  13. package/modules/localmodels/catalog_recipes.py +352 -0
  14. package/modules/localmodels/cli_parser.py +4 -1
  15. package/modules/localmodels/console.py +5 -4
  16. package/modules/localmodels/contracts.py +13 -3
  17. package/modules/localmodels/debug_cli.py +158 -0
  18. package/modules/localmodels/debug_mode.py +727 -0
  19. package/modules/localmodels/debug_stub_server.py +192 -0
  20. package/modules/localmodels/decode_calibration.json +1 -1
  21. package/modules/localmodels/decode_calibration.py +34 -17
  22. package/modules/localmodels/gateway.py +21 -155
  23. package/modules/localmodels/gateway_accept.py +201 -0
  24. package/modules/localmodels/gateway_bifrost.py +30 -193
  25. package/modules/localmodels/gateway_cli.py +15 -6
  26. package/modules/localmodels/gateway_foundations.py +2 -4
  27. package/modules/localmodels/gateway_probe.py +0 -1
  28. package/modules/localmodels/gateway_server.py +2 -3
  29. package/modules/localmodels/gpu_specs.py +12 -0
  30. package/modules/localmodels/guard.py +2 -7
  31. package/modules/localmodels/harness.py +16 -129
  32. package/modules/localmodels/harness_cleanup.py +135 -0
  33. package/modules/localmodels/harness_gateway.py +16 -14
  34. package/modules/localmodels/harness_probe.py +12 -4
  35. package/modules/localmodels/hosts.py +25 -2
  36. package/modules/localmodels/http_local.py +59 -0
  37. package/modules/localmodels/install.py +23 -8
  38. package/modules/localmodels/library_gateway.py +20 -9
  39. package/modules/localmodels/library_jobs.py +125 -28
  40. package/modules/localmodels/library_model.py +10 -0
  41. package/modules/localmodels/library_pricing.py +29 -22
  42. package/modules/localmodels/library_serve.py +17 -1
  43. package/modules/localmodels/library_state.py +15 -2
  44. package/modules/localmodels/library_status.py +30 -0
  45. package/modules/localmodels/llm_rank.py +185 -39
  46. package/modules/localmodels/probe.py +108 -174
  47. package/modules/localmodels/process_identity.py +120 -154
  48. package/modules/localmodels/process_windows.py +86 -0
  49. package/modules/localmodels/recommend.py +6 -3
  50. package/modules/localmodels/recommend_cli.py +14 -6
  51. package/modules/localmodels/remote_ops.py +65 -0
  52. package/modules/localmodels/remote_ops_service.py +14 -2
  53. package/modules/localmodels/runtime_args.py +10 -3
  54. package/modules/localmodels/runtime_auth.py +5 -9
  55. package/modules/localmodels/runtime_cli.py +128 -129
  56. package/modules/localmodels/runtime_discovery.py +84 -0
  57. package/modules/localmodels/runtime_install.py +101 -0
  58. package/modules/localmodels/runtime_releases.py +302 -0
  59. package/modules/localmodels/search_server.py +5 -1
  60. package/modules/localmodels/service_stop.py +8 -108
  61. package/modules/localmodels/service_upgrade.py +394 -63
  62. package/modules/localmodels/services_cli.py +24 -14
  63. package/modules/localmodels/setup_inspection.py +97 -9
  64. package/modules/localmodels/setup_text.py +7 -0
  65. package/modules/localmodels/sizecalc.py +0 -1
  66. package/modules/localmodels/stack.py +45 -235
  67. package/modules/localmodels/stack_arena.py +732 -0
  68. package/modules/localmodels/stack_args.py +21 -12
  69. package/modules/localmodels/stack_auto.py +384 -3
  70. package/modules/localmodels/stack_aux_gpu.py +4 -3
  71. package/modules/localmodels/stack_capacity.py +138 -0
  72. package/modules/localmodels/stack_cleanup.py +9 -4
  73. package/modules/localmodels/stack_cli.py +288 -0
  74. package/modules/localmodels/stack_compose.py +63 -30
  75. package/modules/localmodels/stack_console.py +9 -6
  76. package/modules/localmodels/stack_hardware.py +95 -265
  77. package/modules/localmodels/stack_hardware_text.py +263 -0
  78. package/modules/localmodels/stack_journal.py +3 -9
  79. package/modules/localmodels/stack_ledger.py +48 -18
  80. package/modules/localmodels/stack_lifecycle.py +33 -312
  81. package/modules/localmodels/stack_llm_ram.py +16 -6
  82. package/modules/localmodels/stack_mcp.py +729 -0
  83. package/modules/localmodels/stack_memory.py +0 -2
  84. package/modules/localmodels/stack_picks.py +62 -15
  85. package/modules/localmodels/stack_plan.py +19 -1
  86. package/modules/localmodels/stack_preflight.py +11 -19
  87. package/modules/localmodels/stack_progress.py +9 -1
  88. package/modules/localmodels/stack_remove.py +373 -0
  89. package/modules/localmodels/stack_route.py +101 -17
  90. package/modules/localmodels/stack_run.py +29 -0
  91. package/modules/localmodels/stack_suite.py +21 -10
  92. package/modules/localmodels/stack_summary.py +14 -0
  93. package/modules/localmodels/stack_try.py +238 -24
  94. package/modules/localmodels/stack_try_client.py +53 -15
  95. package/modules/localmodels/stack_try_docs.py +2 -2
  96. package/modules/localmodels/stack_view.py +24 -171
  97. package/modules/localmodels/stack_view_access.py +114 -1
  98. package/modules/localmodels/stack_view_agent.py +3 -13
  99. package/modules/localmodels/stack_view_hub.py +9 -10
  100. package/modules/localmodels/stack_view_llm.py +1 -1
  101. package/modules/localmodels/stack_view_sandbox.py +2 -2
  102. package/modules/localmodels/stack_view_schema.py +183 -0
  103. package/modules/localmodels/stack_view_serve.py +7 -1
  104. package/modules/localmodels/stack_view_service.py +1 -2
  105. package/modules/localmodels/stack_view_text.py +13 -9
  106. package/modules/localmodels/stack_warm.py +48 -4
  107. package/modules/localmodels/stack_warm_store.py +517 -0
  108. package/modules/localmodels/tools.json +32 -18
  109. package/modules/localmodels/transport.py +38 -13
  110. package/modules/localmodels/tui.py +28 -4
  111. package/modules/localmodels/tui_dialogs.py +136 -0
  112. package/modules/localmodels/tui_modals.py +279 -0
  113. package/modules/localmodels/tui_screen.py +113 -154
  114. package/modules/localmodels/tui_views.py +134 -203
  115. package/modules/localmodels/web/index.html +510 -101
  116. package/modules/localmodels/web/sizecalc/app.js +363 -10
  117. package/modules/localmodels/web/sizecalc/page.html +27 -3
  118. package/modules/localmodels/web/view/fleet.html +11 -2
  119. package/modules/localmodels/web/view/fleet.js +191 -17
  120. package/modules/localmodels/web/view/i18n.js +3 -2
  121. package/modules/localmodels/web/view/index.html +1 -1
  122. package/modules/localmodels/web/view/nav.js +22 -3
  123. package/modules/localmodels/web/view/view.css +63 -18
  124. package/modules/localmodels/web/view/view.js +169 -32
  125. package/modules/localmodels/windows_job.py +69 -0
  126. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/METADATA +1 -1
  127. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/RECORD +128 -106
  128. package/package.json +1 -1
  129. package/tool.json +1 -1
  130. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  131. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/WHEEL +0 -0
  132. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/entry_points.txt +0 -0
  133. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/NOTICE +0 -0
  134. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,727 @@
1
+ """Debug modes (``simulate`` and ``tiny``) for fast, deterministic local-model testing and E2E.
2
+
3
+ Configured in priority order by:
4
+ 1. ``LOCALMODELS_DEBUG`` environment variable (``off``, ``simulate``, ``tiny``, JSON, or
5
+ ``simulate:download_ms=1500,vram_gb=24``);
6
+ 2. ``$LOCALMODELS_STATE/debug.json`` (per-instance configuration);
7
+ 3. ``~/.config/localmodels/debug.json`` or ``%APPDATA%/localmodels/debug.json`` (user-wide switch
8
+ picked up automatically by packaged desktop clients launched from Finder/Explorer).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import copy
15
+ import dataclasses
16
+ import json
17
+ import os
18
+ import signal
19
+ import socket
20
+ import subprocess
21
+ import sys
22
+ import time
23
+ import urllib.error
24
+ import urllib.request
25
+ from collections.abc import Callable
26
+ from dataclasses import dataclass, field
27
+ from pathlib import Path
28
+ from typing import Any, Literal, cast
29
+
30
+ from localmodels import hosts, process_identity
31
+
32
+ Mode = Literal["off", "simulate", "tiny"]
33
+ MODES: tuple[str, ...] = ("off", "simulate", "tiny")
34
+ GIB = 1 << 30
35
+ TINY_IDS = ("minicpm5-2b", "qwen3.5-2b")
36
+ DEBUG_ENV = "LOCALMODELS_DEBUG"
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class DebugConfig:
41
+ mode: Mode = "off"
42
+ source: str = "default"
43
+ download_ms: int = 2000
44
+ load_ms: int = 300
45
+ vram_gb: int | None = None
46
+ cache_dir: str | None = None
47
+ isolate_gateway: bool = True
48
+ offline_gateway: bool = False
49
+ fail: dict[str, str] = field(default_factory=dict)
50
+
51
+
52
+ def user_config_path() -> Path:
53
+ if sys.platform == "win32" and (appdata := os.environ.get("APPDATA", "").strip()):
54
+ return Path(appdata) / "localmodels" / "debug.json"
55
+ xdg = os.environ.get("XDG_CONFIG_HOME", "").strip()
56
+ base = Path(xdg).expanduser() if xdg else Path.home() / ".config"
57
+ return base / "localmodels" / "debug.json"
58
+
59
+
60
+ def state_config_path() -> Path:
61
+ return hosts.state_dir() / "debug.json"
62
+
63
+
64
+ def default_cache_dir() -> Path:
65
+ if sys.platform == "win32" and (local := os.environ.get("LOCALAPPDATA", "").strip()):
66
+ return Path(local) / "localmodels" / "artifacts"
67
+ xdg = os.environ.get("XDG_CACHE_HOME", "").strip()
68
+ base = Path(xdg).expanduser() if xdg else Path.home() / ".cache"
69
+ return base / "localmodels" / "artifacts"
70
+
71
+
72
+ def _parse_mapping(data: dict[str, Any], source: str) -> DebugConfig:
73
+ raw_mode = str(data.get("mode") or "off").strip().lower()
74
+ if raw_mode in ("0", "false", "none", "disabled"):
75
+ raw_mode = "off"
76
+ if raw_mode not in MODES:
77
+ raise ValueError(f"unsupported debug mode {raw_mode!r} in {source}")
78
+ mode: Mode = raw_mode # type: ignore[assignment]
79
+ vram_raw = data.get("vram_gb")
80
+ vram_gb = int(vram_raw) if isinstance(vram_raw, int | float | str) and str(vram_raw) else None
81
+ fail_raw = data.get("fail")
82
+ fail = {str(k): str(v) for k, v in fail_raw.items()} if isinstance(fail_raw, dict) else {}
83
+ cache_raw = data.get("cache_dir")
84
+ return DebugConfig(
85
+ mode=mode,
86
+ source=source,
87
+ download_ms=max(0, int(data.get("download_ms", 2000))),
88
+ load_ms=max(0, int(data.get("load_ms", 300))),
89
+ vram_gb=vram_gb if vram_gb and vram_gb > 0 else None,
90
+ cache_dir=str(cache_raw).strip() if cache_raw else None,
91
+ isolate_gateway=bool(data.get("isolate_gateway", True)),
92
+ offline_gateway=bool(data.get("offline_gateway", False)),
93
+ fail=fail,
94
+ )
95
+
96
+
97
+ def _parse_env(raw: str) -> DebugConfig:
98
+ text = raw.strip()
99
+ if text.startswith("{"):
100
+ loaded = json.loads(text)
101
+ if not isinstance(loaded, dict):
102
+ raise ValueError("LOCALMODELS_DEBUG JSON must be an object")
103
+ return _parse_mapping(loaded, f"env:{DEBUG_ENV}")
104
+ head, _, rest = text.partition(":")
105
+ mode_word = head.strip().lower()
106
+ if mode_word in ("0", "false", "off", "none", "disabled"):
107
+ return DebugConfig(mode="off", source=f"env:{DEBUG_ENV}")
108
+ data: dict[str, Any] = {"mode": mode_word}
109
+ fail: dict[str, str] = {}
110
+ if rest:
111
+ for item in rest.split(","):
112
+ key, eq, val = item.partition("=")
113
+ key, val = key.strip(), val.strip()
114
+ if not eq or not key:
115
+ continue
116
+ if key == "fail":
117
+ step, _, reason = val.partition("@")
118
+ if step and reason:
119
+ fail[step] = reason
120
+ elif key in ("download_ms", "load_ms", "vram_gb"):
121
+ data[key] = int(val)
122
+ elif key in ("isolate_gateway", "offline_gateway"):
123
+ data[key] = val.lower() not in ("0", "false", "no", "off")
124
+ elif key == "cache_dir":
125
+ data[key] = val
126
+ if fail:
127
+ data["fail"] = fail
128
+ return _parse_mapping(data, f"env:{DEBUG_ENV}")
129
+
130
+
131
+ def resolve_config() -> DebugConfig:
132
+ if env_val := os.environ.get(DEBUG_ENV, "").strip():
133
+ with contextlib.suppress(ValueError):
134
+ return _parse_env(env_val)
135
+ candidates: list[tuple[str, Path]] = [("state", state_config_path())]
136
+ if (
137
+ "PYTEST_CURRENT_TEST" not in os.environ
138
+ or os.environ.get("LOCALMODELS_DEBUG_USER_CONFIG") == "1"
139
+ ):
140
+ candidates.append(("user", user_config_path()))
141
+ for label, path in candidates:
142
+ if path.is_file():
143
+ with contextlib.suppress(OSError, ValueError):
144
+ loaded = json.loads(path.read_text(encoding="utf-8"))
145
+ if isinstance(loaded, dict):
146
+ return _parse_mapping(loaded, f"{label}:{path}")
147
+ return DebugConfig()
148
+
149
+
150
+ # --------------------------------------------------------------------------- gateway isolation
151
+
152
+
153
+ def _port_listening(addr: str) -> bool:
154
+ host, _, port_str = addr.rpartition(":")
155
+ if not host or not port_str.isdigit():
156
+ return False
157
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
158
+ sock.settimeout(0.2)
159
+ return sock.connect_ex((host, int(port_str))) == 0
160
+
161
+
162
+ def _free_loopback_addr() -> str:
163
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
164
+ sock.bind(("127.0.0.1", 0))
165
+ return f"127.0.0.1:{sock.getsockname()[1]}"
166
+
167
+
168
+ def _ensure_isolated_gateway() -> None:
169
+ root = hosts.state_dir().resolve() / "gateway"
170
+ tools = root / "tools"
171
+ bifrost = root / "bifrost"
172
+ root.mkdir(parents=True, exist_ok=True)
173
+ if sys.platform != "win32":
174
+ root.chmod(0o700)
175
+ os.environ.setdefault("LOCALMODELS_TOOLS_DIR", str(tools))
176
+ os.environ.setdefault("LOCALMODELS_BIFROST_DIR", str(bifrost))
177
+ if not os.environ.get("LOCALMODELS_BIFROST_ADDR", "").strip():
178
+ addr_file = root / "bifrost.addr"
179
+ saved = addr_file.read_text(encoding="utf-8").strip() if addr_file.is_file() else ""
180
+ owned = hosts.load_owned(str(tools))["gateway"].get("bifrost")
181
+ if saved and (owned or not _port_listening(saved)):
182
+ os.environ["LOCALMODELS_BIFROST_ADDR"] = saved
183
+ else:
184
+ default_addr = "127.0.0.1:47711"
185
+ chosen = (
186
+ default_addr
187
+ if (owned and owned["addr"] == default_addr) or not _port_listening(default_addr)
188
+ else _free_loopback_addr()
189
+ )
190
+ addr_file.write_text(chosen + "\n", encoding="utf-8")
191
+ os.environ["LOCALMODELS_BIFROST_ADDR"] = chosen
192
+
193
+
194
+ # --------------------------------------------------------------------------- tiny mode
195
+
196
+
197
+ def _install_tiny_mode(config: DebugConfig) -> None:
198
+ from localmodels import catalog as cat
199
+
200
+ cache_path = Path(config.cache_dir).expanduser() if config.cache_dir else default_cache_dir()
201
+ os.environ.setdefault("LOCALMODELS_CACHE_DIR", str(cache_path))
202
+ original_load = cat.load_catalog_file
203
+
204
+ def load_with_tiny(path: Path = cat.CATALOG_PATH) -> tuple[cat.CatalogEntry, ...]:
205
+ entries = original_load(path)
206
+ if path != cat.CATALOG_PATH:
207
+ return entries
208
+ promoted = []
209
+ for entry in entries:
210
+ if entry.id in TINY_IDS:
211
+ promoted.append(
212
+ dataclasses.replace(
213
+ entry,
214
+ status="validated",
215
+ validated_on=("linux", "darwin", "win32"),
216
+ )
217
+ )
218
+ else:
219
+ promoted.append(entry)
220
+ return tuple(promoted)
221
+
222
+ cat.load_catalog_file = load_with_tiny
223
+
224
+
225
+ # --------------------------------------------------------------------------- simulate mode
226
+
227
+
228
+ def _synthetic_facts(real: dict[str, Any] | None, vram_gb: int) -> dict[str, Any]:
229
+ total = vram_gb * GIB
230
+ base_ram = max(64 * GIB, total * 2)
231
+ is_mac = sys.platform == "darwin"
232
+ platform = "darwin" if is_mac else ("win32" if sys.platform == "win32" else "linux")
233
+ arch = "arm64" if is_mac else "x64"
234
+ template_os = (real or {}).get("os") or {
235
+ "system": "Darwin" if is_mac else ("Windows" if platform == "win32" else "Linux"),
236
+ "release": "6.8",
237
+ "distro": "Simulated Host",
238
+ }
239
+ doc: dict[str, Any] = {
240
+ "schema": "localmodels.host-facts/v1",
241
+ "collected_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
242
+ "hostname": (real or {}).get("hostname") or socket.gethostname() or "simulated-host",
243
+ "user": os.environ.get("USER") or os.environ.get("USERNAME") or "simulated",
244
+ "platform": platform,
245
+ "arch": arch,
246
+ "os": template_os,
247
+ "python": f"{sys.version_info.major}.{sys.version_info.minor}",
248
+ "cpu": (real or {}).get("cpu") or {"model": "Simulated CPU", "cores": 16, "threads": 16},
249
+ "ram": {"total_bytes": base_ram, "available_bytes": int(base_ram * 0.85)},
250
+ "gpu_vendor_class": "apple_silicon" if is_mac else "nvidia",
251
+ "nvidia": None if is_mac else {"cuda_version": "12.8"},
252
+ "gpus": (
253
+ []
254
+ if is_mac
255
+ else [
256
+ {
257
+ "index": 0,
258
+ "uuid": "GPU-simulated-0",
259
+ "name": f"Simulated RTX {vram_gb}GB",
260
+ "vendor": "nvidia",
261
+ "pci_bus_id": "0",
262
+ "pci_device_id": None,
263
+ "total_bytes": total,
264
+ "free_bytes": total,
265
+ "used_bytes": 0,
266
+ "util_percent": 0,
267
+ "driver_version": "570.00",
268
+ }
269
+ ]
270
+ ),
271
+ "cuda_pool": None,
272
+ "llama_servers": [],
273
+ "engines": [],
274
+ "disk": {
275
+ "path": str(hosts.state_dir()),
276
+ "total_bytes": 2000 * GIB,
277
+ "free_bytes": 1000 * GIB,
278
+ },
279
+ "service_manager": {"kind": "nohup", "linger": False},
280
+ "errors": [],
281
+ }
282
+ if is_mac:
283
+ doc["metal"] = {
284
+ "name": f"Simulated Apple Silicon ({vram_gb}GB)",
285
+ "recommended_max_working_set_bytes": total,
286
+ "unified_memory": True,
287
+ }
288
+ return doc
289
+
290
+
291
+ def _apply_simulated_occupancy(facts: dict[str, Any]) -> dict[str, Any]:
292
+ from localmodels import library_state
293
+
294
+ adjusted = copy.deepcopy(facts)
295
+ adjusted.setdefault("disk", {})["free_bytes"] = max(
296
+ int(adjusted.get("disk", {}).get("free_bytes") or 0), 1000 * GIB
297
+ )
298
+ held_by_pool: dict[str, int] = {}
299
+ with contextlib.suppress(Exception):
300
+ for record in library_state.records():
301
+ if record.get("state") == "loaded":
302
+ pool = str(record.get("pool") or "")
303
+ held_by_pool[pool] = held_by_pool.get(pool, 0) + int(
304
+ record.get("memory_bytes") or 0
305
+ )
306
+ for gpu in adjusted.get("gpus") or []:
307
+ extra = held_by_pool.get(f"gpu:{gpu['index']}", 0)
308
+ if extra > 0:
309
+ gpu["free_bytes"] = max(0, int(gpu["free_bytes"]) - extra)
310
+ gpu["used_bytes"] = min(int(gpu["total_bytes"]), int(gpu.get("used_bytes", 0)) + extra)
311
+ if adjusted.get("metal") and (extra := held_by_pool.get("unified", 0)) > 0:
312
+ ram = adjusted["ram"]
313
+ ram["available_bytes"] = max(0, int(ram["available_bytes"]) - extra)
314
+ elif (extra := held_by_pool.get("system", 0)) > 0:
315
+ ram = adjusted["ram"]
316
+ ram["available_bytes"] = max(0, int(ram["available_bytes"]) - extra)
317
+ return adjusted
318
+
319
+
320
+ def _sim_dir() -> Path:
321
+ path = hosts.state_dir() / "simulate"
322
+ path.mkdir(parents=True, exist_ok=True)
323
+ return path
324
+
325
+
326
+ def _pid_alive(pid: int) -> bool:
327
+ return process_identity.alive(pid)
328
+
329
+
330
+ def _http_healthy(port: int, timeout: float = 0.5) -> bool:
331
+ try:
332
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=timeout) as resp:
333
+ return int(getattr(resp, "status", 200)) == 200
334
+ except (urllib.error.URLError, OSError, ValueError):
335
+ return False
336
+
337
+
338
+ def _stop_sim_service(service_name: str) -> None:
339
+ pid_file = _sim_dir() / f"{service_name}.pid"
340
+ if not pid_file.is_file():
341
+ return
342
+ with contextlib.suppress(OSError, ValueError):
343
+ pid = int(pid_file.read_text(encoding="utf-8").strip())
344
+ if _pid_alive(pid):
345
+ os.kill(pid, signal.SIGTERM)
346
+ deadline = time.monotonic() + 2.0
347
+ while time.monotonic() < deadline and _pid_alive(pid):
348
+ time.sleep(0.05)
349
+ if _pid_alive(pid) and hasattr(signal, "SIGKILL"):
350
+ os.kill(pid, signal.SIGKILL)
351
+ pid_file.unlink(missing_ok=True)
352
+
353
+
354
+ class SimulatedExecutor:
355
+ """Fast local executor: streams authentic progress ticks and runs lightweight stub servers."""
356
+
357
+ def __init__(self, config: DebugConfig) -> None:
358
+ self.config = config
359
+
360
+ def _engine(self, params: dict[str, Any]) -> dict[str, object]:
361
+ directory = Path(os.path.expanduser(str(params["dir"])))
362
+ directory.mkdir(parents=True, exist_ok=True)
363
+ binary = directory / str(params.get("binary") or "llama-server")
364
+ if not binary.exists():
365
+ binary.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
366
+ with contextlib.suppress(OSError):
367
+ binary.chmod(0o755)
368
+ return {"event": "result", "binary": str(binary), "reused": True}
369
+
370
+ def _download_one(
371
+ self,
372
+ f: dict[str, Any],
373
+ steps: int,
374
+ step_sleep: float,
375
+ on_event: Callable[[dict[str, object]], None] | None,
376
+ ) -> None:
377
+ dest = Path(os.path.expanduser(str(f["dest"])))
378
+ dest.parent.mkdir(parents=True, exist_ok=True)
379
+ marker = Path(str(dest) + ".sha256")
380
+ size = int(f["size_bytes"])
381
+ sha = str(f["sha256"])
382
+ if dest.exists() and marker.is_file() and marker.read_text(encoding="utf-8").strip() == sha:
383
+ if on_event is not None:
384
+ on_event(
385
+ {
386
+ "event": "progress",
387
+ "phase": "download",
388
+ "file": dest.name,
389
+ "done": size,
390
+ "total": size,
391
+ "bytes_per_s": max(1, size),
392
+ }
393
+ )
394
+ return
395
+ part = Path(str(dest) + ".part")
396
+ part.write_bytes(b"sim")
397
+ rate = int(size / max(0.05, self.config.download_ms / 1000.0))
398
+ for i in range(1, steps + 1):
399
+ if step_sleep > 0:
400
+ time.sleep(step_sleep)
401
+ done = size if i == steps else (size * i) // steps
402
+ if on_event is not None:
403
+ on_event(
404
+ {
405
+ "event": "progress",
406
+ "phase": "download",
407
+ "file": dest.name,
408
+ "done": done,
409
+ "total": size,
410
+ "bytes_per_s": rate,
411
+ }
412
+ )
413
+ part.unlink(missing_ok=True)
414
+ with dest.open("wb") as handle:
415
+ os.truncate(handle.fileno(), size)
416
+ marker.write_text(sha + "\n", encoding="utf-8")
417
+
418
+ def _download(
419
+ self,
420
+ params: dict[str, Any],
421
+ on_event: Callable[[dict[str, object]], None] | None,
422
+ ) -> dict[str, object]:
423
+ files = list(params.get("files") or [])
424
+ steps = 10 if self.config.download_ms > 0 else 1
425
+ step_sleep = (self.config.download_ms / 1000.0) / max(1, steps * max(1, len(files)))
426
+ for f in files:
427
+ self._download_one(f, steps, step_sleep, on_event)
428
+ return {"event": "result", "files": len(files)}
429
+
430
+ def _install(self, params: dict[str, Any]) -> dict[str, object]:
431
+ deploy_dir = Path(os.path.expanduser(str(params["deploy_dir"])))
432
+ deploy_dir.mkdir(parents=True, exist_ok=True)
433
+ if "api_key" in params:
434
+ (deploy_dir / "api-key").write_text(str(params["api_key"]), encoding="utf-8")
435
+ model_name = ((params.get("record") or {}).get("model") or {}).get("model_id") or str(
436
+ params.get("service") or "simulated-model"
437
+ )
438
+ spec = {
439
+ "service": str(params["service"]),
440
+ "port": int(params["port"]),
441
+ "model": str(model_name),
442
+ }
443
+ (deploy_dir / "sim-service.json").write_text(
444
+ json.dumps(spec, indent=2) + "\n", encoding="utf-8"
445
+ )
446
+ return {"event": "result"}
447
+
448
+ def _start(self, params: dict[str, Any]) -> tuple[dict[str, object], bool]:
449
+ deploy_dir = Path(os.path.expanduser(str(params["deploy_dir"])))
450
+ service_name = str(params["service"])
451
+ port = int(params["port"])
452
+ spec_file = deploy_dir / "sim-service.json"
453
+ model_name = service_name
454
+ if spec_file.is_file():
455
+ with contextlib.suppress(OSError, ValueError):
456
+ model_name = str(
457
+ json.loads(spec_file.read_text(encoding="utf-8")).get("model") or service_name
458
+ )
459
+ _stop_sim_service(service_name)
460
+ module_root = str(Path(__file__).resolve().parent.parent)
461
+ env = {
462
+ **os.environ,
463
+ "PYTHONPATH": module_root,
464
+ "PYTHONNOUSERSITE": "1",
465
+ "PYTHONDONTWRITEBYTECODE": "1",
466
+ }
467
+ proc = subprocess.Popen(
468
+ [
469
+ sys.executable,
470
+ "-P",
471
+ "-s",
472
+ "-m",
473
+ "localmodels.debug_stub_server",
474
+ "--port",
475
+ str(port),
476
+ "--model",
477
+ model_name,
478
+ ],
479
+ env=env,
480
+ stdin=subprocess.DEVNULL,
481
+ stdout=subprocess.DEVNULL,
482
+ stderr=subprocess.DEVNULL,
483
+ start_new_session=sys.platform != "win32",
484
+ )
485
+ (_sim_dir() / f"{service_name}.pid").write_text(f"{proc.pid}\n", encoding="utf-8")
486
+ deadline = time.monotonic() + 5.0
487
+ while time.monotonic() < deadline:
488
+ if _http_healthy(port, timeout=0.2):
489
+ return {"event": "result", "started": True}, True
490
+ if proc.poll() is not None:
491
+ break
492
+ time.sleep(0.05)
493
+ _stop_sim_service(service_name)
494
+ return {"event": "error", "message": f"simulated server on {port} did not start"}, False
495
+
496
+ def _status(self, params: dict[str, Any]) -> dict[str, object]:
497
+ service_name = str(params["service"])
498
+ port = int(params["port"])
499
+ pid_file = _sim_dir() / f"{service_name}.pid"
500
+ pid = int(pid_file.read_text(encoding="utf-8").strip()) if pid_file.is_file() else 0
501
+ if _pid_alive(pid) and _http_healthy(port, timeout=0.3):
502
+ return {"event": "result", "state": "active", "health": "ok"}
503
+ return {"event": "result", "state": "inactive", "health": "not running, not probed"}
504
+
505
+ def run_action(
506
+ self,
507
+ action: str,
508
+ params: dict[str, Any],
509
+ *,
510
+ timeout: float = 60,
511
+ on_event: Callable[[dict[str, object]], None] | None = None,
512
+ ) -> tuple[dict[str, object], Any]:
513
+ from localmodels.transport import Result
514
+
515
+ if reason := self.config.fail.get(action):
516
+ return {"event": "error", "message": reason}, Result(1, "", reason)
517
+ if action == "engine":
518
+ return self._engine(params), Result(0, "", "")
519
+ if action == "download":
520
+ return self._download(params, on_event), Result(0, "", "")
521
+ if action == "install":
522
+ return self._install(params), Result(0, "", "")
523
+ if action == "start":
524
+ outcome, ok = self._start(params)
525
+ return outcome, Result(0 if ok else 1, "", "" if ok else str(outcome.get("message")))
526
+ if action == "verify":
527
+ if on_event is not None:
528
+ on_event({"event": "progress", "phase": "loading"})
529
+ if _http_healthy(int(params["port"]), timeout=1.0):
530
+ return {"event": "result", "health": "ok"}, Result(0, "", "")
531
+ return {"event": "error", "message": "health check failed"}, Result(1, "", "failed")
532
+ if action == "status":
533
+ return self._status(params), Result(0, "", "")
534
+ if action == "stop":
535
+ _stop_sim_service(str(params["service"]))
536
+ return {"event": "result", "stopped": True}, Result(0, "", "")
537
+ if action == "remove":
538
+ _stop_sim_service(str(params["service"]))
539
+ return {"event": "result", "removed": True, "purged": 0, "kept": []}, Result(0, "", "")
540
+ return {"event": "result"}, Result(0, "", "")
541
+
542
+
543
+ def _install_direct_pi_gateway() -> None:
544
+ """Offline fallback for ``simulate`` when Bifrost is unavailable or ``offline_gateway`` is set."""
545
+ from localmodels import bifrost_models, library_gateway
546
+ from localmodels import catalog as cat
547
+ from localmodels.library_model import display_name, split_id
548
+ from localmodels.library_state import Registration
549
+
550
+ original_register = library_gateway.register
551
+ original_unregister = library_gateway.unregister
552
+
553
+ def direct_register(
554
+ model: str,
555
+ entry: cat.CatalogEntry,
556
+ plan: Any,
557
+ key: str,
558
+ facts: Any,
559
+ *,
560
+ stack_provider: str | None = None,
561
+ ) -> Registration:
562
+ added = library_gateway.planned(model, plan, stack_provider=stack_provider)
563
+ levels = list(entry.reasoning_efforts or cat.EFFORT_LEVELS)
564
+ context = int(str(plan["launch"].get("window") or 0)) or bifrost_models.DEFAULT_CONTEXT
565
+ facts_: bifrost_models.LlmFacts = {
566
+ "display": display_name(entry.display_name, split_id(model)[1]),
567
+ "context": context,
568
+ "efforts": levels,
569
+ "defaultEffort": bifrost_models.default_effort(levels),
570
+ }
571
+ base_url = str(plan["endpoint"]["base_url"]).removesuffix("/v1").rstrip("/")
572
+ served = str(plan["endpoint"]["model"])
573
+ pi_entry = bifrost_models.pi_provider(facts_, served, base_url)["models"][0]
574
+ with library_gateway.gateway_locked():
575
+ library_gateway._pi_add(added["pi_provider"], pi_entry, base_url)
576
+ return {**added, "model": served, "pi_model": f"{added['pi_provider']}/{served}"}
577
+
578
+ def direct_unregister(registration: Registration) -> None:
579
+ with library_gateway.gateway_locked():
580
+ library_gateway._pi_drop(registration["pi_provider"], registration["model"])
581
+
582
+ def register_with_fallback(
583
+ model: str,
584
+ entry: cat.CatalogEntry,
585
+ plan: Any,
586
+ key: str,
587
+ facts: Any,
588
+ *,
589
+ stack_provider: str | None = None,
590
+ ) -> Registration:
591
+ try:
592
+ return original_register(model, entry, plan, key, facts, stack_provider=stack_provider)
593
+ except Exception:
594
+ return direct_register(model, entry, plan, key, facts, stack_provider=stack_provider)
595
+
596
+ def unregister_with_fallback(registration: Registration) -> None:
597
+ if "/" not in registration.get("model", ""):
598
+ direct_unregister(registration)
599
+ return
600
+ with contextlib.suppress(Exception):
601
+ original_unregister(registration)
602
+
603
+ library_gateway.register = register_with_fallback
604
+ library_gateway.unregister = unregister_with_fallback
605
+
606
+
607
+ def _empty_services() -> dict[str, Any]:
608
+ return {
609
+ "compute_processes": [],
610
+ "systemd_units": [],
611
+ "containers": [],
612
+ "ports": [],
613
+ "unknown": {},
614
+ }
615
+
616
+
617
+ def _install_simulate_mode(config: DebugConfig) -> None:
618
+ from localmodels import (
619
+ app,
620
+ library_gateway,
621
+ library_pricing,
622
+ library_serve,
623
+ probe,
624
+ service_probe,
625
+ stack_warm,
626
+ )
627
+
628
+ if config.vram_gb is not None and os.environ.get("CUDA_VISIBLE_DEVICES") == "":
629
+ os.environ.pop("CUDA_VISIBLE_DEVICES", None)
630
+ original_probe = app.probe
631
+ original_collect = probe.collect
632
+ executor = SimulatedExecutor(config)
633
+
634
+ def _simulated_local_facts(real_loader: Callable[[], Any]) -> Any:
635
+ real: dict[str, Any] | None = None
636
+ if config.vram_gb is None:
637
+ with contextlib.suppress(Exception):
638
+ probed = real_loader()
639
+ if probed and (probed.get("gpus") or probed.get("metal")):
640
+ real = copy.deepcopy(dict(probed))
641
+ real["llama_servers"] = []
642
+ real["services"] = _empty_services()
643
+ facts = real if real is not None else _synthetic_facts(real, config.vram_gb or 24)
644
+ facts["services"] = _empty_services()
645
+ return _apply_simulated_occupancy(facts)
646
+
647
+ def simulated_probe(dev_id: str, **kwargs: Any) -> Any:
648
+ if dev_id != hosts.LOCAL_ID:
649
+ return original_probe(dev_id, **kwargs)
650
+ return _simulated_local_facts(lambda: original_probe(dev_id, **kwargs))
651
+
652
+ def simulated_collect(*args: Any, **kwargs: Any) -> Any:
653
+ return _simulated_local_facts(lambda: original_collect(*args, **kwargs))
654
+
655
+ def simulated_base_free(base_dir: str) -> int:
656
+ _ = base_dir
657
+ return 1024 if "disk" in config.fail else 1000 * GIB
658
+
659
+ app.probe = simulated_probe
660
+ probe.collect = simulated_collect
661
+ service_probe.collect = lambda *_a, **_kw: _empty_services()
662
+ library_pricing.base_free = simulated_base_free
663
+ library_serve._port = lambda facts: int(_free_loopback_addr().rsplit(":", 1)[1])
664
+ cast(Any, hosts).executor = lambda _dev: executor
665
+
666
+ def simulated_warm(_part: Any) -> dict[str, Any]:
667
+ if config.load_ms > 0:
668
+ time.sleep(config.load_ms / 1000.0)
669
+ return {"decode_tok_s": 120.0, "ok": True}
670
+
671
+ cast(Any, stack_warm).warm_llm = simulated_warm
672
+ if config.offline_gateway:
673
+ from localmodels import bifrost_models
674
+ from localmodels import catalog as cat
675
+ from localmodels.library_model import display_name, split_id
676
+ from localmodels.library_state import Registration
677
+
678
+ def offline_only_register(
679
+ model: str,
680
+ entry: cat.CatalogEntry,
681
+ plan: Any,
682
+ key: str,
683
+ facts: Any,
684
+ *,
685
+ stack_provider: str | None = None,
686
+ ) -> Registration:
687
+ _ = key, facts
688
+ added = library_gateway.planned(model, plan, stack_provider=stack_provider)
689
+ levels = list(entry.reasoning_efforts or cat.EFFORT_LEVELS)
690
+ context = int(str(plan["launch"].get("window") or 0)) or bifrost_models.DEFAULT_CONTEXT
691
+ facts_: bifrost_models.LlmFacts = {
692
+ "display": display_name(entry.display_name, split_id(model)[1]),
693
+ "context": context,
694
+ "efforts": levels,
695
+ "defaultEffort": bifrost_models.default_effort(levels),
696
+ }
697
+ base_url = str(plan["endpoint"]["base_url"]).removesuffix("/v1").rstrip("/")
698
+ served = str(plan["endpoint"]["model"])
699
+ pi_entry = bifrost_models.pi_provider(facts_, served, base_url)["models"][0]
700
+ with library_gateway.gateway_locked():
701
+ library_gateway._pi_add(added["pi_provider"], pi_entry, base_url)
702
+ return {**added, "model": served, "pi_model": f"{added['pi_provider']}/{served}"}
703
+
704
+ library_gateway.register = offline_only_register
705
+ else:
706
+ _install_direct_pi_gateway()
707
+
708
+
709
+ _ACTIVE: DebugConfig | None = None
710
+
711
+
712
+ def activate() -> DebugConfig:
713
+ """Apply the configured debug mode once per process; ``off`` changes nothing."""
714
+ global _ACTIVE
715
+ if _ACTIVE is not None:
716
+ return _ACTIVE
717
+ config = resolve_config()
718
+ _ACTIVE = config
719
+ if config.mode == "off":
720
+ return config
721
+ if config.isolate_gateway:
722
+ _ensure_isolated_gateway()
723
+ if config.mode == "tiny":
724
+ _install_tiny_mode(config)
725
+ elif config.mode == "simulate":
726
+ _install_simulate_mode(config)
727
+ return config