@simplexai/localmodels-darwin-arm64 0.1.0-dev.38 → 0.1.0-dev.40
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +81 -73
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +4 -0
- package/modules/localmodels/auth_proxy.py +74 -16
- package/modules/localmodels/bifrost_config.py +19 -0
- package/modules/localmodels/budget.py +27 -18
- package/modules/localmodels/catalog.json +18 -6
- package/modules/localmodels/chat_template.py +35 -0
- package/modules/localmodels/cli_parser.py +26 -3
- package/modules/localmodels/deploy.py +44 -10
- package/modules/localmodels/deploy_steps.py +6 -3
- package/modules/localmodels/download-mirrors.json +52 -4
- package/modules/localmodels/engines-b11583.json +20 -4
- package/modules/localmodels/engines-b12167.json +5 -1
- package/modules/localmodels/engines-strata-0.1.47.json +5 -1
- package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
- package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
- package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
- package/modules/localmodels/engines-whisper-b5454.json +5 -1
- package/modules/localmodels/engines.json +55 -11
- package/modules/localmodels/frontend.py +5 -2
- package/modules/localmodels/gateway.py +2 -0
- package/modules/localmodels/gateway_bifrost.py +3 -0
- package/modules/localmodels/gateway_home.py +132 -0
- package/modules/localmodels/guard.py +15 -6
- package/modules/localmodels/harness.py +104 -37
- package/modules/localmodels/harness_gateway.py +9 -3
- package/modules/localmodels/harness_probe.py +5 -1
- package/modules/localmodels/hf_repo.py +15 -8
- package/modules/localmodels/library_gateway.py +28 -15
- package/modules/localmodels/library_jobs.py +7 -1
- package/modules/localmodels/library_serve.py +5 -0
- package/modules/localmodels/metal.py +29 -12
- package/modules/localmodels/metal_probe.py +16 -6
- package/modules/localmodels/npm_signatures.py +131 -0
- package/modules/localmodels/npm_transport.py +26 -10
- package/modules/localmodels/probe.py +4 -0
- package/modules/localmodels/process_identity.py +21 -5
- package/modules/localmodels/region.py +244 -0
- package/modules/localmodels/remote_ops.py +69 -13
- package/modules/localmodels/remote_ops_download.py +217 -10
- package/modules/localmodels/remote_ops_prepare.py +61 -8
- package/modules/localmodels/remote_ops_remove.py +15 -0
- package/modules/localmodels/remote_ops_service.py +10 -0
- package/modules/localmodels/runtime-lock.json +13 -13
- package/modules/localmodels/runtime_args.py +4 -2
- package/modules/localmodels/runtime_cli.py +76 -74
- package/modules/localmodels/runtime_discovery.py +58 -0
- package/modules/localmodels/runtime_install.py +103 -7
- package/modules/localmodels/runtime_io.py +64 -7
- package/modules/localmodels/runtime_pi.py +122 -0
- package/modules/localmodels/runtime_process.py +101 -15
- package/modules/localmodels/runtime_releases.py +51 -71
- package/modules/localmodels/service_deployment.py +5 -3
- package/modules/localmodels/service_probe.py +146 -31
- package/modules/localmodels/setup_inspection.py +110 -14
- package/modules/localmodels/setup_text.py +13 -0
- package/modules/localmodels/slot_cache.py +467 -0
- package/modules/localmodels/source_byok.py +484 -0
- package/modules/localmodels/source_byok_probe.py +275 -0
- package/modules/localmodels/source_cli.py +426 -0
- package/modules/localmodels/stack_args.py +2 -1
- package/modules/localmodels/stack_binding.py +125 -5
- package/modules/localmodels/stack_capacity.py +3 -3
- package/modules/localmodels/stack_down.py +22 -7
- package/modules/localmodels/stack_events.py +62 -0
- package/modules/localmodels/stack_hardware.py +20 -17
- package/modules/localmodels/stack_lifecycle.py +12 -3
- package/modules/localmodels/stack_rollback.py +9 -4
- package/modules/localmodels/stack_up.py +27 -20
- package/modules/localmodels/stack_update.py +3 -1
- package/modules/localmodels/tools.json +1365 -14
- package/modules/localmodels/transport.py +2 -0
- package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/RECORD +78 -70
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -19,11 +19,14 @@ from localmodels import (
|
|
|
19
19
|
runtime_auth,
|
|
20
20
|
runtime_discovery,
|
|
21
21
|
runtime_install,
|
|
22
|
+
runtime_pi,
|
|
22
23
|
runtime_process,
|
|
23
24
|
)
|
|
25
|
+
from localmodels.harness import load_lock
|
|
24
26
|
from localmodels.runtime_auth import check_config, owned_files, provider_accepted, save_config
|
|
25
27
|
from localmodels.runtime_auth import save_api_key as save_api_key
|
|
26
28
|
from localmodels.runtime_discovery import compatible_version as _compatible_version
|
|
29
|
+
from localmodels.runtime_discovery import pi_loads_extensions
|
|
27
30
|
from localmodels.runtime_discovery import private_file as _private_file
|
|
28
31
|
from localmodels.runtime_io import (
|
|
29
32
|
Event,
|
|
@@ -37,7 +40,6 @@ from localmodels.runtime_io import (
|
|
|
37
40
|
from localmodels.runtime_io import (
|
|
38
41
|
extract_archive as extract_archive,
|
|
39
42
|
)
|
|
40
|
-
from localmodels.runtime_releases import STABLE as _STABLE_VERSION
|
|
41
43
|
from localmodels.runtime_releases import codex_release as _codex_release
|
|
42
44
|
from localmodels.runtime_releases import resolve as _external_release
|
|
43
45
|
from localmodels.runtime_releases import version_key as _stable_version
|
|
@@ -88,8 +90,6 @@ def _require_installed_version(code: int, output: str, expected: str) -> None:
|
|
|
88
90
|
|
|
89
91
|
|
|
90
92
|
def _lock() -> dict[str, Any]:
|
|
91
|
-
from localmodels.harness import load_lock
|
|
92
|
-
|
|
93
93
|
value: dict[str, Any] = json.loads(LOCK.read_text())
|
|
94
94
|
pi = load_lock()["pi"]
|
|
95
95
|
value["versions"]["pi"] = pi["version"]
|
|
@@ -111,7 +111,7 @@ def _lock() -> dict[str, Any]:
|
|
|
111
111
|
digest=module["sha256"],
|
|
112
112
|
maxBytes=module["size_bytes"],
|
|
113
113
|
format="tar",
|
|
114
|
-
destination="package/
|
|
114
|
+
destination="package/" + module["path"],
|
|
115
115
|
)
|
|
116
116
|
)
|
|
117
117
|
for native_platform in value["node"]["artifacts"]:
|
|
@@ -300,7 +300,7 @@ def inspect_runtimes(
|
|
|
300
300
|
match = re.search(r"\d+\.\d+\.\d+(?:[\w.+-]*)", version)
|
|
301
301
|
if not _compatible_version(
|
|
302
302
|
runtime, match.group() if match else None, before_version=before_version
|
|
303
|
-
):
|
|
303
|
+
) or (runtime == "pi" and not pi_loads_extensions([executable, *prefix])):
|
|
304
304
|
if explicit is not None:
|
|
305
305
|
row.update(
|
|
306
306
|
executable=executable,
|
|
@@ -402,15 +402,14 @@ def build_plan(
|
|
|
402
402
|
)["runtimes"]
|
|
403
403
|
if row["runtime"] == runtime
|
|
404
404
|
)
|
|
405
|
-
if (
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
"
|
|
413
|
-
)
|
|
405
|
+
if os.environ.get(f"SIMPLEX_{runtime.upper()}_PATH") is not None and status["executable"]:
|
|
406
|
+
if not _compatible_version(runtime, status["version"], before_version=before_version):
|
|
407
|
+
raise ValueError(
|
|
408
|
+
"Explicit runtime version is incompatible with the supported baseline or "
|
|
409
|
+
"--before-version bound"
|
|
410
|
+
)
|
|
411
|
+
if not status["installed"]: # the status reads only the explicit path: no install helps
|
|
412
|
+
raise ValueError("The explicit runtime path cannot load extensions")
|
|
414
413
|
plan = native_plan(
|
|
415
414
|
runtime,
|
|
416
415
|
root,
|
|
@@ -419,44 +418,20 @@ def build_plan(
|
|
|
419
418
|
version=status["version"],
|
|
420
419
|
)
|
|
421
420
|
lock = _lock()
|
|
422
|
-
if runtime == "codex" and plan["action"] == "install":
|
|
421
|
+
if runtime == "codex" and plan["action"] == "install" and before_version is not None:
|
|
423
422
|
plan["version"], plan["artifacts"] = _codex_release(
|
|
424
423
|
plan["platform"], before_version=before_version
|
|
425
424
|
)
|
|
426
425
|
plan["artifactSource"] = "codex-stable-npm"
|
|
427
426
|
if runtime == "pi" and plan["action"] == "install":
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
plan["bootstrap"].append(
|
|
433
|
-
_bootstrap(Path(node), "node.exe" if os.name == "nt" else "node")
|
|
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()
|
|
440
|
-
else:
|
|
441
|
-
plan["nodeArtifact"] = lock["node"]["artifacts"][_platform()]
|
|
442
|
-
if _platform().startswith("win32-"):
|
|
443
|
-
if launcher:
|
|
444
|
-
if not Path(launcher).is_absolute() or not Path(launcher).is_file():
|
|
445
|
-
raise ValueError("Windows Pi requires an absolute native launcher path")
|
|
446
|
-
plan["bootstrap"].append(_bootstrap(Path(launcher), "pi.exe"))
|
|
447
|
-
else:
|
|
448
|
-
plan["launcherArtifact"] = lock["launchers"].get(_platform())
|
|
449
|
-
if not plan["launcherArtifact"]:
|
|
450
|
-
raise ValueError(
|
|
451
|
-
"Windows Pi launcher artifact is unpublished; supply --launcher"
|
|
452
|
-
)
|
|
453
|
-
else:
|
|
454
|
-
node_version = None
|
|
455
|
-
if runtime in ("claude", "pi") and plan["action"] == "install":
|
|
427
|
+
runtime_pi.plan_install(
|
|
428
|
+
plan, lock, node, launcher, before_version, platform=_platform(), probe=_probe
|
|
429
|
+
)
|
|
430
|
+
if runtime == "claude" and plan["action"] == "install" and before_version is not None:
|
|
456
431
|
plan["version"], plan["artifacts"] = _external_release(
|
|
457
|
-
runtime, plan["platform"], before_version=before_version
|
|
432
|
+
runtime, plan["platform"], before_version=before_version
|
|
458
433
|
)
|
|
459
|
-
plan["artifactSource"] =
|
|
434
|
+
plan["artifactSource"] = "claude-stable"
|
|
460
435
|
if before_version is not None:
|
|
461
436
|
plan["beforeVersion"] = before_version
|
|
462
437
|
plan["id"] = plan_id(plan)
|
|
@@ -542,7 +517,7 @@ def _validate_plan_artifacts(plan: dict[str, Any]) -> None:
|
|
|
542
517
|
):
|
|
543
518
|
raise ValueError("Invalid Codex registry plan")
|
|
544
519
|
expected_version, expected_artifacts = _codex_release(_platform(), plan["version"])
|
|
545
|
-
elif runtime
|
|
520
|
+
elif runtime == "claude" and plan.get("artifactSource") == "claude-stable":
|
|
546
521
|
if plan["action"] != "install" or not isinstance(plan["version"], str):
|
|
547
522
|
raise ValueError("Invalid stable runtime plan")
|
|
548
523
|
expected_version, expected_artifacts = _external_release(
|
|
@@ -582,38 +557,19 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
|
|
|
582
557
|
):
|
|
583
558
|
raise ValueError("Changed bootstrap artifact")
|
|
584
559
|
if plan["action"] == "reuse":
|
|
585
|
-
|
|
586
|
-
raise ValueError("Existing runtime version is incompatible with the supported baseline")
|
|
587
|
-
code, current_version = _probe([*plan["command"], "--version"])
|
|
588
|
-
match = re.search(r"\d+\.\d+\.\d+(?:[\w.+-]*)", current_version)
|
|
589
|
-
if code != 0 or (match.group() if match else None) != plan["existingVersion"]:
|
|
590
|
-
raise ValueError("Existing runtime changed; create a new plan")
|
|
560
|
+
_check_reused(plan)
|
|
591
561
|
event({"kind": "stage", "stage": "reuse", "state": "succeeded"})
|
|
592
|
-
return
|
|
562
|
+
return _installed(root, runtime, before_versions)
|
|
593
563
|
target = root / "tools" / runtime / plan["version"]
|
|
564
|
+
replace = False
|
|
594
565
|
if target.exists() or target.is_symlink():
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
marker.is_file()
|
|
599
|
-
and not marker.is_symlink()
|
|
600
|
-
and json.loads(marker.read_text()).get("planId") == approve
|
|
601
|
-
):
|
|
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"])
|
|
608
|
-
if code != 0 or plan["version"] not in version:
|
|
609
|
-
raise ValueError(
|
|
610
|
-
"Owned runtime failed version verification; inspect before retrying"
|
|
611
|
-
)
|
|
612
|
-
return inspect_runtimes(root, before_versions=before_versions)
|
|
613
|
-
raise ValueError("Runtime target exists; refusing to overwrite it")
|
|
566
|
+
if _kept(target, plan, approve):
|
|
567
|
+
return _installed(root, runtime, before_versions)
|
|
568
|
+
replace = True
|
|
614
569
|
private_directory(target.parent)
|
|
615
570
|
event({"kind": "stage", "stage": "install", "state": "running"})
|
|
616
|
-
|
|
571
|
+
# Short names: Windows allows 260 characters, and Pi's tree has files 138 below its root
|
|
572
|
+
with tempfile.TemporaryDirectory(prefix=".s", dir=target.parent) as temporary:
|
|
617
573
|
stage = Path(temporary)
|
|
618
574
|
private_permissions(stage, created=True)
|
|
619
575
|
tree = _install_tree(plan, stage, event)
|
|
@@ -626,6 +582,10 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
|
|
|
626
582
|
code, version = _probe(command + ["--version"])
|
|
627
583
|
try:
|
|
628
584
|
_require_installed_version(code, version, plan["version"])
|
|
585
|
+
if runtime == "pi" and not pi_loads_extensions(command):
|
|
586
|
+
raise RuntimeVersionVerificationError(
|
|
587
|
+
"RUNTIME_EXTENSIONS_FAILED", "Pi could not load an extension."
|
|
588
|
+
)
|
|
629
589
|
except RuntimeVersionVerificationError as error:
|
|
630
590
|
event(
|
|
631
591
|
{
|
|
@@ -640,9 +600,51 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
|
|
|
640
600
|
marker = tree / "localmodels-runtime.json"
|
|
641
601
|
marker.write_text(json.dumps({"schema": "localmodels.runtime-owned/v1", "planId": approve}))
|
|
642
602
|
private_permissions(marker, created=True)
|
|
603
|
+
if replace:
|
|
604
|
+
runtime_pi.retire(target)
|
|
643
605
|
tree.rename(target)
|
|
606
|
+
runtime_install.release_downloads(plan)
|
|
644
607
|
event({"kind": "stage", "stage": "install", "state": "succeeded"})
|
|
645
|
-
return
|
|
608
|
+
return _installed(root, runtime, before_versions)
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def _check_reused(plan: dict[str, Any]) -> None:
|
|
612
|
+
"""The reused runtime still reports its version, and a Pi still loads an extension."""
|
|
613
|
+
if not _compatible_version(plan["runtime"], plan["existingVersion"]):
|
|
614
|
+
raise ValueError("Existing runtime version is incompatible with the supported baseline")
|
|
615
|
+
code, current_version = _probe([*plan["command"], "--version"])
|
|
616
|
+
match = re.search(r"\d+\.\d+\.\d+(?:[\w.+-]*)", current_version)
|
|
617
|
+
if code != 0 or (match.group() if match else None) != plan["existingVersion"]:
|
|
618
|
+
raise ValueError("Existing runtime changed; create a new plan")
|
|
619
|
+
if plan["runtime"] == "pi" and not pi_loads_extensions(plan["command"]):
|
|
620
|
+
raise RuntimeVersionVerificationError(
|
|
621
|
+
"RUNTIME_EXTENSIONS_FAILED", "Pi could not load an extension."
|
|
622
|
+
)
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _kept(target: Path, plan: dict[str, Any], approve: str) -> bool:
|
|
626
|
+
"""Whether the owned install at ``target`` is the install; False: an owned Pi to replace
|
|
627
|
+
once the new tree verified (dev38's, without jiti). A working owned Pi is kept, whichever
|
|
628
|
+
plan made it; anything not owned is never overwritten."""
|
|
629
|
+
marker = None if target.is_symlink() else runtime_discovery.owned_marker(target)
|
|
630
|
+
if marker is None:
|
|
631
|
+
raise ValueError("Runtime target exists; refusing to overwrite it")
|
|
632
|
+
if plan["runtime"] == "pi":
|
|
633
|
+
return runtime_pi.healthy(target, plan["version"], _probe, pi_loads_extensions)
|
|
634
|
+
if marker.get("planId") != approve:
|
|
635
|
+
raise ValueError("Runtime target exists; refusing to overwrite it")
|
|
636
|
+
code, version = _probe([str(installed_command(plan)), "--version"])
|
|
637
|
+
if code != 0 or plan["version"] not in version:
|
|
638
|
+
raise ValueError("Owned runtime failed version verification; inspect before retrying")
|
|
639
|
+
return True
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def _installed(root: Path, runtime: str, before_versions: dict[str, str] | None) -> dict[str, Any]:
|
|
643
|
+
"""The status after apply; never exit 0 while the runtime is not installed (Linger)."""
|
|
644
|
+
status = inspect_runtimes(root, before_versions=before_versions)
|
|
645
|
+
if not next(row for row in status["runtimes"] if row["runtime"] == runtime)["installed"]:
|
|
646
|
+
raise ValueError(f"{runtime} is still not usable after apply")
|
|
647
|
+
return status
|
|
646
648
|
|
|
647
649
|
|
|
648
650
|
def _act(args: argparse.Namespace) -> dict[str, Any]:
|
|
@@ -2,11 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import json
|
|
5
6
|
import os
|
|
6
7
|
import platform
|
|
7
8
|
import re
|
|
8
9
|
import shutil
|
|
10
|
+
import tempfile
|
|
11
|
+
from collections.abc import Mapping
|
|
9
12
|
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
10
14
|
|
|
11
15
|
from localmodels import runtime_process
|
|
12
16
|
from localmodels.runtime_io import private_permissions
|
|
@@ -82,3 +86,57 @@ def compatible_version(
|
|
|
82
86
|
if version is None or not runtime_process.version_ok(version, MINIMUM[runtime]):
|
|
83
87
|
return False
|
|
84
88
|
return before_version is None or version_key(version) < version_key(before_version)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
PI_EXTENSION_MARKER = "localmodels-pi-extension-probe"
|
|
92
|
+
# TypeScript, so loading it needs the jiti transform Pi loads every extension with (Linger passes
|
|
93
|
+
# --extension <computer-tools>/extensions/pi-mcp.mjs on every run). The marker is joined at run
|
|
94
|
+
# time: a loader error that quotes the source must not print it.
|
|
95
|
+
PI_EXTENSION_PROBE = """const marker: string = ["localmodels-pi", "extension-probe"].join("-");
|
|
96
|
+
export default function (_pi: unknown): void {
|
|
97
|
+
process.stderr.write(marker + "\\n");
|
|
98
|
+
}
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def pi_loads_extensions(argv: list[str], env: Mapping[str, str] | None = None) -> bool:
|
|
103
|
+
"""Whether this Pi can load an extension. A Pi missing its dependencies (localmodels before
|
|
104
|
+
0.1.0.dev39 installed only the bundled CLI and its image module) prints "Cannot find module
|
|
105
|
+
'jiti'" and still exits 0, so the probe extension's own output is the evidence. The probe
|
|
106
|
+
runs in its own empty directory with an empty private profile and without extension
|
|
107
|
+
discovery: no user extension or project setting runs and no user setting is read or
|
|
108
|
+
written."""
|
|
109
|
+
with tempfile.TemporaryDirectory(
|
|
110
|
+
prefix="localmodels-pi-probe-", ignore_cleanup_errors=True
|
|
111
|
+
) as temporary:
|
|
112
|
+
directory = Path(temporary)
|
|
113
|
+
extension = directory / "probe.ts"
|
|
114
|
+
extension.write_text(PI_EXTENSION_PROBE, encoding="utf-8")
|
|
115
|
+
(directory / "agent").mkdir()
|
|
116
|
+
child = {
|
|
117
|
+
**(os.environ if env is None else env),
|
|
118
|
+
"PI_CODING_AGENT_DIR": str(directory / "agent"),
|
|
119
|
+
}
|
|
120
|
+
code, output = runtime_process.probe(
|
|
121
|
+
[*argv, "--no-extensions", "--extension", str(extension), "--list-models"],
|
|
122
|
+
child,
|
|
123
|
+
timeout=30,
|
|
124
|
+
retry_timeout=True,
|
|
125
|
+
cwd=str(directory),
|
|
126
|
+
)
|
|
127
|
+
return code == 0 and PI_EXTENSION_MARKER in output
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def owned_marker(target: Path) -> dict[str, Any] | None:
|
|
131
|
+
"""The ownership record apply wrote into ``target``, or None when there is none or it is
|
|
132
|
+
not one (a hand-made file, or JSON that is not an object)."""
|
|
133
|
+
marker = target / "localmodels-runtime.json"
|
|
134
|
+
if not private_file(marker):
|
|
135
|
+
return None
|
|
136
|
+
try:
|
|
137
|
+
value = json.loads(marker.read_text(encoding="utf-8"))
|
|
138
|
+
except (OSError, ValueError):
|
|
139
|
+
return None
|
|
140
|
+
if not isinstance(value, dict) or value.get("schema") != "localmodels.runtime-owned/v1":
|
|
141
|
+
return None
|
|
142
|
+
return value
|
|
@@ -2,15 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import contextlib
|
|
5
6
|
import os
|
|
6
7
|
import shutil
|
|
8
|
+
import threading
|
|
7
9
|
from collections.abc import Callable
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
11
|
+
from functools import partial
|
|
8
12
|
from pathlib import Path
|
|
9
13
|
from typing import Any
|
|
10
14
|
|
|
11
15
|
from localmodels import http_local
|
|
12
16
|
from localmodels.runtime_io import (
|
|
13
17
|
Event,
|
|
18
|
+
Rate,
|
|
14
19
|
cached_download,
|
|
15
20
|
download,
|
|
16
21
|
extract_archive,
|
|
@@ -32,17 +37,107 @@ def downloads_dir(root: Path, runtime: str) -> Path:
|
|
|
32
37
|
return root / "tools" / ".downloads" / runtime
|
|
33
38
|
|
|
34
39
|
|
|
40
|
+
MODULE_DOWNLOADS = 8 # Pi's dependency tree is ~120 small tarballs; one at a time takes minutes
|
|
41
|
+
|
|
42
|
+
|
|
35
43
|
def fetch_all(
|
|
36
44
|
plan: dict[str, Any], event: Event, *, download_fn: Callable[..., Any] = download
|
|
37
45
|
) -> list[Path]:
|
|
38
|
-
"""Download every artifact first: one that failed leaves the others ready for the retry.
|
|
46
|
+
"""Download every artifact first: one that failed leaves the others ready for the retry.
|
|
47
|
+
Pi's dependency modules download together and report one byte count."""
|
|
48
|
+
cache = downloads_dir(Path(plan["root"]), plan["runtime"])
|
|
49
|
+
if plan.get("artifactSource") == "codex-stable-npm":
|
|
50
|
+
download_fn = partial(download_fn, retry_missing=True)
|
|
51
|
+
wanted = _wanted(plan)
|
|
52
|
+
found = {
|
|
53
|
+
a["digest"]: cached_download(cache, a, event, download_fn)
|
|
54
|
+
for a in wanted
|
|
55
|
+
if a and not a.get("destination")
|
|
56
|
+
}
|
|
57
|
+
modules = {a["digest"]: a for a in wanted if a and a.get("destination")}
|
|
58
|
+
found.update(_fetch_modules(cache, list(modules.values()), event, download_fn))
|
|
59
|
+
return [found[a["digest"]] if a else Path() for a in wanted]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _fetch_modules(
|
|
63
|
+
cache: Path, artifacts: list[dict[str, Any]], event: Event, download_fn: Callable[..., Any]
|
|
64
|
+
) -> dict[str, Path]:
|
|
65
|
+
"""Download the modules eight at a time. The byte count never goes back: a module that
|
|
66
|
+
restarts (a retry, the other registry) keeps its highest count, and the rate counts only
|
|
67
|
+
bytes that came over the network, not modules already in the cache. The first failure
|
|
68
|
+
cancels the modules still queued."""
|
|
69
|
+
if not artifacts:
|
|
70
|
+
return {}
|
|
71
|
+
total = sum(int(a["maxBytes"]) for a in artifacts) # the pinned sizes are exact
|
|
72
|
+
done: dict[str, int] = {} # each module's highest byte count, cached ones included
|
|
73
|
+
fetched: dict[str, int] = {} # each module's highest count reported by a transfer
|
|
74
|
+
lock = threading.Lock()
|
|
75
|
+
rate = Rate(0)
|
|
76
|
+
shown = 0
|
|
77
|
+
private_directory(cache) # once, before the downloads race to create it
|
|
78
|
+
|
|
79
|
+
def fetch(artifact: dict[str, Any]) -> Path:
|
|
80
|
+
digest = artifact["digest"]
|
|
81
|
+
|
|
82
|
+
def report(update: dict[str, Any]) -> None:
|
|
83
|
+
nonlocal shown
|
|
84
|
+
with lock:
|
|
85
|
+
if update.get("kind") != "progress":
|
|
86
|
+
if update.get("state") != "reused":
|
|
87
|
+
event(update)
|
|
88
|
+
return
|
|
89
|
+
count = int(update["completed"])
|
|
90
|
+
done[digest] = max(done.get(digest, 0), count)
|
|
91
|
+
fetched[digest] = max(fetched.get(digest, 0), count)
|
|
92
|
+
shown = max(shown, min(total, sum(done.values())))
|
|
93
|
+
event(
|
|
94
|
+
{
|
|
95
|
+
"kind": "progress",
|
|
96
|
+
"stage": "download",
|
|
97
|
+
"completed": shown,
|
|
98
|
+
"total": total,
|
|
99
|
+
"unit": "bytes",
|
|
100
|
+
**rate.fields(sum(fetched.values()), None),
|
|
101
|
+
**_eta(rate, total - shown),
|
|
102
|
+
}
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
path = cached_download(cache, artifact, report, download_fn)
|
|
106
|
+
with lock:
|
|
107
|
+
done[digest] = int(artifact["maxBytes"])
|
|
108
|
+
return path
|
|
109
|
+
|
|
110
|
+
pool = ThreadPoolExecutor(MODULE_DOWNLOADS)
|
|
111
|
+
try:
|
|
112
|
+
futures = {a["digest"]: pool.submit(fetch, a) for a in artifacts}
|
|
113
|
+
for future in as_completed(futures.values()):
|
|
114
|
+
future.result() # the first failure raises; the finally clause drops the queue
|
|
115
|
+
finally:
|
|
116
|
+
pool.shutdown(wait=True, cancel_futures=True)
|
|
117
|
+
return {digest: future.result() for digest, future in futures.items()}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _eta(rate: Rate, left: int) -> dict[str, int]:
|
|
121
|
+
return {"etaSeconds": -(-max(0, left) // rate.rate)} if rate.rate else {}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _wanted(plan: dict[str, Any]) -> list[dict[str, Any] | None]:
|
|
125
|
+
return [*plan["artifacts"], plan.get("nodeArtifact"), plan.get("launcherArtifact")]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def release_downloads(plan: dict[str, Any]) -> None:
|
|
129
|
+
"""Delete the cached artifacts once the install is published. A file left behind is harmless:
|
|
130
|
+
the next apply verifies its digest and reuses it."""
|
|
39
131
|
cache = downloads_dir(Path(plan["root"]), plan["runtime"])
|
|
40
|
-
|
|
41
|
-
|
|
132
|
+
for artifact in _wanted(plan):
|
|
133
|
+
if artifact:
|
|
134
|
+
with contextlib.suppress(OSError):
|
|
135
|
+
(cache / artifact["digest"]).unlink(missing_ok=True)
|
|
42
136
|
|
|
43
137
|
|
|
44
138
|
def take(kept: Path, file: Path) -> None:
|
|
45
|
-
|
|
139
|
+
# Copy, not move: the cache must survive a failed verification or interruption of this stage.
|
|
140
|
+
shutil.copyfile(kept, file)
|
|
46
141
|
private_permissions(file, created=True)
|
|
47
142
|
|
|
48
143
|
|
|
@@ -53,7 +148,7 @@ def install_tree(
|
|
|
53
148
|
*,
|
|
54
149
|
download_fn: Callable[..., Any] = download,
|
|
55
150
|
) -> Path:
|
|
56
|
-
tree = stage / "
|
|
151
|
+
tree = stage / "t" # short: see apply_plan
|
|
57
152
|
private_directory(tree)
|
|
58
153
|
fetched = fetch_all(plan, event, download_fn=download_fn)
|
|
59
154
|
for index, artifact in enumerate(plan["artifacts"]):
|
|
@@ -67,10 +162,11 @@ def install_tree(
|
|
|
67
162
|
else:
|
|
68
163
|
unpack = stage / f"unpack-{index}"
|
|
69
164
|
extract_archive(file, unpack)
|
|
70
|
-
if
|
|
165
|
+
if artifact.get("destination"): # a module of Pi's dependency tree
|
|
166
|
+
(top,) = unpack.iterdir() # npm drops the archive's one top directory
|
|
71
167
|
target = tree / artifact["destination"]
|
|
72
168
|
private_directory(target.parent)
|
|
73
|
-
|
|
169
|
+
top.rename(target)
|
|
74
170
|
else:
|
|
75
171
|
for entry in unpack.iterdir():
|
|
76
172
|
entry.rename(tree / entry.name)
|
|
@@ -23,6 +23,9 @@ from collections.abc import Callable
|
|
|
23
23
|
from pathlib import Path
|
|
24
24
|
from typing import Any, cast
|
|
25
25
|
|
|
26
|
+
# remote_ops before remote_ops_download: the bundle's entry module loads its siblings
|
|
27
|
+
from localmodels import region, remote_ops, remote_ops_download
|
|
28
|
+
|
|
26
29
|
Event = Callable[[dict[str, Any]], None]
|
|
27
30
|
|
|
28
31
|
|
|
@@ -329,11 +332,14 @@ def _extract_archive(archive: Path, target: Path) -> None:
|
|
|
329
332
|
private_permissions(destination, created=True)
|
|
330
333
|
return
|
|
331
334
|
with tarfile.open(archive) as tar:
|
|
332
|
-
|
|
333
|
-
|
|
335
|
+
# npm tarballs may repeat a/b as a/./b; the last wins, as with tar (scripts/pin_pi.py
|
|
336
|
+
# refuses a pinned Pi archive whose repeats differ).
|
|
337
|
+
entries_all = tar.getmembers()
|
|
338
|
+
for entry in entries_all: # every member, before a repeat could hide a link or device
|
|
334
339
|
_safe_member(entry.name)
|
|
335
340
|
if not (entry.isfile() or entry.isdir()):
|
|
336
341
|
raise ValueError("Unsafe archive member")
|
|
342
|
+
entries = list({_safe_member(e.name): e for e in entries_all}.values())
|
|
337
343
|
for entry in entries:
|
|
338
344
|
destination = target / _safe_member(entry.name)
|
|
339
345
|
if entry.isdir():
|
|
@@ -422,7 +428,7 @@ class Rate:
|
|
|
422
428
|
def fields(self, completed: int, total: int | None) -> dict[str, int]:
|
|
423
429
|
now = self.clock()
|
|
424
430
|
if now - self.mark >= 1.0:
|
|
425
|
-
self.rate = int((completed - self.marked) / (now - self.mark))
|
|
431
|
+
self.rate = max(0, int((completed - self.marked) / (now - self.mark)))
|
|
426
432
|
self.mark, self.marked = now, completed
|
|
427
433
|
if self.rate is None:
|
|
428
434
|
return {}
|
|
@@ -432,7 +438,7 @@ class Rate:
|
|
|
432
438
|
return found
|
|
433
439
|
|
|
434
440
|
|
|
435
|
-
def _transfer(url: str, part: Path, limit: int, event: Event) -> None:
|
|
441
|
+
def _transfer(url: str, part: Path, limit: int, event: Event, *, retry_missing: bool) -> None:
|
|
436
442
|
"""One request for the rest of ``part``; network failures raise _TransferError."""
|
|
437
443
|
have = part.stat().st_size
|
|
438
444
|
request = urllib.request.Request(url, headers={"User-Agent": "localmodels-runtime"})
|
|
@@ -441,6 +447,8 @@ def _transfer(url: str, part: Path, limit: int, event: Event) -> None:
|
|
|
441
447
|
try:
|
|
442
448
|
source = urllib.request.urlopen(request, timeout=30)
|
|
443
449
|
except urllib.error.HTTPError as exc:
|
|
450
|
+
if exc.code == 404 and retry_missing:
|
|
451
|
+
raise _TransferError("HTTP 404") from None
|
|
444
452
|
if exc.code == 416 and have:
|
|
445
453
|
part.write_bytes(b"") # the kept part no longer matches; start over
|
|
446
454
|
raise _TransferError("the server could not resume the download") from None
|
|
@@ -489,6 +497,18 @@ def _interrupted(exc: BaseException) -> _TransferError:
|
|
|
489
497
|
return _TransferError(reason, retryable=retryable)
|
|
490
498
|
|
|
491
499
|
|
|
500
|
+
def download_urls(url: str) -> list[str]:
|
|
501
|
+
"""``url`` and the other hosts serving the same file (the npm mirror for the npm registry
|
|
502
|
+
and nodejs.org), in the download region's order. A URL with no other host does not resolve
|
|
503
|
+
the region."""
|
|
504
|
+
source: remote_ops.Source = {"source": "", "url": url}
|
|
505
|
+
every = [url, *(s["url"] for s in remote_ops_download.alternates(source))]
|
|
506
|
+
if len(every) == 1:
|
|
507
|
+
return every
|
|
508
|
+
cn = [u for u in every if remote_ops_download.side(u) == "cn"]
|
|
509
|
+
return region.prefer(region.current_region(), [u for u in every if u not in cn], cn)
|
|
510
|
+
|
|
511
|
+
|
|
492
512
|
def download(
|
|
493
513
|
artifact: dict[str, Any],
|
|
494
514
|
destination: Path,
|
|
@@ -496,11 +516,48 @@ def download(
|
|
|
496
516
|
*,
|
|
497
517
|
attempts: int = DOWNLOAD_ATTEMPTS,
|
|
498
518
|
pause: Callable[[float], None] = time.sleep,
|
|
519
|
+
retry_missing: bool = False,
|
|
499
520
|
) -> None:
|
|
500
521
|
"""Fetch a pinned artifact into ``destination``, which must not exist. Network failures are
|
|
501
522
|
retried with backoff and each retry resumes ``destination.part``; a part left by an earlier
|
|
502
|
-
call is resumed too. Only content matching the pinned digest is published.
|
|
503
|
-
|
|
523
|
+
call is resumed too. Only content matching the pinned digest is published. When every
|
|
524
|
+
retry against one host fails, the next host serving the same file (``download_urls``) is
|
|
525
|
+
tried, and a success on the other region's side switches the region."""
|
|
526
|
+
urls = download_urls(artifact["url"])
|
|
527
|
+
preferred = remote_ops_download.side(urls[0])
|
|
528
|
+
failed_preferred = False
|
|
529
|
+
for index, url in enumerate(urls):
|
|
530
|
+
try:
|
|
531
|
+
_download_from(
|
|
532
|
+
url,
|
|
533
|
+
artifact,
|
|
534
|
+
destination,
|
|
535
|
+
event,
|
|
536
|
+
attempts=attempts,
|
|
537
|
+
pause=pause,
|
|
538
|
+
retry_missing=retry_missing,
|
|
539
|
+
)
|
|
540
|
+
except RuntimeDownloadError:
|
|
541
|
+
if index + 1 == len(urls):
|
|
542
|
+
raise
|
|
543
|
+
failed_preferred = failed_preferred or remote_ops_download.side(url) == preferred
|
|
544
|
+
continue
|
|
545
|
+
used = remote_ops_download.side(url)
|
|
546
|
+
if failed_preferred and used and used != preferred:
|
|
547
|
+
region.fallback_to(used)
|
|
548
|
+
return
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _download_from(
|
|
552
|
+
url: str,
|
|
553
|
+
artifact: dict[str, Any],
|
|
554
|
+
destination: Path,
|
|
555
|
+
event: Event,
|
|
556
|
+
*,
|
|
557
|
+
attempts: int,
|
|
558
|
+
pause: Callable[[float], None],
|
|
559
|
+
retry_missing: bool,
|
|
560
|
+
) -> None:
|
|
504
561
|
part = destination.with_name(destination.name + ".part")
|
|
505
562
|
if destination.exists() or destination.is_symlink():
|
|
506
563
|
raise ValueError("Runtime download destination exists")
|
|
@@ -516,7 +573,7 @@ def download(
|
|
|
516
573
|
while True:
|
|
517
574
|
attempt += 1
|
|
518
575
|
try:
|
|
519
|
-
_transfer(url, part, artifact["maxBytes"], event)
|
|
576
|
+
_transfer(url, part, artifact["maxBytes"], event, retry_missing=retry_missing)
|
|
520
577
|
break
|
|
521
578
|
except _TransferError as exc:
|
|
522
579
|
kept = part.stat().st_size
|