@simplexai/localmodels-darwin-arm64 0.1.0-dev.38 → 0.1.0-dev.39

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 (61) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +60 -54
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/bifrost_config.py +19 -0
  6. package/modules/localmodels/catalog.json +18 -6
  7. package/modules/localmodels/cli_parser.py +26 -3
  8. package/modules/localmodels/deploy.py +37 -9
  9. package/modules/localmodels/deploy_steps.py +6 -3
  10. package/modules/localmodels/download-mirrors.json +52 -4
  11. package/modules/localmodels/engines-b11583.json +20 -4
  12. package/modules/localmodels/engines-b12167.json +5 -1
  13. package/modules/localmodels/engines-strata-0.1.47.json +5 -1
  14. package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
  15. package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
  16. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
  17. package/modules/localmodels/engines-whisper-b5454.json +5 -1
  18. package/modules/localmodels/engines.json +55 -11
  19. package/modules/localmodels/frontend.py +5 -2
  20. package/modules/localmodels/guard.py +15 -6
  21. package/modules/localmodels/harness.py +65 -33
  22. package/modules/localmodels/harness_gateway.py +9 -3
  23. package/modules/localmodels/hf_repo.py +15 -8
  24. package/modules/localmodels/library_gateway.py +15 -13
  25. package/modules/localmodels/metal_probe.py +16 -6
  26. package/modules/localmodels/npm_signatures.py +131 -0
  27. package/modules/localmodels/npm_transport.py +26 -10
  28. package/modules/localmodels/process_identity.py +21 -5
  29. package/modules/localmodels/region.py +244 -0
  30. package/modules/localmodels/remote_ops.py +69 -13
  31. package/modules/localmodels/remote_ops_download.py +210 -10
  32. package/modules/localmodels/remote_ops_prepare.py +61 -8
  33. package/modules/localmodels/runtime-lock.json +13 -13
  34. package/modules/localmodels/runtime_args.py +4 -2
  35. package/modules/localmodels/runtime_cli.py +19 -37
  36. package/modules/localmodels/runtime_discovery.py +30 -0
  37. package/modules/localmodels/runtime_install.py +81 -6
  38. package/modules/localmodels/runtime_io.py +61 -5
  39. package/modules/localmodels/runtime_pi.py +79 -0
  40. package/modules/localmodels/runtime_process.py +99 -15
  41. package/modules/localmodels/runtime_releases.py +51 -71
  42. package/modules/localmodels/service_probe.py +62 -4
  43. package/modules/localmodels/setup_inspection.py +21 -4
  44. package/modules/localmodels/setup_text.py +6 -0
  45. package/modules/localmodels/source_byok.py +484 -0
  46. package/modules/localmodels/source_byok_probe.py +275 -0
  47. package/modules/localmodels/source_cli.py +426 -0
  48. package/modules/localmodels/stack_args.py +2 -1
  49. package/modules/localmodels/stack_binding.py +47 -4
  50. package/modules/localmodels/stack_events.py +3 -0
  51. package/modules/localmodels/stack_hardware.py +17 -3
  52. package/modules/localmodels/tools.json +1364 -14
  53. package/modules/localmodels/transport.py +2 -0
  54. package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/METADATA +1 -1
  55. package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/RECORD +57 -51
  56. package/package.json +1 -1
  57. package/tool.json +1 -1
  58. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/WHEEL +0 -0
  59. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/entry_points.txt +0 -0
  60. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/NOTICE +0 -0
  61. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -12,12 +12,14 @@ from __future__ import annotations
12
12
  import http.client
13
13
  import json
14
14
  import os
15
+ import shutil
16
+ import tarfile
15
17
  import threading
16
18
  import time
17
19
  import urllib.error
18
20
  import urllib.parse
19
21
  import urllib.request
20
- from typing import Tuple
22
+ from typing import Iterator, Tuple
21
23
 
22
24
  try:
23
25
  from localmodels import remote_ops, remote_ops_prepare
@@ -44,7 +46,15 @@ def act_engine(p: remote_ops.EngineParams) -> None:
44
46
  ):
45
47
  a = p["assets"][i]
46
48
  archive = os.path.join(cache, a["name"])
