@simplexai/localmodels-darwin-arm64 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
@@ -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")
@@ -0,0 +1,84 @@
1
+ """Executable candidates from the user's computer and previous native installations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import platform
7
+ import re
8
+ import shutil
9
+ from pathlib import Path
10
+
11
+ from localmodels import runtime_process
12
+ from localmodels.runtime_io import private_permissions
13
+ from localmodels.runtime_releases import MINIMUM, codex_member, version_key
14
+
15
+
16
+ def private_file(path: Path) -> bool:
17
+ try:
18
+ if not path.is_file() or path.is_symlink():
19
+ return False
20
+ private_permissions(path)
21
+ return True
22
+ except (OSError, ValueError):
23
+ return False
24
+
25
+
26
+ def managed_commands(root: Path, runtime: str, native_platform: str) -> list[list[str]]:
27
+ """Find previously installed releases without contacting the registry."""
28
+ try:
29
+ member = (
30
+ codex_member(native_platform)
31
+ if runtime == "codex"
32
+ else runtime + (".exe" if os.name == "nt" else "")
33
+ )
34
+ except KeyError:
35
+ return []
36
+ parent = root / "tools" / runtime
37
+ versions = [
38
+ path
39
+ for path in parent.glob("*")
40
+ if re.fullmatch(r"\d+\.\d+\.\d+", path.name)
41
+ and not path.is_symlink()
42
+ and private_file(path / "localmodels-runtime.json")
43
+ and (path / member).is_file()
44
+ ]
45
+ versions.sort(key=lambda path: tuple(map(int, path.name.split("."))), reverse=True)
46
+ return [[str(path / member)] for path in versions]
47
+
48
+
49
+ def host_commands(runtime: str, native_platform: str) -> list[str]:
50
+ home = Path.home()
51
+ directories = [*os.get_exec_path(), str(home / ".local/bin")]
52
+ if os.name == "nt" and (appdata := os.environ.get("APPDATA")):
53
+ directories.append(str(Path(appdata) / "npm"))
54
+ commands = [
55
+ executable
56
+ for directory in dict.fromkeys(directories)
57
+ if Path(directory).is_absolute()
58
+ and (executable := shutil.which(runtime, path=directory))
59
+ and Path(executable).is_absolute()
60
+ ]
61
+ if runtime in ("codex", "claude") and native_platform.startswith("darwin-"):
62
+ for directory in (Path("/Applications"), home / "Applications"):
63
+ bundle = directory / f"{runtime.capitalize()}.app/Contents/Resources/{runtime}"
64
+ if bundle.is_file():
65
+ commands.append(str(bundle))
66
+ return list(dict.fromkeys(commands)) or [runtime]
67
+
68
+
69
+ def platform_tag() -> str:
70
+ system = {"Windows": "win32", "Darwin": "darwin", "Linux": "linux"}.get(
71
+ platform.system(), "unknown"
72
+ )
73
+ arch = {"x86_64": "x64", "AMD64": "x64", "aarch64": "arm64", "arm64": "arm64"}.get(
74
+ platform.machine(), "unknown"
75
+ )
76
+ return f"{system}-{arch}"
77
+
78
+
79
+ def compatible_version(
80
+ runtime: str, version: str | None, *, before_version: str | None = None
81
+ ) -> bool:
82
+ if version is None or not runtime_process.version_ok(version, MINIMUM[runtime]):
83
+ return False
84
+ return before_version is None or version_key(version) < version_key(before_version)
@@ -0,0 +1,101 @@
1
+ """Artifact caching, unpacking and staged tree installation for native agent runtimes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ from collections.abc import Callable
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from localmodels import http_local
12
+ from localmodels.runtime_io import (
13
+ Event,
14
+ cached_download,
15
+ download,
16
+ extract_archive,
17
+ extract_binary,
18
+ private_directory,
19
+ private_permissions,
20
+ )
21
+
22
+
23
+ def bootstrap(path: Path, destination: str) -> dict[str, str]:
24
+ if path.is_symlink():
25
+ raise ValueError("Unsafe bootstrap executable")
26
+ return dict(path=str(path), destination=destination, digest=http_local.sha256_file(path))
27
+
28
+
29
+ def downloads_dir(root: Path, runtime: str) -> Path:
30
+ """Where apply keeps verified and partial downloads until a run uses them, so a retry after
31
+ a network failure resumes instead of starting over."""
32
+ return root / "tools" / ".downloads" / runtime
33
+
34
+
35
+ def fetch_all(
36
+ plan: dict[str, Any], event: Event, *, download_fn: Callable[..., Any] = download
37
+ ) -> list[Path]:
38
+ """Download every artifact first: one that failed leaves the others ready for the retry."""
39
+ cache = downloads_dir(Path(plan["root"]), plan["runtime"])
40
+ wanted = [*plan["artifacts"], plan.get("nodeArtifact"), plan.get("launcherArtifact")]
41
+ return [cached_download(cache, a, event, download_fn) if a else Path() for a in wanted]
42
+
43
+
44
+ def take(kept: Path, file: Path) -> None:
45
+ kept.rename(file)
46
+ private_permissions(file, created=True)
47
+
48
+
49
+ def install_tree(
50
+ plan: dict[str, Any],
51
+ stage: Path,
52
+ event: Event,
53
+ *,
54
+ download_fn: Callable[..., Any] = download,
55
+ ) -> Path:
56
+ tree = stage / "runtime"
57
+ private_directory(tree)
58
+ fetched = fetch_all(plan, event, download_fn=download_fn)
59
+ for index, artifact in enumerate(plan["artifacts"]):
60
+ file = stage / f"artifact-{index}"
61
+ take(fetched[index], file)
62
+ event({"kind": "stage", "stage": "extract", "state": "running"})
63
+ if artifact["format"] == "binary":
64
+ shutil.copyfile(file, tree / artifact["executable"])
65
+ (tree / artifact["executable"]).chmod(0o700)
66
+ private_permissions(tree / artifact["executable"], created=True)
67
+ else:
68
+ unpack = stage / f"unpack-{index}"
69
+ extract_archive(file, unpack)
70
+ if plan["runtime"] == "pi" and index == 1:
71
+ target = tree / artifact["destination"]
72
+ private_directory(target.parent)
73
+ (unpack / "package").rename(target)
74
+ else:
75
+ for entry in unpack.iterdir():
76
+ entry.rename(tree / entry.name)
77
+ if plan.get("nodeArtifact"):
78
+ node_archive = stage / "node-archive"
79
+ take(fetched[-2], node_archive)
80
+ extract_binary(
81
+ node_archive,
82
+ plan["nodeArtifact"]["member"],
83
+ tree / ("node.exe" if os.name == "nt" else "node"),
84
+ )
85
+ if plan.get("launcherArtifact"):
86
+ take(fetched[-1], tree / "pi.exe")
87
+ for item in plan["bootstrap"]:
88
+ source = Path(item["path"])
89
+ if source.is_symlink() or http_local.sha256_file(source) != item["digest"]:
90
+ raise ValueError("Bootstrap artifact changed; create a new plan")
91
+ destination = tree / item["destination"]
92
+ shutil.copyfile(source, destination)
93
+ destination.chmod(0o700)
94
+ private_permissions(destination, created=True)
95
+ if plan["runtime"] == "pi" and os.name != "nt":
96
+ wrapper = tree / "pi"
97
+ wrapper.write_text(
98
+ '#!/bin/sh\nHERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)\nexec "$HERE/node" "$HERE/package/dist/bundle/cli.js" "$@"\n'
99
+ )
100
+ wrapper.chmod(0o700)
101
+ return tree