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

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 (121) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +119 -98
  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_config.py +188 -0
  7. package/modules/localmodels/budget.py +13 -2
  8. package/modules/localmodels/catalog.py +51 -320
  9. package/modules/localmodels/catalog_add.py +2 -8
  10. package/modules/localmodels/catalog_recipes.py +321 -0
  11. package/modules/localmodels/cli_parser.py +4 -1
  12. package/modules/localmodels/console.py +5 -4
  13. package/modules/localmodels/contracts.py +13 -3
  14. package/modules/localmodels/debug_cli.py +158 -0
  15. package/modules/localmodels/debug_mode.py +727 -0
  16. package/modules/localmodels/debug_stub_server.py +192 -0
  17. package/modules/localmodels/decode_calibration.json +1 -1
  18. package/modules/localmodels/decode_calibration.py +34 -17
  19. package/modules/localmodels/gateway.py +21 -155
  20. package/modules/localmodels/gateway_accept.py +201 -0
  21. package/modules/localmodels/gateway_bifrost.py +19 -184
  22. package/modules/localmodels/gateway_cli.py +11 -4
  23. package/modules/localmodels/gateway_foundations.py +2 -4
  24. package/modules/localmodels/gateway_probe.py +0 -1
  25. package/modules/localmodels/gateway_server.py +2 -3
  26. package/modules/localmodels/gpu_specs.py +12 -0
  27. package/modules/localmodels/guard.py +2 -7
  28. package/modules/localmodels/harness.py +16 -129
  29. package/modules/localmodels/harness_cleanup.py +135 -0
  30. package/modules/localmodels/harness_gateway.py +16 -14
  31. package/modules/localmodels/harness_probe.py +12 -4
  32. package/modules/localmodels/hosts.py +25 -2
  33. package/modules/localmodels/http_local.py +59 -0
  34. package/modules/localmodels/install.py +23 -8
  35. package/modules/localmodels/library_gateway.py +9 -9
  36. package/modules/localmodels/library_jobs.py +76 -27
  37. package/modules/localmodels/library_serve.py +12 -1
  38. package/modules/localmodels/library_state.py +6 -1
  39. package/modules/localmodels/llm_rank.py +102 -9
  40. package/modules/localmodels/probe.py +108 -174
  41. package/modules/localmodels/process_identity.py +109 -154
  42. package/modules/localmodels/process_windows.py +86 -0
  43. package/modules/localmodels/recommend.py +1 -1
  44. package/modules/localmodels/recommend_cli.py +14 -6
  45. package/modules/localmodels/remote_ops.py +65 -0
  46. package/modules/localmodels/remote_ops_service.py +14 -2
  47. package/modules/localmodels/runtime_args.py +10 -3
  48. package/modules/localmodels/runtime_auth.py +5 -9
  49. package/modules/localmodels/runtime_cli.py +128 -129
  50. package/modules/localmodels/runtime_discovery.py +84 -0
  51. package/modules/localmodels/runtime_install.py +101 -0
  52. package/modules/localmodels/runtime_releases.py +302 -0
  53. package/modules/localmodels/service_stop.py +8 -108
  54. package/modules/localmodels/service_upgrade.py +394 -63
  55. package/modules/localmodels/services_cli.py +24 -14
  56. package/modules/localmodels/setup_inspection.py +97 -9
  57. package/modules/localmodels/setup_text.py +7 -0
  58. package/modules/localmodels/sizecalc.py +0 -1
  59. package/modules/localmodels/stack.py +14 -221
  60. package/modules/localmodels/stack_arena.py +732 -0
  61. package/modules/localmodels/stack_args.py +15 -9
  62. package/modules/localmodels/stack_auto.py +384 -3
  63. package/modules/localmodels/stack_aux_gpu.py +4 -3
  64. package/modules/localmodels/stack_capacity.py +138 -0
  65. package/modules/localmodels/stack_cleanup.py +9 -4
  66. package/modules/localmodels/stack_cli.py +286 -0
  67. package/modules/localmodels/stack_compose.py +58 -25
  68. package/modules/localmodels/stack_console.py +9 -6
  69. package/modules/localmodels/stack_hardware.py +92 -263
  70. package/modules/localmodels/stack_hardware_text.py +263 -0
  71. package/modules/localmodels/stack_journal.py +3 -9
  72. package/modules/localmodels/stack_ledger.py +48 -18
  73. package/modules/localmodels/stack_lifecycle.py +33 -312
  74. package/modules/localmodels/stack_mcp.py +729 -0
  75. package/modules/localmodels/stack_memory.py +0 -2
  76. package/modules/localmodels/stack_picks.py +59 -12
  77. package/modules/localmodels/stack_plan.py +19 -1
  78. package/modules/localmodels/stack_preflight.py +11 -19
  79. package/modules/localmodels/stack_remove.py +373 -0
  80. package/modules/localmodels/stack_route.py +101 -17
  81. package/modules/localmodels/stack_suite.py +11 -7
  82. package/modules/localmodels/stack_summary.py +14 -0
  83. package/modules/localmodels/stack_try.py +238 -24
  84. package/modules/localmodels/stack_try_client.py +53 -15
  85. package/modules/localmodels/stack_try_docs.py +2 -2
  86. package/modules/localmodels/stack_view.py +24 -171
  87. package/modules/localmodels/stack_view_access.py +114 -1
  88. package/modules/localmodels/stack_view_agent.py +3 -13
  89. package/modules/localmodels/stack_view_hub.py +9 -10
  90. package/modules/localmodels/stack_view_llm.py +1 -1
  91. package/modules/localmodels/stack_view_sandbox.py +2 -2
  92. package/modules/localmodels/stack_view_schema.py +183 -0
  93. package/modules/localmodels/stack_view_serve.py +7 -1
  94. package/modules/localmodels/stack_view_service.py +1 -2
  95. package/modules/localmodels/stack_view_text.py +13 -9
  96. package/modules/localmodels/stack_warm.py +3 -0
  97. package/modules/localmodels/stack_warm_store.py +517 -0
  98. package/modules/localmodels/tui.py +28 -4
  99. package/modules/localmodels/tui_dialogs.py +136 -0
  100. package/modules/localmodels/tui_modals.py +279 -0
  101. package/modules/localmodels/tui_screen.py +113 -154
  102. package/modules/localmodels/tui_views.py +134 -203
  103. package/modules/localmodels/web/index.html +510 -101
  104. package/modules/localmodels/web/sizecalc/app.js +363 -10
  105. package/modules/localmodels/web/sizecalc/page.html +27 -3
  106. package/modules/localmodels/web/view/fleet.html +11 -2
  107. package/modules/localmodels/web/view/fleet.js +191 -17
  108. package/modules/localmodels/web/view/i18n.js +3 -2
  109. package/modules/localmodels/web/view/index.html +1 -1
  110. package/modules/localmodels/web/view/nav.js +22 -3
  111. package/modules/localmodels/web/view/view.css +63 -18
  112. package/modules/localmodels/web/view/view.js +169 -32
  113. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
  114. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +115 -94
  115. package/package.json +1 -1
  116. package/tool.json +1 -1
  117. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  118. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
  119. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
  120. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
  121. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -20,6 +20,7 @@ The actions, their handlers and parameters are the Actions table below.