47
- remote_ops.fetch(a["url"], archive, a["sha256"], a["size_bytes"], a["name"])
49
+ remote_ops.fetch(
50
+ a["url"],
51
+ archive,
52
+ a["sha256"],
53
+ a["size_bytes"],
54
+ a["name"],
55
+ npm_copies(a),
56
+ p.get("region"),
57
+ )
48
58
  remote_ops.unpack(archive, directory)
49
59
  if not os.access(binary, os.X_OK):
50
60
  raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
@@ -93,9 +103,11 @@ def act_download(p: remote_ops.DownloadParams) -> None:
93
103
  raise RuntimeError(
94
104
  f"{f['dest']} has no download URL, and the reusable copy failed the SHA256 check"
95
105
  )
96
- remote_ops.fetch(f["url"], dest, f["sha256"], f["size_bytes"], label, f.get("mirrors"))
106
+ remote_ops.fetch(
107
+ f["url"], dest, f["sha256"], f["size_bytes"], label, f.get("mirrors"), p.get("region")
108
+ )
97
109
  if p.get("preparation"):
98
- remote_ops_prepare.prepare(p["preparation"], p["files"])
110
+ remote_ops_prepare.prepare(p["preparation"], p["files"], p.get("region"))
99
111
  remote_ops.emit("result", files=len(p["files"]))
100
112
 
101
113
 
@@ -108,18 +120,107 @@ SEGMENTS = 4
108
120
  MIN_SEGMENT_BYTES = 64 << 20
109
121
  ATTEMPTS = 5
110
122
  WEB = ("http", "https")
111
- SOURCE_HOSTS = (("huggingface.co", "huggingface"), ("modelscope.cn", "modelscope"))
123
+ SOURCE_HOSTS = (
124
+ ("hf-mirror.com", "hf-mirror"),
125
+ ("huggingface.co", "huggingface"),
126
+ ("modelscope.cn", "modelscope"),
127
+ ("npmmirror.com", "npmmirror"),
128
+ )
129
+ # Which side of the network each host serves best. A host on neither (GitHub, a LAN registry,
130
+ # a user's own mirror) is neutral: it is never a reason to switch the region.
131
+ GLOBAL_HOSTS = ("huggingface.co", "registry.npmjs.org", "nodejs.org")
132
+ CN_HOSTS = ("hf-mirror.com", "modelscope.cn", "npmmirror.com")
133
+ # The same bytes under another host: (global prefix, cn prefix). Region "cn" tries the cn copy
134
+ # first; "global" keeps today's sources first and tries the cn copy only after them.
135
+ ALTERNATES = (
136
+ ("https://huggingface.co/", "https://hf-mirror.com/"),
137
+ ("https://registry.npmjs.org/", "https://registry.npmmirror.com/"),
138
+ ("https://nodejs.org/dist/", "https://cdn.npmmirror.com/binaries/node/"),
139
+ )
140
+ NPM_REGISTRIES = (
141
+ ("npm", "https://registry.npmjs.org"),
142
+ ("npmmirror", "https://registry.npmmirror.com"),
143
+ )
144
+ # Region cn's order by label; within one rank the plan's order holds. A non-public source (a
145
+ # LAN registry or mirror, remote_ops.non_public) comes first, then ModelScope and the npm
146
+ # mirror, then another neutral source (a user's public mirror, the original GitHub asset), then
147
+ # hf-mirror.com, then the global hosts.
148
+ CN_RANK = {"modelscope": 1, "npmmirror": 1, "custom": 2, "hf-mirror": 3}
149
+
150
+
151
+ def cn_rank(source: remote_ops.Source) -> int:
152
+ return 0 if remote_ops.non_public(source["url"]) else CN_RANK.get(source["source"], 4)
153
+
154
+
155
+ NPM_OVERHEAD_BYTES = 4 << 20
156
+
157
+
158
+ def _host_in(url: str, domains: tuple[str, ...]) -> bool:
159
+ host = (urllib.parse.urlsplit(url).hostname or "").lower()
160
+ return any(host == d or host.endswith("." + d) for d in domains)
112
161
 
113
162
 
114
163
  def source_name(url: str) -> str:
115
- """The public label of a download URL: huggingface, modelscope or custom (never the URL)."""
116
- host = (urllib.parse.urlsplit(url).hostname or "").lower()
164
+ """The public label of a download URL: huggingface, hf-mirror, modelscope, npmmirror or
165
+ custom (never the URL)."""
117
166
  for domain, name in SOURCE_HOSTS:
118
- if host == domain or host.endswith("." + domain):
167
+ if _host_in(url, (domain,)):
119
168
  return name
120
169
  return "custom"
121
170
 
122
171
 
172
+ def side(url: str) -> str:
173
+ """``cn``, ``global`` or "" (neutral) for a download URL."""
174
+ return "cn" if _host_in(url, CN_HOSTS) else "global" if _host_in(url, GLOBAL_HOSTS) else ""
175
+
176
+
177
+ def alternates(source: remote_ops.Source) -> list[remote_ops.Source]:
178
+ """Other hosts that serve the same path: hf-mirror.com for huggingface.co, the npm mirror for
179
+ the npm registry and nodejs.org's releases, and the other way round."""
180
+ found: list[remote_ops.Source] = []
181
+ for pair in ALTERNATES:
182
+ for here, there in (pair, pair[::-1]):
183
+ if source["url"].startswith(here):
184
+ url = there + source["url"][len(here) :]
185
+ other: remote_ops.Source = {"source": source_name(url), "url": url}
186
+ if source.get("member"):
187
+ other["member"] = source["member"]
188
+ found.append(other)
189
+ return found
190
+
191
+
192
+ def npm_copies(asset: remote_ops.Archive) -> list[remote_ops.Source]:
193
+ """The npm packages holding a byte-identical copy of ``asset`` (``npm_copy`` in the engine
194
+ and tool locks), on the npm registry and its China mirror; the copy is the package's file of
195
+ the asset's name, and its SHA256 pin is the asset's."""
196
+ copy = asset.get("npm_copy")
197
+ if not copy:
198
+ return []
199
+ name, version = copy["package"], copy["version"]
200
+ tail = f"{name}/-/{name.split('/')[-1]}-{version}.tgz"
201
+ return [
202
+ {"source": label, "url": f"{base}/{tail}", "member": "package/" + asset["name"]}
203
+ for label, base in NPM_REGISTRIES
204
+ ]
205
+
206
+
207
+ def candidates(
208
+ sources: list[remote_ops.Source], region: str | None
209
+ ) -> tuple[list[remote_ops.Source], list[remote_ops.Source]]:
210
+ """(the plan's own sources, the alternates added for the region), without duplicates."""
211
+ own: list[remote_ops.Source] = []
212
+ for s in sources:
213
+ if s.get("url") and all(s["url"] != o["url"] for o in own):
214
+ own.append(s)
215
+ extra: list[remote_ops.Source] = []
216
+ if region in ("cn", "global"):
217
+ for s in own:
218
+ for alt in alternates(s):
219
+ if all(alt["url"] != o["url"] for o in own + extra):
220
+ extra.append(alt)
221
+ return own, extra
222
+
223
+
123
224
  def _ranged_request(url: str, start: int, end: int) -> urllib.request.Request:
124
225
  request = urllib.request.Request(url, headers={"User-Agent": "localmodels-deploy"})
125
226
  request.add_header("Range", f"bytes={start}-{end - 1}")
@@ -157,9 +258,15 @@ def probe(url: str, size: int) -> tuple[float, bool] | None:
157
258
  return got / max(1e-3, time.monotonic() - start), ranged
158
259
 
159
260
 