20
20
  from __future__ import annotations
21
21
 
22
22
  import base64
23
+ import contextlib
23
24
  import hashlib
24
25
  import json
25
26
  import os
@@ -281,6 +282,66 @@ def _sha256(path: str, label: str) -> str:
281
282
  return digest.hexdigest()
282
283
 
283
284
 
285
+ def _cache_blob(sha256: str) -> str | None:
286
+ root = os.environ.get("LOCALMODELS_CACHE_DIR", "").strip()
287
+ if not root or len(sha256) != 64:
288
+ return None
289
+ return os.path.join(_expand(root), sha256)
290
+
291
+
292
+ def _restore_cached(dest: str, sha256: str, size: int, label: str) -> bool:
293
+ cached = _cache_blob(sha256)
294
+ if not cached or not os.path.isfile(cached) or os.path.getsize(cached) != size:
295
+ return False
296
+ receipt = cached + ".sha256"
297
+ if not (os.path.isfile(receipt) and _read(receipt).strip() == sha256):
298
+ if _sha256(cached, label) != sha256:
299
+ return False
300
+ _write(receipt, sha256)
301
+ tmp = f"{dest}.cache.{os.getpid()}"
302
+ with contextlib.suppress(OSError):
303
+ os.unlink(tmp)
304
+ try:
305
+ if os.stat(cached).st_dev == os.stat(os.path.dirname(dest)).st_dev:
306
+ os.link(cached, tmp)
307
+ else:
308
+ shutil.copyfile(cached, tmp)
309
+ os.replace(tmp, dest)
310
+ except OSError:
311
+ with contextlib.suppress(OSError):
312
+ os.unlink(tmp)
313
+ return False
314
+ _write(dest + ".sha256", sha256)
315
+ emit(
316
+ "progress",
317
+ phase="download",
318
+ file=label,
319
+ done=size,
320
+ total=size,
321
+ bytes_per_s=size,
322
+ source="cache",
323
+ connections=0,
324
+ **step_fields(size),
325
+ )
326
+ emit("log", message="reused verified local cache for " + label)
327
+ return True
328
+
329
+
330
+ def _store_cached(dest: str, sha256: str, size: int) -> None:
331
+ cached = _cache_blob(sha256)
332
+ if not cached or (os.path.isfile(cached) and os.path.getsize(cached) == size):
333
+ return
334
+ with contextlib.suppress(OSError):
335
+ os.makedirs(os.path.dirname(cached), mode=0o700, exist_ok=True)
336
+ tmp = f"{cached}.tmp.{os.getpid()}"
337
+ if os.stat(dest).st_dev == os.stat(os.path.dirname(cached)).st_dev:
338
+ os.link(dest, tmp)
339
+ else:
340
+ shutil.copyfile(dest, tmp)
341
+ os.replace(tmp, cached)
342
+ _write(cached + ".sha256", sha256)
343
+
344
+
284
345
  def fetch(
285
346
  url: str,
286
347
  dest: str,
@@ -298,6 +359,9 @@ def fetch(
298
359
  os.makedirs(os.path.dirname(dest), exist_ok=True)
299
360
  if os.path.exists(dest) and os.path.getsize(dest) == size and _sha256(dest, label) == sha256:
300
361
  _write(marker, sha256)
362
+ _store_cached(dest, sha256, size)
363
+ return
364
+ if _restore_cached(dest, sha256, size, label):
301
365
  return
302
366
  free = shutil.disk_usage(os.path.dirname(dest)).free
303
367
  part = dest + ".part"
@@ -330,6 +394,7 @@ def fetch(
330
394
  remote_ops_download.discard(part + ".ranges") # the record only; part is renamed
331
395
  os.replace(part, dest)
332
396
  _write(marker, sha256)
397
+ _store_cached(dest, sha256, size)
333
398
  emit("log", message=f"downloaded and verified {label} from {source['source']}")
334
399
  return
335
400
  raise error or RuntimeError(f"{label} has no download source")
@@ -313,6 +313,15 @@ def _require_own_fragment(unit: str, paths: dict[str, str]) -> None:
313
313
  )
314
314
 
315
315
 
316
+ def _unit_not_loaded(unit: str) -> bool:
317
+ """True when systemd neither knows ``unit`` nor tracks any process or cgroup under it."""
318
+ return (
319
+ remote_ops._systemctl("show", "-p", "LoadState", "--value", unit) == (0, "not-found")
320
+ and remote_ops._systemctl("show", "-p", "MainPID", "--value", unit) == (0, "0")
321
+ and remote_ops._systemctl("show", "-p", "ControlGroup", "--value", unit) == (0, "")
322
+ )
323
+
324
+
316
325
  def _stop_owned_unit(p: remote_ops.InstallParams, paths: dict[str, str], ports: set[int]) -> None:
317
326
  unit = p["service"] + ".service"
318
327
  fragment = _unit_property(unit, "FragmentPath")
@@ -516,10 +525,13 @@ def act_stop(p: remote_ops.ServiceParams) -> None:
516
525
  except RuntimeError as exc:
517
526
  raise RuntimeError(f"the service process is still running: {exc}") from None
518
527
  elif p["service_kind"] == "systemd-user":
528
+ unit = p["service"] + ".service"
519
529
  if unit_runs_elsewhere(paths):
520
530
  raise RuntimeError("the systemd unit with this name runs another deployment; kept")
521
- _require_own_fragment(p["service"] + ".service", paths)
522
- if remote_ops._systemctl("stop", p["service"] + ".service")[0]:
531
+ _require_own_fragment(unit, paths)
532
+ if not os.path.exists(paths["unit"]) and _unit_not_loaded(unit):
533
+ pass
534
+ elif remote_ops._systemctl("stop", unit)[0]:
523
535
  raise RuntimeError("systemctl could not stop the service")
524
536
  else:
525
537
  # SIGKILL what SIGTERM leaves running: whisper-server b5454 can hang on SIGTERM.
@@ -52,15 +52,17 @@ DOCS: dict[str, tuple[str, str, list[tuple[str, str]]]] = {
52
52
  "save a plan to install or reuse one runtime; prints its approve id",
53
53
  "Look the runtime up as status does, then write localmodels.harness-plan/v1 to --out and "
54
54
  "print it. A runtime that already answers --version is reused; otherwise the plan pins "
55
- "the artifacts for this OS and CPU (URL, SHA256, size) for DIR/tools/<runtime>/<version>. "
56
- "Downloads nothing. The plan's id (a SHA256 of the plan) is the --approve value.",
55
+ "the artifacts for this OS and CPU (URL, digest, size limit) for DIR/tools/<runtime>/<version>. "
56
+ "The missing runtime resolves a stable release; --before-version excludes that "
57
+ "version and newer ones after a failed launch. No archive is downloaded. The plan's id "
58
+ "(a SHA256 of the plan) is the --approve value.",
57
59
  [("%(prog)s --root ~/harness --runtime codex --out plan.json", "")],
58
60
  ),
59
61
  "apply": (
60
62
  "install or reuse a runtime from a plan you approved",
61
63
  "Refuse unless --approve equals the plan's id and the platform, pinned lock and any "
62
64
  "supplied Node or launcher are unchanged. A reuse plan re-checks the existing version. An "
63
- "install plan downloads each artifact (size and SHA256 checked), unpacks it privately, "
65
+ "install plan downloads each artifact (size and digest checked), unpacks it privately, "
64
66
  "runs --version and moves it to <root>/tools/<runtime>/<version>; an existing target is "
65
67
  "never overwritten, but rerunning a plan that already installed succeeds. Prints "
66
68
  "localmodels.harness-status/v1.",
@@ -134,6 +136,11 @@ def add_parser(sub: Any) -> None:
134
136
  actions.choices["plan"].add_argument(
135
137
  "--out", type=Path, required=True, metavar="FILE", help="plan file (created 0600)"
136
138
  )
139
+ actions.choices["plan"].add_argument(
140
+ "--before-version",
141
+ metavar="VERSION",
142
+ help="select a stable release below VERSION",
143
+ )
137
144
  apply = actions.choices["apply"]
138
145
  apply.add_argument("--jsonl", action="store_true", help="print progress events (JSONL) first")
139
146
  apply.add_argument("plan", type=Path, metavar="PLAN", help="the file `harness plan` wrote")
@@ -18,6 +18,7 @@ import urllib.request
18
18
  from pathlib import Path
19
19
  from typing import Any
20
20
 
21
+ from localmodels import http_local
21
22
  from localmodels.runtime_io import (
22
23
  private_directory,
23
24
  private_permissions,
@@ -195,13 +196,6 @@ def codex_status_model(
195
196
  return None, error.code
196
197
 
197
198
 
198
- class _NoRedirect(urllib.request.HTTPRedirectHandler):
199
- def redirect_request(
200
- self, _req: Any, _fp: Any, _code: int, _msg: str, _headers: Any, _newurl: str
201
- ) -> None:
202
- return None
203
-
204
-
205
199
  def _validate_config(runtime: str, value: dict[str, Any]) -> None:
206
200
  if not isinstance(value, dict) or set(value) - {
207
201
  "provider",
@@ -294,7 +288,9 @@ def _verify_config(value: dict[str, Any]) -> None:
294
288
  headers = {"x-api-key": key, "anthropic-version": "2023-06-01"}
295
289
  try:
296
290
  request = urllib.request.Request(url, data=data, headers=headers)
297
- with urllib.request.build_opener(_NoRedirect()).open(request, timeout=45) as response:
291
+ with urllib.request.build_opener(http_local.NoRedirectHandler()).open(
292
+ request, timeout=45
293
+ ) as response:
298
294
  if response.status != 200:
299
295
  raise ValueError("Provider rejected runtime credentials")
300
296
  if provider == "openai-compatible":
@@ -326,7 +322,7 @@ def _context_window(value: dict[str, Any]) -> int:
326
322
  if "contextWindow" in value:
327
323
  return int(value["contextWindow"])
328
324
  base = value["baseUrl"].rstrip("/")
329
- opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
325
+ opener = http_local.no_proxy_opener(allow_redirects=False)
330
326
  for url in (base.removesuffix("/v1") + "/props", base + "/models"):
331
327
  try:
332
328
  request = urllib.request.Request(
@@ -6,9 +6,7 @@ import argparse
6
6
  import hashlib
7
7
  import json
8
8
  import os
9
- import platform
10
9
  import re
11
- import shutil
12
10
  import subprocess
13
11
  import sys
14
12
  import tempfile
@@ -16,16 +14,22 @@ import time
16
14
  from pathlib import Path
17
15
  from typing import Any
18
16
 
19
- from localmodels import runtime_auth, runtime_process
17
+ from localmodels import (
18
+ http_local,
19
+ runtime_auth,
20
+ runtime_discovery,
21
+ runtime_install,
22
+ runtime_process,
23
+ )
20
24
  from localmodels.runtime_auth import check_config, owned_files, provider_accepted, save_config
21
25
  from localmodels.runtime_auth import save_api_key as save_api_key
26
+ from localmodels.runtime_discovery import compatible_version as _compatible_version
27
+ from localmodels.runtime_discovery import private_file as _private_file
22
28
  from localmodels.runtime_io import (
23
29
  Event,
24
30
  RuntimeDownloadError,
25
- cached_download,
26
31
  download,
27
32
  error_cause,
28
- extract_binary,
29
33
  private_directory,
30
34
  private_permissions,
31
35
  validate_runtime_root,
@@ -33,21 +37,16 @@ from localmodels.runtime_io import (
33
37
  from localmodels.runtime_io import (
34
38
  extract_archive as extract_archive,
35
39
  )
40
+ from localmodels.runtime_releases import STABLE as _STABLE_VERSION
41
+ from localmodels.runtime_releases import codex_release as _codex_release
42
+ from localmodels.runtime_releases import resolve as _external_release
43
+ from localmodels.runtime_releases import version_key as _stable_version
36
44
 
37
45
  RUNTIMES = ("codex", "claude", "pi")
38
46
  LOCK = Path(__file__).with_name("runtime-lock.json")
39
47
  PROFILE_KEYS = {"codex": "CODEX_HOME", "claude": "CLAUDE_CONFIG_DIR", "pi": "PI_CODING_AGENT_DIR"}
40
48
  PROFILE_DIRS = {"codex": ".codex", "claude": ".claude", "pi": ".pi/agent"}
41
-
42
-
43
- def _private_file(path: Path) -> bool:
44
- try:
45
- if not path.is_file() or path.is_symlink():
46
- return False
47
- private_permissions(path)
48
- return True
49
- except (OSError, ValueError):
50
- return False
49
+ _platform = runtime_discovery.platform_tag
51
50
 
52
51
 
53
52
  def _owned_profile(directory: Path) -> bool:
@@ -59,20 +58,6 @@ def _active_profile(runtime: str, env: dict[str, str]) -> Path:
59
58
  return Path(env.get(PROFILE_KEYS[runtime], str(Path.home() / PROFILE_DIRS[runtime])))
60
59
 
61
60
 
62
- def _compatible_version(runtime: str, version: str | None) -> bool:
63
- return runtime != "claude" or runtime_process.version_ok(version, _lock()["versions"][runtime])
64
-
65
-
66
- def _platform() -> str:
67
- system = {"Windows": "win32", "Darwin": "darwin", "Linux": "linux"}.get(
68
- platform.system(), "unknown"
69
- )
70
- arch = {"x86_64": "x64", "AMD64": "x64", "aarch64": "arm64", "arm64": "arm64"}.get(
71
- platform.machine(), "unknown"
72
- )
73
- return f"{system}-{arch}"
74
-
75
-
76
61
  def _probe(argv: list[str], env: dict[str, str] | None = None) -> tuple[int, str]:
77
62
  """Bound execution and output; raw native messages never enter public reports."""
78
63
  return runtime_process.probe(argv, env, retry_timeout=bool(argv and argv[-1] == "--version"))
@@ -270,21 +255,26 @@ def inspect_runtimes(
270
255
  offline: bool = True,
271
256
  node: str | None = None,
272
257
  launcher: str | None = None,
258
+ before_versions: dict[str, str] | None = None,
273
259
  ) -> dict[str, Any]:
274
260
  """Read-only local native status; auth output and key material remain private."""
275
261
  validate_runtime_root(root)
276
262
  rows: list[dict[str, Any]] = []
277
263
  for runtime in RUNTIMES:
264
+ before_version = (before_versions or {}).get(runtime)
278
265
  explicit = os.environ.get(f"SIMPLEX_{runtime.upper()}_PATH")
279
- host = explicit if explicit is not None else (shutil.which(runtime) or runtime)
280
- candidates = [(host, "host")] if explicit is not None else [(host, "host")]
281
- commands: list[tuple[str, list[str], str]] = [
282
- (str(command), [], source) for command, source in candidates if command
283
- ]
266
+ hosts = (
267
+ [explicit]
268
+ if explicit is not None
269
+ else runtime_discovery.host_commands(runtime, _platform())
270
+ )
271
+ commands: list[tuple[str, list[str], str]] = [(host, [], "host") for host in hosts if host]
284
272
  if explicit is None:
285
273
  managed = _managed_command(root, runtime, node)
286
- if managed:
287
- commands.append((managed[0], managed[1:], "managed"))
274
+ managed_commands = runtime_discovery.managed_commands(root, runtime, _platform())
275
+ if managed and managed not in managed_commands:
276
+ managed_commands.append(managed)
277
+ commands.extend((entry[0], entry[1:], "managed") for entry in managed_commands)
288
278
  row: dict[str, Any] = dict(
289
279
  runtime=runtime,
290
280
  executable=None,
@@ -308,7 +298,9 @@ def inspect_runtimes(
308
298
  if code != 0:
309
299
  continue
310
300
  match = re.search(r"\d+\.\d+\.\d+(?:[\w.+-]*)", version)
311
- if not _compatible_version(runtime, match.group() if match else None):
301
+ if not _compatible_version(
302
+ runtime, match.group() if match else None, before_version=before_version
303
+ ):
312
304
  if explicit is not None:
313
305
  row.update(
314
306
  executable=executable,
@@ -391,18 +383,34 @@ def plan_id(plan: dict[str, Any]) -> str:
391
383
 
392
384
 
393
385
  def build_plan(
394
- runtime: str, root: Path, *, node: str | None = None, launcher: str | None = None
386
+ runtime: str,
387
+ root: Path,
388
+ *,
389
+ node: str | None = None,
390
+ launcher: str | None = None,
391
+ before_version: str | None = None,
395
392
  ) -> dict[str, Any]:
396
393
  validate_runtime_root(root)
397
394
  if runtime not in RUNTIMES:
398
395
  raise ValueError("Unknown runtime")
399
- status = next(row for row in inspect_runtimes(root)["runtimes"] if row["runtime"] == runtime)
396
+ if before_version is not None:
397
+ _stable_version(before_version)
398
+ status = next(
399
+ row
400
+ for row in inspect_runtimes(
401
+ root, before_versions={runtime: before_version} if before_version is not None else None
402
+ )["runtimes"]
403
+ if row["runtime"] == runtime
404
+ )
400
405
  if (
401
406
  os.environ.get(f"SIMPLEX_{runtime.upper()}_PATH") is not None
402
407
  and status["executable"]
403
- and not _compatible_version(runtime, status["version"])
408
+ and not _compatible_version(runtime, status["version"], before_version=before_version)
404
409
  ):
405
- raise ValueError("Explicit runtime version is incompatible with the supported baseline")
410
+ raise ValueError(
411
+ "Explicit runtime version is incompatible with the supported baseline or "
412
+ "--before-version bound"
413
+ )
406
414
  plan = native_plan(
407
415
  runtime,
408
416
  root,
@@ -411,13 +419,24 @@ def build_plan(
411
419
  version=status["version"],
412
420
  )
413
421
  lock = _lock()
422
+ if runtime == "codex" and plan["action"] == "install":
423
+ plan["version"], plan["artifacts"] = _codex_release(
424
+ plan["platform"], before_version=before_version
425
+ )
426
+ plan["artifactSource"] = "codex-stable-npm"
414
427
  if runtime == "pi" and plan["action"] == "install":
428
+ node_version = lock["node"]["version"]
415
429
  if node:
416
430
  if not Path(node).is_absolute() or not Path(node).is_file():
417
431
  raise ValueError("Pi requires an absolute regular private Node path")
418
432
  plan["bootstrap"].append(
419
433
  _bootstrap(Path(node), "node.exe" if os.name == "nt" else "node")
420
434
  )
435
+ code, version = _probe([node, "--version"])
436
+ match = _STABLE_VERSION.fullmatch(version.strip().removeprefix("v"))
437
+ if code != 0 or not match:
438
+ raise ValueError("The private Node executable could not report its version")
439
+ node_version = match.group()
421
440
  else:
422
441
  plan["nodeArtifact"] = lock["node"]["artifacts"][_platform()]
423
442
  if _platform().startswith("win32-"):
@@ -431,6 +450,15 @@ def build_plan(
431
450
  raise ValueError(
432
451
  "Windows Pi launcher artifact is unpublished; supply --launcher"
433
452
  )
453
+ else:
454
+ node_version = None
455
+ if runtime in ("claude", "pi") and plan["action"] == "install":
456
+ plan["version"], plan["artifacts"] = _external_release(
457
+ runtime, plan["platform"], before_version=before_version, node_version=node_version
458
+ )
459
+ plan["artifactSource"] = f"{runtime}-stable"
460
+ if before_version is not None:
461
+ plan["beforeVersion"] = before_version
434
462
  plan["id"] = plan_id(plan)
435
463
  return plan
436
464
 
@@ -480,102 +508,53 @@ def installed_command(plan: dict[str, Any]) -> Path:
480
508
  )
481
509
 
482
510
 
483
- def _bootstrap(path: Path, destination: str) -> dict[str, str]:
484
- if path.is_symlink():
485
- raise ValueError("Unsafe bootstrap executable")
486
- return dict(
487
- path=str(path),
488
- destination=destination,
489
- digest=hashlib.sha256(path.read_bytes()).hexdigest(),
490
- )
491
-
492
-
493
- def _downloads(root: Path, runtime: str) -> Path:
494
- """Where apply keeps verified and partial downloads until a run uses them, so a retry after
495
- a network failure resumes instead of starting over."""
496
- return root / "tools" / ".downloads" / runtime
497
-
498
-
499
- def _fetch_all(plan: dict[str, Any], event: Event) -> list[Path]:
500
- """Download every artifact first: one that failed leaves the others ready for the retry."""
501
- cache = _downloads(Path(plan["root"]), plan["runtime"])
502
- wanted = [*plan["artifacts"], plan.get("nodeArtifact"), plan.get("launcherArtifact")]
503
- return [cached_download(cache, a, event, download) if a else Path() for a in wanted]
504
-
505
-
506
- def _take(kept: Path, file: Path) -> None:
507
- kept.rename(file)
508
- private_permissions(file, created=True)
511
+ _bootstrap = runtime_install.bootstrap
512
+ _downloads = runtime_install.downloads_dir
509
513
 
510
514
 
511
515
  def _install_tree(plan: dict[str, Any], stage: Path, event: Event) -> Path:
512
- tree = stage / "runtime"
513
- private_directory(tree)
514
- fetched = _fetch_all(plan, event)
515
- for index, artifact in enumerate(plan["artifacts"]):
516
- file = stage / f"artifact-{index}"
517
- _take(fetched[index], file)
518
- event({"kind": "stage", "stage": "extract", "state": "running"})
519
- if artifact["format"] == "binary":
520
- shutil.copyfile(file, tree / artifact["executable"])
521
- (tree / artifact["executable"]).chmod(0o700)
522
- private_permissions(tree / artifact["executable"], created=True)
523
- else:
524
- unpack = stage / f"unpack-{index}"
525
- extract_archive(file, unpack)
526
- if plan["runtime"] == "pi" and index == 1:
527
- target = tree / artifact["destination"]
528
- private_directory(target.parent)
529
- (unpack / "package").rename(target)
530
- else:
531
- for entry in unpack.iterdir():
532
- entry.rename(tree / entry.name)
533
- if plan.get("nodeArtifact"):
534
- node_archive = stage / "node-archive"
535
- _take(fetched[-2], node_archive)
536
- extract_binary(
537
- node_archive,
538
- plan["nodeArtifact"]["member"],
539
- tree / ("node.exe" if os.name == "nt" else "node"),
540
- )
541
- if plan.get("launcherArtifact"):
542
- _take(fetched[-1], tree / "pi.exe")
543
- for bootstrap in plan["bootstrap"]:
544
- source = Path(bootstrap["path"])
545
- if (
546
- source.is_symlink()
547
- or hashlib.sha256(source.read_bytes()).hexdigest() != bootstrap["digest"]
548
- ):
549
- raise ValueError("Bootstrap artifact changed; create a new plan")
550
- destination = tree / bootstrap["destination"]
551
- shutil.copyfile(source, destination)
552
- destination.chmod(0o700)
553
- private_permissions(destination, created=True)
554
- if plan["runtime"] == "pi" and os.name != "nt":
555
- wrapper = tree / "pi"
556
- wrapper.write_text(
557
- '#!/bin/sh\nHERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nexec "$HERE/node" "$HERE/package/dist/bundle/cli.js" "$@"\n'
558
- )
559
- wrapper.chmod(0o700)
560
- return tree
516
+ return runtime_install.install_tree(plan, stage, event, download_fn=download)
561
517
 
562
518
 
563
- def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None) -> dict[str, Any]:
564
- if approve != plan_id(plan) or plan.get("id") != approve:
565
- raise ValueError("Runtime approval digest mismatch")
566
- root = validate_runtime_root(Path(plan["root"]))
519
+ def _validate_plan_artifacts(plan: dict[str, Any]) -> None:
567
520
  runtime = plan["runtime"]
568
521
  lock = _lock()
569
522
  if (
570
523
  plan["schema"] != "localmodels.harness-plan/v1"
571
524
  or plan["platform"] != _platform()
572
525
  or plan["lockDigest"] != _lock_digest()
573
- or plan["artifacts"] != lock["artifacts"].get(f"{runtime}/{_platform()}")
574
- or plan["version"] != lock["versions"].get(runtime)
575
526
  ):
576
527
  raise ValueError("Runtime platform or artifact lock changed; create a new plan")
577
528
  if plan["action"] not in ("install", "reuse"):
578
529
  raise ValueError("Invalid runtime plan action")
530
+ if "beforeVersion" in plan:
531
+ _stable_version(plan["beforeVersion"])
532
+ selected = plan["existingVersion"] if plan["action"] == "reuse" else plan["version"]
533
+ if not isinstance(selected, str) or not _compatible_version(
534
+ runtime, selected, before_version=plan["beforeVersion"]
535
+ ):
536
+ raise ValueError("Runtime version is incompatible with the approved version bound")
537
+ if plan.get("artifactSource") == "codex-stable-npm":
538
+ if (
539
+ runtime != "codex"
540
+ or plan["action"] != "install"
541
+ or not isinstance(plan["version"], str)
542
+ ):
543
+ raise ValueError("Invalid Codex registry plan")
544
+ expected_version, expected_artifacts = _codex_release(_platform(), plan["version"])
545
+ elif runtime in ("claude", "pi") and plan.get("artifactSource") == f"{runtime}-stable":
546
+ if plan["action"] != "install" or not isinstance(plan["version"], str):
547
+ raise ValueError("Invalid stable runtime plan")
548
+ expected_version, expected_artifacts = _external_release(
549
+ runtime, _platform(), plan["version"]
550
+ )
551
+ elif "artifactSource" not in plan:
552
+ expected_version = lock["versions"].get(runtime)
553
+ expected_artifacts = lock["artifacts"].get(f"{runtime}/{_platform()}")
554
+ else:
555
+ raise ValueError("Unknown runtime artifact source")
556
+ if (plan["version"], plan["artifacts"]) != (expected_version, expected_artifacts):
557
+ raise ValueError("Runtime artifact changed; create a new plan")
579
558
  if (
580
559
  plan.get("nodeArtifact") is not None
581
560
  and plan["nodeArtifact"] != lock["node"]["artifacts"].get(_platform())
@@ -584,13 +563,22 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
584
563
  and plan["launcherArtifact"] != lock["launchers"].get(_platform())
585
564
  ):
586
565
  raise ValueError("Runtime bootstrap lock changed")
566
+
567
+
568
+ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None) -> dict[str, Any]:
569
+ if approve != plan_id(plan) or plan.get("id") != approve:
570
+ raise ValueError("Runtime approval digest mismatch")
571
+ root = validate_runtime_root(Path(plan["root"]))
572
+ runtime = plan["runtime"]
573
+ _validate_plan_artifacts(plan)
574
+ before_versions = {runtime: plan["beforeVersion"]} if "beforeVersion" in plan else None
587
575
  allowed_bootstrap = {"node", "node.exe", "pi.exe"}
588
576
  for item in plan["bootstrap"]:
589
577
  if item["destination"] not in allowed_bootstrap or not Path(item["path"]).is_absolute():
590
578
  raise ValueError("Invalid bootstrap artifact")
591
579
  if (
592
580
  Path(item["path"]).is_symlink()
593
- or hashlib.sha256(Path(item["path"]).read_bytes()).hexdigest() != item["digest"]
581
+ or http_local.sha256_file(Path(item["path"])) != item["digest"]
594
582
  ):
595
583
  raise ValueError("Changed bootstrap artifact")
596
584
  if plan["action"] == "reuse":
@@ -601,8 +589,8 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
601
589
  if code != 0 or (match.group() if match else None) != plan["existingVersion"]:
602
590
  raise ValueError("Existing runtime changed; create a new plan")
603
591
  event({"kind": "stage", "stage": "reuse", "state": "succeeded"})
604
- return inspect_runtimes(root)
605
- target = _target(root, runtime)
592
+ return inspect_runtimes(root, before_versions=before_versions)
593
+ target = root / "tools" / runtime / plan["version"]
606
594
  if target.exists() or target.is_symlink():
607
595
  # An owned complete install can be safely retried, but unrelated/broken content is never overwritten.
608
596
  marker = target / "localmodels-runtime.json"
@@ -611,12 +599,17 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
611
599
  and not marker.is_symlink()
612
600
  and json.loads(marker.read_text()).get("planId") == approve
613
601
  ):
614
- code, version = _probe(_managed_command(root, runtime) + ["--version"])
602
+ command = (
603
+ [str(installed_command(plan))]
604
+ if runtime != "pi"
605
+ else [str(target / ("pi.exe" if os.name == "nt" else "pi"))]
606
+ )
607
+ code, version = _probe(command + ["--version"])
615
608
  if code != 0 or plan["version"] not in version:
616
609
  raise ValueError(
617
610
  "Owned runtime failed version verification; inspect before retrying"
618
611
  )
619
- return inspect_runtimes(root)
612
+ return inspect_runtimes(root, before_versions=before_versions)
620
613
  raise ValueError("Runtime target exists; refusing to overwrite it")
621
614
  private_directory(target.parent)
622
615
  event({"kind": "stage", "stage": "install", "state": "running"})
@@ -649,7 +642,7 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
649
642
  private_permissions(marker, created=True)
650
643
  tree.rename(target)
651
644
  event({"kind": "stage", "stage": "install", "state": "succeeded"})
652
- return inspect_runtimes(root)
645
+ return inspect_runtimes(root, before_versions=before_versions)
653
646
 
654
647
 
655
648
  def _act(args: argparse.Namespace) -> dict[str, Any]:
@@ -688,7 +681,13 @@ def _act(args: argparse.Namespace) -> dict[str, Any]:
688
681
  if args.runtime:
689
682
  value["runtimes"] = [row for row in value["runtimes"] if row["runtime"] == args.runtime]
690
683
  elif args.harness_action == "plan":
691
- value = build_plan(args.runtime, args.root, node=args.node, launcher=args.launcher)
684
+ value = build_plan(
685
+ args.runtime,
686
+ args.root,
687
+ node=args.node,
688
+ launcher=args.launcher,
689
+ before_version=getattr(args, "before_version", None),
690
+ )
692
691
  if args.out.exists() or args.out.is_symlink():
693
692
  private_permissions(args.out)
694
693
  args.out.write_text(json.dumps(value, indent=2) + "\n")