160
- def rank(sources: list[remote_ops.Source], size: int, label: str) -> list[_Ranked]:
261
+ def rank(
262
+ sources: list[remote_ops.Source],
263
+ size: int,
264
+ label: str,
265
+ unreachable: list[remote_ops.Source] | None = None,
266
+ ) -> list[_Ranked]:
161
267
  """The sources fastest first, each with whether it serves ranges; ones that failed the probe
162
- go last in plan order, so a passing hiccup still leaves them as a fallback."""
268
+ go last in plan order (and into ``unreachable``), so a passing hiccup still leaves them as
269
+ a fallback."""
163
270
  measured: list[tuple[float, int, _Ranked]] = []
164
271
  failed: list[_Ranked] = []
165
272
  notes = []
@@ -168,6 +275,8 @@ def rank(sources: list[remote_ops.Source], size: int, label: str) -> list[_Ranke
168
275
  if result is None: # try ranges anyway: a resumed .part must not restart on a hiccup
169
276
  failed.append((source, urllib.parse.urlsplit(source["url"]).scheme in WEB))
170
277
  notes.append(source["source"] + " unreachable")
278
+ if unreachable is not None:
279
+ unreachable.append(source)
171
280
  else:
172
281
  measured.append((-result[0], i, (source, result[1])))
173
282
  notes.append("{} {:.1f} MB/s".format(source["source"], result[0] / 1e6))
@@ -178,6 +287,50 @@ def rank(sources: list[remote_ops.Source], size: int, label: str) -> list[_Ranke
178
287
  return [r for _, _, r in sorted(measured)] + failed
179
288
 
180
289
 
290
+ def _web(source: remote_ops.Source) -> bool:
291
+ return urllib.parse.urlsplit(source["url"]).scheme in WEB
292
+
293
+
294
+ def ordered(
295
+ sources: list[remote_ops.Source],
296
+ size: int,
297
+ label: str,
298
+ region: str | None,
299
+ failed: list[remote_ops.Source],
300
+ ) -> Iterator[_Ranked]:
301
+ """The sources to try in turn. Without a region, ``rank``'s speed order as before. In
302
+ global, the plan's own sources keep that order and the cn alternates follow. In cn, the
303
+ CN_RANK order: each source is probed only when its turn comes, one that fails the probe is
304
+ added to ``failed`` and moved last, and the first that passes is used. npm packages (a
305
+ ``member``) cannot be probed for the pinned size; they are tried as they come."""
306
+ own, extra = candidates(sources, region)
307
+ if region != "cn":
308
+ yield from rank([s for s in own if not s.get("member")], size, label, failed)
309
+ rest = [s for s in own if s.get("member")] + extra
310
+ rest.sort(key=lambda s: side(s["url"]) == "cn")
311
+ yield from ((s, _web(s) and not s.get("member")) for s in rest)
312
+ return
313
+ queue = sorted(own + extra, key=cn_rank)
314
+ demoted: list[remote_ops.Source] = []
315
+ notes = []
316
+ for source in queue:
317
+ if source.get("member"):
318
+ yield source, False
319
+ continue
320
+ result = probe(source["url"], size)
321
+ if result is None:
322
+ notes.append(source["source"] + " unreachable")
323
+ failed.append(source)
324
+ demoted.append(source)
325
+ continue
326
+ notes.append("{} {:.1f} MB/s".format(source["source"], result[0] / 1e6))
327
+ remote_ops.emit(
328
+ "log", message="download source for {} (region cn): {}".format(label, ", ".join(notes))
329
+ )
330
+ yield source, result[1]
331
+ yield from ((s, _web(s)) for s in demoted)
332
+
333
+
181
334
  class _NoRangeError(Exception):
182
335
  """The source stopped honouring byte ranges; the next source is tried."""
183
336
 
@@ -319,6 +472,53 @@ def transfer(source: remote_ops.Source, part: str, size: int, label: str, ranged
319
472
  _finish(job, label)
320
473
 
321
474
 
475
+ def npm_transfer(source: remote_ops.Source, part: str, size: int, label: str) -> None:
476
+ """Fill ``part`` with the ``member`` file of the npm package at ``source``: the package is
477
+ read in one bounded stream (an npm tarball is a gzip of the file, so a little larger than
478
+ it), then only that regular file of exactly ``size`` bytes is taken. The caller checks its
479
+ SHA256 against the asset's pin as for any other source."""
480
+ archive = part + ".npm"
481
+ cap = size + size // 64 + NPM_OVERHEAD_BYTES
482
+ request = urllib.request.Request(source["url"], headers={"User-Agent": "localmodels-deploy"})
483
+ got, start, mark = 0, time.monotonic(), time.monotonic()
484
+ try:
485
+ with urllib.request.urlopen(request, timeout=60) as r, open(archive, "wb") as out:
486
+ while True:
487
+ chunk = r.read(remote_ops._CHUNK)
488
+ if not chunk:
489
+ break
490
+ got += len(chunk)
491
+ if got > cap:
492
+ raise RuntimeError(f"the npm copy of {label} exceeds its size limit")
493
+ out.write(chunk)
494
+ if time.monotonic() - mark >= remote_ops._PROGRESS_EVERY_S:
495
+ mark = time.monotonic()
496
+ remote_ops.emit(
497
+ "progress",
498
+ phase="download",
499
+ file=label,
500
+ done=min(got, size),
501
+ total=size,
502
+ bytes_per_s=int(got / max(1e-3, mark - start)),
503
+ source=source["source"],
504
+ connections=1,
505
+ **remote_ops.step_fields(min(got, size)),
506
+ )
507
+ with tarfile.open(archive) as tar:
508
+ member = tar.getmember(source["member"])
509
+ stream = tar.extractfile(member) if member.isfile() and member.size == size else None
510
+ if stream is None:
511
+ raise RuntimeError(f"the npm copy of {label} does not hold a {size}-byte file")
512
+ discard(_state_path(part)) # part is rewritten whole, not resumed
513
+ with stream, open(part, "wb") as out:
514
+ shutil.copyfileobj(stream, out, remote_ops._CHUNK)
515
+ except KeyError:
516
+ raise RuntimeError(f"the npm copy of {label} does not hold {source['member']}") from None
517
+ finally:
518
+ if os.path.exists(archive):
519
+ os.remove(archive)
520
+
521
+
322
522
  def _finish(job: _Transfer, label: str) -> None:
323
523
  if job.errors:
324
524
  raise job.errors[0]
@@ -204,7 +204,7 @@ def _inputs(
204
204
  raise
205
205
 
206
206
 
207
- def _gguf_source(spec: remote_ops.StrataPreparation, work: str) -> str:
207
+ def _gguf_source(spec: remote_ops.StrataPreparation, work: str, region: str | None) -> str:
208
208
  asset = spec["gguf_py"]
209
209
  if (
210
210
  not asset["name"]
@@ -213,7 +213,9 @@ def _gguf_source(spec: remote_ops.StrataPreparation, work: str) -> str:
213
213
  ):
214
214
  raise RuntimeError("Strata preparation source archive needs a file name")
215
215
  archive = os.path.join(work, asset["name"])
216
- remote_ops.fetch(asset["url"], archive, asset["sha256"], asset["size_bytes"], asset["name"])
216
+ remote_ops.fetch(
217
+ asset["url"], archive, asset["sha256"], asset["size_bytes"], asset["name"], None, region
218
+ )
217
219
  source_file: remote_ops.Download = {
218
220
  "dest": archive,
219
221
  "url": asset["url"],
@@ -232,7 +234,53 @@ def _gguf_source(spec: remote_ops.StrataPreparation, work: str) -> str:
232
234
  return gguf_py
233
235
 
234
236
 
235
- def _environment(spec: remote_ops.StrataPreparation, gguf_py: str) -> dict[str, str]:
237
+ HF_API = "https://huggingface.co"
238
+ HF_MIRROR = "https://hf-mirror.com" # region.HF_MIRROR; this bundle imports no controller module
239
+
240
+
241
+ def hub_endpoints(endpoint: str, region: str | None) -> list[str]:
242
+ """The Hubs the preparation tools may read, in order: for the plan's default Hugging Face,
243
+ hf-mirror.com beside it (first in cn); a Hub the plan names is the only one. Every output
244
+ is checked against its pin, so the order only decides speed."""
245
+ if endpoint.rstrip("/") != HF_API or region not in ("cn", "global"):
246
+ return [endpoint]
247
+ return [HF_MIRROR, HF_API] if region == "cn" else [HF_API, HF_MIRROR]
248
+
249
+
250
+ def _generate_from_hubs(
251
+ spec: remote_ops.StrataPreparation,
252
+ group: str,
253
+ outputs: _Group,
254
+ stage: str,
255
+ work: str,
256
+ env: dict[str, str],
257
+ lock_fd: int,
258
+ region: str | None,
259
+ ) -> None:
260
+ """Generate one group; a group that reads the Hub (the MTP head) is retried from the other
261
+ Hub when the first fails, and a success there switches the region (``region_fallback``)."""
262
+ hubs = hub_endpoints(spec["hf_endpoint"], region) if group != spec["pack"] else [""]
263
+ for index, hub in enumerate(hubs):
264
+ if hub:
265
+ env["HF_ENDPOINT"] = hub
266
+ try:
267
+ _generate(spec, group, outputs, stage, work, env, lock_fd)
268
+ except RuntimeError as exc:
269
+ if index + 1 == len(hubs):
270
+ raise
271
+ remote_ops.emit("log", phase="prepare", message=f"{exc}; trying the other Hub")
272
+ shutil.rmtree(os.path.join(stage, group), ignore_errors=True)
273
+ continue
274
+ if index:
275
+ side = "cn" if hub == HF_MIRROR else "global"
276
+ switch = {"region_fallback": side} if side != region else {}
277
+ remote_ops.emit("log", phase="prepare", message="read the other Hub", **switch)
278
+ return
279
+
280
+
281
+ def _environment(
282
+ spec: remote_ops.StrataPreparation, gguf_py: str, region: str | None
283
+ ) -> dict[str, str]:
236
284
  env = {
237
285
  key: value for key, value in os.environ.items() if not key.startswith(("PYTHON", "STRATA_"))
238
286
  }
@@ -242,7 +290,7 @@ def _environment(spec: remote_ops.StrataPreparation, gguf_py: str) -> dict[str,
242
290
  STRATA_MTP_REVISION=spec["mtp_revision"],
243
291
  STRATA_ALLOW_UNPINNED="0",
244
292
  STRATA_EXIT_WITH_PARENT="1",
245
- HF_ENDPOINT=spec["hf_endpoint"],
293
+ HF_ENDPOINT=hub_endpoints(spec["hf_endpoint"], region)[0],
246
294
  )
247
295
  return env
248
296
 
@@ -355,8 +403,13 @@ def verify_reused_outputs(files: list[remote_ops.Reusable]) -> None:
355
403
  _receipt(path, file["sha256"])
356
404
 
357
405
 
358
- def prepare(spec: remote_ops.StrataPreparation, files: list[remote_ops.Reusable]) -> None:
359
- """Generate missing groups, check their exact pins, and atomically publish their files."""
406
+ def prepare(
407
+ spec: remote_ops.StrataPreparation,
408
+ files: list[remote_ops.Reusable],
409
+ region: str | None = None,
410
+ ) -> None:
411
+ """Generate missing groups, check their exact pins, and atomically publish their files.
412
+ In region cn the tools read the Hub through hf-mirror.com unless the plan names its own."""
360
413
  if spec["kind"] != KIND or spec["mtp_revision"] != MTP_REVISION:
361
414
  raise RuntimeError("unsupported Strata preparation kind or MTP revision")
362
415
  if os.name != "posix" or spec["scratch_bytes"] < 0:
@@ -406,9 +459,9 @@ def prepare(spec: remote_ops.StrataPreparation, files: list[remote_ops.Reusable]
406
459
  )
407
460
  stage = os.path.join(work, "model")
408
461
  os.makedirs(stage, mode=0o700, exist_ok=True)
409
- env = _environment(spec, _gguf_source(spec, work))
462
+ env = _environment(spec, _gguf_source(spec, work, region), region)
410
463
  for group, outputs in needed.items():
411
- _generate(spec, group, outputs, stage, work, env, lock_fd)
464
+ _generate_from_hubs(spec, group, outputs, stage, work, env, lock_fd, region)
412
465
  try:
413
466
  for relative, file in outputs:
414
467
  _require_file(os.path.join(stage, relative), file)
@@ -2,7 +2,7 @@
2
2
  "schema": "localmodels.runtime-lock/v1",
3
3
  "versions": {
4
4
  "codex": "0.150.1",
5
- "claude": "2.1.310"
5
+ "claude": "2.1.311"
6
6
  },
7
7
  "artifacts": {
8
8
  "codex/win32-x64": [
@@ -57,9 +57,9 @@
57
57
  ],
58
58
  "claude/win32-arm64": [
59
59
  {
60
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.310/win32-arm64/claude.exe",
60
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.311/win32-arm64/claude.exe",
61
61
  "algorithm": "sha256",
62
- "digest": "91da8a2247a8806162319bcdf3e70c6ffeeb58b568481a9827fbff167a694edb",
62
+ "digest": "951b5d94bf2a5296db2c442784e68d18fa04dec2d7d2e805aa50e75d618aad5e",
63
63
  "maxBytes": 419430400,
64
64
  "format": "binary",
65
65
  "executable": "claude.exe"
@@ -67,9 +67,9 @@
67
67
  ],
68
68
  "claude/win32-x64": [
69
69
  {
70
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.310/win32-x64/claude.exe",
70
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.311/win32-x64/claude.exe",
71
71
  "algorithm": "sha256",
72
- "digest": "f9a3920634ae3b961ee92c2eb58d0051f5f8852b120983d0a4f57b6a5efeba61",
72
+ "digest": "966f4b2ce962298f5dee6a942e8c47c8f97392e69e728e622319a98b259c0680",
73
73
  "maxBytes": 419430400,
74
74
  "format": "binary",
75
75
  "executable": "claude.exe"
@@ -77,9 +77,9 @@
77
77
  ],
78
78
  "claude/darwin-arm64": [
79
79
  {
80
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.310/darwin-arm64/claude",
80
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.311/darwin-arm64/claude",
81
81
  "algorithm": "sha256",
82
- "digest": "ffb64331bc0ee1b69efb7c2c428bd3ab516bc31b75bf60886b356c97c1c25ffd",
82
+ "digest": "85d8c08707fcfd1e78ffa0204eefbc6ec9e4fe22f375fb2767ef85d957ed3161",
83
83
  "maxBytes": 419430400,
84
84
  "format": "binary",
85
85
  "executable": "claude"
@@ -87,9 +87,9 @@
87
87
  ],
88
88
  "claude/darwin-x64": [
89
89
  {
90
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.310/darwin-x64/claude",
90
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.311/darwin-x64/claude",
91
91
  "algorithm": "sha256",
92
- "digest": "28fdbed5a84ef7d4205b5751c7f021e79151c4e319c4a401e48fe6aae86bbb39",
92
+ "digest": "d34e1cb82015b050471a97574aa6ea6f698ecf3a97a61c980961f43ad9f838f5",
93
93
  "maxBytes": 419430400,
94
94
  "format": "binary",
95
95
  "executable": "claude"
@@ -97,9 +97,9 @@
97
97
  ],
98
98
  "claude/linux-arm64": [
99
99
  {
100
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.310/linux-arm64/claude",
100
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.311/linux-arm64/claude",
101
101
  "algorithm": "sha256",
102
- "digest": "9c64d9a7442436b65fcd7cc02c1aa0051bb5a7041e7788576ed3b5f29c447d54",
102
+ "digest": "2e2496c9a8065df93acb0fca2d341f59a6b8777649b2e025ab8c9bcd5eef61f3",
103
103
  "maxBytes": 419430400,
104
104
  "format": "binary",
105
105
  "executable": "claude"
@@ -107,9 +107,9 @@
107
107
  ],
108
108
  "claude/linux-x64": [
109
109
  {
110
- "url": "https://downloads.claude.ai/claude-code-releases/2.1.310/linux-x64/claude",
110
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.311/linux-x64/claude",
111
111
  "algorithm": "sha256",
112
- "digest": "b73676430af12f97316a798b8371f81d640f90a58bdcb8f3ce56a835bb47df56",
112
+ "digest": "86dc1fcc69498159eaf15f446613e847010f9036bfbbdffd4c49350be8489ada",
113
113
  "maxBytes": 419430400,
114
114
  "format": "binary",
115
115
  "executable": "claude"
@@ -53,8 +53,10 @@ DOCS: dict[str, tuple[str, str, list[tuple[str, str]]]] = {
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
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 "
56
+ "A fresh install uses the bundled lock; Pi comes with its whole dependency tree. "
57
+ "--before-version selects an earlier stable Codex or Claude release after a failed "
58
+ "launch; Pi has only its pinned release. "
59
+ "No archive is downloaded. The plan's id "
58
60
  "(a SHA256 of the plan) is the --approve value.",
59
61
  [("%(prog)s --root ~/harness --runtime codex --out plan.json", "")],
60
62
  ),
@@ -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/node_modules/" + module["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,
@@ -419,44 +419,20 @@ def build_plan(
419
419
  version=status["version"],
420
420
  )
421
421
  lock = _lock()
422
- if runtime == "codex" and plan["action"] == "install":
422
+ if runtime == "codex" and plan["action"] == "install" and before_version is not None:
423
423
  plan["version"], plan["artifacts"] = _codex_release(
424
424
  plan["platform"], before_version=before_version
425
425
  )
426
426
  plan["artifactSource"] = "codex-stable-npm"
427
427
  if runtime == "pi" and plan["action"] == "install":
428
- node_version = lock["node"]["version"]
429
- if node:
430
- if not Path(node).is_absolute() or not Path(node).is_file():
431
- raise ValueError("Pi requires an absolute regular private Node path")
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":
428
+ runtime_pi.plan_install(
429
+ plan, lock, node, launcher, before_version, platform=_platform(), probe=_probe
430
+ )
431
+ if runtime == "claude" and plan["action"] == "install" and before_version is not None:
456
432
  plan["version"], plan["artifacts"] = _external_release(
457
- runtime, plan["platform"], before_version=before_version, node_version=node_version
433
+ runtime, plan["platform"], before_version=before_version
458
434
  )
459
- plan["artifactSource"] = f"{runtime}-stable"
435
+ plan["artifactSource"] = "claude-stable"
460
436
  if before_version is not None:
461
437
  plan["beforeVersion"] = before_version
462
438
  plan["id"] = plan_id(plan)
@@ -542,7 +518,7 @@ def _validate_plan_artifacts(plan: dict[str, Any]) -> None:
542
518
  ):
543
519
  raise ValueError("Invalid Codex registry plan")
544
520
  expected_version, expected_artifacts = _codex_release(_platform(), plan["version"])
545
- elif runtime in ("claude", "pi") and plan.get("artifactSource") == f"{runtime}-stable":
521
+ elif runtime == "claude" and plan.get("artifactSource") == "claude-stable":
546
522
  if plan["action"] != "install" or not isinstance(plan["version"], str):
547
523
  raise ValueError("Invalid stable runtime plan")
548
524
  expected_version, expected_artifacts = _external_release(
@@ -591,6 +567,7 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
591
567
  event({"kind": "stage", "stage": "reuse", "state": "succeeded"})
592
568
  return inspect_runtimes(root, before_versions=before_versions)
593
569
  target = root / "tools" / runtime / plan["version"]
570
+ runtime_pi.replace_broken(target, plan, pi_loads_extensions)
594
571
  if target.exists() or target.is_symlink():
595
572
  # An owned complete install can be safely retried, but unrelated/broken content is never overwritten.
596
573
  marker = target / "localmodels-runtime.json"
@@ -626,6 +603,10 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
626
603
  code, version = _probe(command + ["--version"])
627
604
  try:
628
605
  _require_installed_version(code, version, plan["version"])
606
+ if runtime == "pi" and not pi_loads_extensions(command):
607
+ raise RuntimeVersionVerificationError(
608
+ "RUNTIME_EXTENSIONS_FAILED", "Pi could not load an extension."
609
+ )
629
610
  except RuntimeVersionVerificationError as error:
630
611
  event(
631
612
  {
@@ -641,6 +622,7 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
641
622
  marker.write_text(json.dumps({"schema": "localmodels.runtime-owned/v1", "planId": approve}))
642
623
  private_permissions(marker, created=True)
643
624
  tree.rename(target)
625
+ runtime_install.release_downloads(plan)
644
626
  event({"kind": "stage", "stage": "install", "state": "succeeded"})
645
627
  return inspect_runtimes(root, before_versions=before_versions)
646
628