@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.
Files changed (82) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +81 -73
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/auth_proxy.py +74 -16
  6. package/modules/localmodels/bifrost_config.py +19 -0
  7. package/modules/localmodels/budget.py +27 -18
  8. package/modules/localmodels/catalog.json +18 -6
  9. package/modules/localmodels/chat_template.py +35 -0
  10. package/modules/localmodels/cli_parser.py +26 -3
  11. package/modules/localmodels/deploy.py +44 -10
  12. package/modules/localmodels/deploy_steps.py +6 -3
  13. package/modules/localmodels/download-mirrors.json +52 -4
  14. package/modules/localmodels/engines-b11583.json +20 -4
  15. package/modules/localmodels/engines-b12167.json +5 -1
  16. package/modules/localmodels/engines-strata-0.1.47.json +5 -1
  17. package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
  18. package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
  19. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
  20. package/modules/localmodels/engines-whisper-b5454.json +5 -1
  21. package/modules/localmodels/engines.json +55 -11
  22. package/modules/localmodels/frontend.py +5 -2
  23. package/modules/localmodels/gateway.py +2 -0
  24. package/modules/localmodels/gateway_bifrost.py +3 -0
  25. package/modules/localmodels/gateway_home.py +132 -0
  26. package/modules/localmodels/guard.py +15 -6
  27. package/modules/localmodels/harness.py +104 -37
  28. package/modules/localmodels/harness_gateway.py +9 -3
  29. package/modules/localmodels/harness_probe.py +5 -1
  30. package/modules/localmodels/hf_repo.py +15 -8
  31. package/modules/localmodels/library_gateway.py +28 -15
  32. package/modules/localmodels/library_jobs.py +7 -1
  33. package/modules/localmodels/library_serve.py +5 -0
  34. package/modules/localmodels/metal.py +29 -12
  35. package/modules/localmodels/metal_probe.py +16 -6
  36. package/modules/localmodels/npm_signatures.py +131 -0
  37. package/modules/localmodels/npm_transport.py +26 -10
  38. package/modules/localmodels/probe.py +4 -0
  39. package/modules/localmodels/process_identity.py +21 -5
  40. package/modules/localmodels/region.py +244 -0
  41. package/modules/localmodels/remote_ops.py +69 -13
  42. package/modules/localmodels/remote_ops_download.py +217 -10
  43. package/modules/localmodels/remote_ops_prepare.py +61 -8
  44. package/modules/localmodels/remote_ops_remove.py +15 -0
  45. package/modules/localmodels/remote_ops_service.py +10 -0
  46. package/modules/localmodels/runtime-lock.json +13 -13
  47. package/modules/localmodels/runtime_args.py +4 -2
  48. package/modules/localmodels/runtime_cli.py +76 -74
  49. package/modules/localmodels/runtime_discovery.py +58 -0
  50. package/modules/localmodels/runtime_install.py +103 -7
  51. package/modules/localmodels/runtime_io.py +64 -7
  52. package/modules/localmodels/runtime_pi.py +122 -0
  53. package/modules/localmodels/runtime_process.py +101 -15
  54. package/modules/localmodels/runtime_releases.py +51 -71
  55. package/modules/localmodels/service_deployment.py +5 -3
  56. package/modules/localmodels/service_probe.py +146 -31
  57. package/modules/localmodels/setup_inspection.py +110 -14
  58. package/modules/localmodels/setup_text.py +13 -0
  59. package/modules/localmodels/slot_cache.py +467 -0
  60. package/modules/localmodels/source_byok.py +484 -0
  61. package/modules/localmodels/source_byok_probe.py +275 -0
  62. package/modules/localmodels/source_cli.py +426 -0
  63. package/modules/localmodels/stack_args.py +2 -1
  64. package/modules/localmodels/stack_binding.py +125 -5
  65. package/modules/localmodels/stack_capacity.py +3 -3
  66. package/modules/localmodels/stack_down.py +22 -7
  67. package/modules/localmodels/stack_events.py +62 -0
  68. package/modules/localmodels/stack_hardware.py +20 -17
  69. package/modules/localmodels/stack_lifecycle.py +12 -3
  70. package/modules/localmodels/stack_rollback.py +9 -4
  71. package/modules/localmodels/stack_up.py +27 -20
  72. package/modules/localmodels/stack_update.py +3 -1
  73. package/modules/localmodels/tools.json +1365 -14
  74. package/modules/localmodels/transport.py +2 -0
  75. package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/METADATA +1 -1
  76. package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/RECORD +78 -70
  77. package/package.json +1 -1
  78. package/tool.json +1 -1
  79. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/WHEEL +0 -0
  80. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/entry_points.txt +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/NOTICE +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev38.dist-info → simplex_localmodels-0.1.0.dev40.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -18,13 +18,14 @@ import difflib
18
18
  import io
19
19
  import json
20
20
  import re
21
+ import urllib.error
21
22
  import urllib.parse
22
23
  import urllib.request
23
24
  from collections.abc import Callable, Sequence
24
25
  from typing import NamedTuple, TypedDict
25
26
 
26
27
  from localmodels import catalog as cat
27
- from localmodels import catalog_add
28
+ from localmodels import catalog_add, region
28
29
  from localmodels.contracts import decode
29
30
  from localmodels.gguf import SPLIT_PART_RE, GGUFHeader, model_id_from_stem, read_header_stream
30
31
  from localmodels.plan_envelope import PlanError
@@ -227,13 +228,19 @@ def entry_for(
227
228
  if not api:
228
229
  raise PlanError(f"--llm {spec} needs a Hub endpoint to resolve")
229
230
  repo, quant, revision = parts
230
- if revision:
231
- doc = decode(
232
- hf_get(f"{api}/api/models/{repo}/revision/{urllib.parse.quote(revision)}"),
233
- ModelInfo,
234
- )
235
- else:
236
- doc = decode(hf_get(f"{api}/api/models/{repo}"), ModelInfo)
231
+ # The pins of an ad-hoc repo are minted here: only from the Hub the user trusts, never from
232
+ # the region's mirror (region.MINT_REFUSAL).
233
+ first = f"{api}/api/models/{repo}" + (
234
+ f"/revision/{urllib.parse.quote(revision)}" if revision else ""
235
+ )
236
+ try:
237
+ doc = decode(hf_get(first), ModelInfo)
238
+ except urllib.error.HTTPError:
239
+ raise
240
+ except OSError as exc:
241
+ if region.explicit_hub(api):
242
+ raise
243
+ raise PlanError(region.MINT_REFUSAL.format(what=repo)) from exc
237
244
  commit = doc.get("sha")
238
245
  if not commit:
239
246
  raise PlanError(f"{repo} does not resolve on the Hub")
@@ -28,6 +28,7 @@ from localmodels import (
28
28
  bifrost_models,
29
29
  bifrost_unit,
30
30
  gateway_bifrost,
31
+ gateway_home,
31
32
  harness,
32
33
  harness_probe,
33
34
  hosts,
@@ -66,6 +67,16 @@ def pi_profile() -> Path:
66
67
  return Path(harness_probe.client_environment(hosts.tools_dir())["PI_CODING_AGENT_DIR"])
67
68
 
68
69
 
70
+ def _gateway_error(exc: Exception) -> LibraryError:
71
+ """GATEWAY_REGISTRATION_FAILED for ``exc``; a gateway-home this tool could not recover
72
+ (GitLab #15) adds ``cause`` and ``path`` for the installer's own remedy copy."""
73
+ if isinstance(exc, gateway_home.GatewayHomeError):
74
+ return LibraryError(
75
+ "GATEWAY_REGISTRATION_FAILED", str(exc), cause=exc.cause, path=str(exc.path)
76
+ )
77
+ return _fail(str(exc))
78
+
79
+
69
80
  def _fail(detail: str) -> LibraryError:
70
81
  return LibraryError("GATEWAY_REGISTRATION_FAILED", detail)
71
82
 
@@ -130,14 +141,16 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
130
141
  return record
131
142
 
132
143
 
133
- def _instance(facts: HostFacts | None) -> hosts.OwnedBifrost | None:
144
+ def ensure_instance(facts: HostFacts | None) -> hosts.OwnedBifrost | None:
145
+ """Return this tool's Bifrost record, installing it first when ``facts`` are supplied."""
134
146
  record = hosts.load_owned()["gateway"].get("bifrost")
135
147
  if record is None and facts is not None:
136
148
  record = _install(facts)
137
149
  return record
138
150
 
139
151
 
140
- def _sheet(app: Path) -> dict[str, Any]:
152
+ def read_sheet(app: Path) -> dict[str, Any]:
153
+ """Read the current model datasheet of ``app``, or an empty mapping when absent."""
141
154
  try:
142
155
  value = json.loads((app / bifrost_datasheet.DATASHEET).read_text(encoding="utf-8"))
143
156
  except (OSError, ValueError):
@@ -145,7 +158,7 @@ def _sheet(app: Path) -> dict[str, Any]:
145
158
  return value if isinstance(value, dict) else {}
146
159
 
147
160
 
148
- def _apply(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict[str, Any]) -> None:
161
+ def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict[str, Any]) -> None:
149
162
  """Write the config and datasheet; restart the instance when they changed. A gateway left
150
163
  with no provider at all (no library model, and nothing of the stack such as its LLM,
151
164
  decision model or foundation services) serves nobody: it is stopped instead, its record
@@ -381,11 +394,11 @@ def _register(
381
394
  shared = stack_provider is not None and _stack_owns_pi()
382
395
  if not shared:
383
396
  _pi_free(pi_provider)
384
- record = _instance(facts)
397
+ record = ensure_instance(facts)
385
398
  assert record is not None
386
399
  app = Path(record["app_dir"])
387
400
  config = gateway_bifrost.read_config(app)
388
- before, before_sheet = copy.deepcopy(config), _sheet(app)
401
+ before, before_sheet = copy.deepcopy(config), read_sheet(app)
389
402
  providers = config.setdefault("providers", {})
390
403
  if stack_provider is not None:
391
404
  providers[pid] = bifrost_provider.render("llm", url, name, key, pid)
@@ -399,7 +412,7 @@ def _register(
399
412
  before_sheet
400
413
  | bifrost_datasheet.sheets(pid, names, context)[bifrost_datasheet.DATASHEET]
401
414
  )
402
- _apply(record, config, sheet)
415
+ apply_config(record, config, sheet)
403
416
  try:
404
417
  if listed_as not in bifrost_models.listed(record["addr"]):
405
418
  raise _fail(f"Bifrost does not list {listed_as}")
@@ -416,12 +429,12 @@ def _register(
416
429
  _pi_add(pi_provider, pi_entry, base)
417
430
  except BaseException: # roll the gateway back to what it was before this call
418
431
  with contextlib.suppress(harness.HarnessError, OSError, ValueError, LibraryError):
419
- _apply(record, before, before_sheet)
432
+ apply_config(record, before, before_sheet)
420
433
  raise
421
434
  except LibraryError:
422
435
  raise
423
436
  except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
424
- raise _fail(str(exc)) from None
437
+ raise _gateway_error(exc) from None
425
438
  return added
426
439
 
427
440
 
@@ -431,7 +444,7 @@ def _unregister(registration: Registration) -> None:
431
444
  _unwire_member(registration)
432
445
  return
433
446
  _pi_drop(registration.get("pi_provider", PI_PROVIDER), registration["model"])
434
- record = _instance(None)
447
+ record = ensure_instance(None)
435
448
  if record is None:
436
449
  return
437
450
  app = Path(record["app_dir"])
@@ -441,10 +454,10 @@ def _unregister(registration: Registration) -> None:
441
454
  return
442
455
  del providers[registration["provider"]]
443
456
  prefix = registration["provider"] + "/"
444
- sheet = {k: v for k, v in _sheet(app).items() if not k.startswith(prefix)}
445
- _apply(record, config, sheet)
457
+ sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
458
+ apply_config(record, config, sheet)
446
459
  except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
447
- raise _fail(str(exc)) from None
460
+ raise _gateway_error(exc) from None
448
461
 
449
462
 
450
463
  def _stack_owns_pi() -> bool:
@@ -460,7 +473,7 @@ def _unwire_member(registration: Registration) -> None:
460
473
  gateway stops only when nothing at all is left for it to serve."""
461
474
  from localmodels import bifrost_clients, bifrost_pi
462
475
 
463
- record = _instance(None)
476
+ record = ensure_instance(None)
464
477
  app = Path(record["app_dir"]) if record else None
465
478
  config = gateway_bifrost.read_config(app) if app else {}
466
479
  providers = config.get("providers") or {}
@@ -478,5 +491,5 @@ def _unwire_member(registration: Registration) -> None:
478
491
  return
479
492
  _route_agent(config)
480
493
  prefix = registration["provider"] + "/"
481
- sheet = {k: v for k, v in _sheet(app).items() if not k.startswith(prefix)}
482
- _apply(record, config, sheet)
494
+ sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
495
+ apply_config(record, config, sheet)
@@ -26,6 +26,7 @@ from localmodels import (
26
26
  library_pricing,
27
27
  library_state,
28
28
  library_status,
29
+ metal,
29
30
  plan_envelope,
30
31
  process_identity,
31
32
  remote_ops_download,
@@ -45,7 +46,12 @@ from localmodels.transport import Executor
45
46
 
46
47
 
47
48
  def probe() -> HostFacts:
48
- return app.probe(hosts.LOCAL_ID)
49
+ """This computer's facts, an inference server's file-cached weights on a Mac out of the RAM
50
+ available (metal.foreign_cached_bytes; the library's own servers are not foreign)."""
51
+ facts = app.probe(hosts.LOCAL_ID)
52
+ if foreign := metal.foreign_cached_bytes(facts):
53
+ facts["ram"]["available_bytes"] = max(0, facts["ram"]["available_bytes"] - foreign)
54
+ return facts
49
55
 
50
56
 
51
57
  def executor() -> Executor:
@@ -266,6 +266,11 @@ def _admit(model: Model, record: Record, targets: list[Record], facts: HostFacts
266
266
  releasing the lock, so the next claimant sees it."""
267
267
  freed: dict[str, int] = {}
268
268
  for target in [*targets, *([record] if record["state"] != "idle" else [])]:
269
+ # A server that does not answer (failed, crashed, already stopped) is not counted:
270
+ # ``facts`` already count a gone one's memory as free (on a Mac its weights as file
271
+ # cache), and one still starting is priced as held.
272
+ if not library_status.answering(str(target["plan"]["endpoint"]["base_url"])):
273
+ continue
269
274
  pool = target["pool"]
270
275
  freed[pool] = freed.get(pool, 0) + library_pricing.memory_bytes(target["plan"])
271
276
  _room(facts, model, record, freed)
@@ -20,7 +20,7 @@ from collections.abc import Mapping
20
20
  from typing import TypedDict
21
21
 
22
22
  from localmodels.contracts import decode
23
- from localmodels.probe import GPU, HostFacts
23
+ from localmodels.probe import GPU, ComputeProcess, HostFacts
24
24
 
25
25
  GIB = 1 << 30
26
26
  METAL_UUID = "metal-0" # service_probe.METAL_UUID labels the processes it finds on the GPU
@@ -228,26 +228,43 @@ def conflicts(facts: HostFacts) -> list[str]:
228
228
  return found
229
229
 
230
230
 
231
- def owned_bytes(facts: HostFacts) -> int:
232
- """Resident memory of this tool's own servers on the GPU (service discovery's ``ps``)."""
231
+ def _metal_processes(facts: HostFacts) -> list[ComputeProcess]:
233
232
  services = facts.get("services")
234
233
  processes = (services.get("compute_processes") if services else None) or []
234
+ return [p for p in processes if p["gpu_uuid"] == METAL_UUID]
235
+
236
+
237
+ def owned_bytes(facts: HostFacts) -> int:
238
+ """What stopping this tool's own servers on the GPU gives back (service discovery's
239
+ ``ps``): their resident memory less their file cache, which the RAM available already
240
+ counts (``cached_bytes``)."""
241
+ return sum(
242
+ max(0, int(p.get("used_bytes") or 0) - int(p.get("cached_bytes") or 0))
243
+ for p in _metal_processes(facts)
244
+ if p["owned"] is True
245
+ )
246
+
247
+
248
+ def foreign_cached_bytes(facts: HostFacts) -> int:
249
+ """The file-cached weights of inference servers this tool does not own: an upstream server
250
+ unwires its weights a few minutes into idling, and macOS then counts them as available.
251
+ They are still that server's model (decision 43), so they are not free for a plan."""
235
252
  return sum(
236
- int(p.get("used_bytes") or 0)
237
- for p in processes
238
- if p["gpu_uuid"] == METAL_UUID and p["owned"] is True
253
+ int(p.get("cached_bytes") or 0) for p in _metal_processes(facts) if p["owned"] is not True
239
254
  )
240
255
 
241
256
 
242
257
  def reclaimed(facts: HostFacts) -> HostFacts:
243
- """``facts`` with this tool's own servers' memory back in the RAM available: a re-plan prices
244
- them as a fresh plan would, as the Linux suite slice is reclaimed (budget.host_ram)."""
245
- owned = owned_bytes(facts)
246
- if not owned:
258
+ """``facts`` with this tool's own servers' memory back in the RAM available, as a fresh plan
259
+ would price them (as the Linux suite slice is reclaimed, budget.host_ram), and another
260
+ server's file-cached weights out of it."""
261
+ owned, foreign = owned_bytes(facts), foreign_cached_bytes(facts)
262
+ if not owned and not foreign:
247
263
  return facts
248
264
  seen = copy.deepcopy(facts)
249
- seen["ram"]["available_bytes"] = min(
250
- seen["ram"]["total_bytes"], seen["ram"]["available_bytes"] + owned
265
+ ram = seen["ram"]
266
+ ram["available_bytes"] = max(
267
+ 0, min(ram["total_bytes"], ram["available_bytes"] + owned) - foreign
251
268
  )
252
269
  return seen
253
270
 
@@ -25,18 +25,28 @@ METAL = "/System/Library/Frameworks/Metal.framework/Metal"
25
25
 
26
26
 
27
27
  def available_memory(total_text: str, vm_stat: str) -> tuple[int, int]:
28
- """Available RAM from vm_stat's disjoint free, inactive and speculative page counts."""
28
+ """What macOS gives a new process without compressing or swapping anything: free pages,
29
+ file-backed pages (the file cache, including speculative read-ahead, which it drops first)
30
+ and purgeable pages (Activity Monitor's "available" memory). Inactive anonymous pages are
31
+ not counted: reusing them means compressing them. The three counts are disjoint: vm_stat's
32
+ file-backed plus anonymous pages are exactly its active, inactive and speculative pages, and
33
+ purgeable pages are anonymous. A model just unloaded leaves its weights in the file cache,
34
+ so free + inactive + speculative (before 0.1.0.dev39) missed them and refused to load the
35
+ same model again (Linger 0.1.3 RC3 on a 24 GB Mac)."""
36
+
37
+ def count(label: str) -> int | None:
38
+ found = re.search(rf"^{label}:[ \t]+(\d+)\.[ \t]*$", vm_stat, re.MULTILINE)
39
+ return int(found[1]) if found else None
40
+
29
41
  page = re.search(r"page size of (\d+) bytes\)", vm_stat)
30
- free = re.search(r"^Pages free:[ \t]+(\d+)\.[ \t]*$", vm_stat, re.MULTILINE)
31
- inactive = re.search(r"^Pages inactive:[ \t]+(\d+)\.[ \t]*$", vm_stat, re.MULTILINE)
32
- speculative = re.search(r"^Pages speculative:[ \t]+(\d+)\.[ \t]*$", vm_stat, re.MULTILINE)
33
- if not page or not free or not inactive or not speculative:
42
+ pages = [count(label) for label in ("Pages free", "File-backed pages", "Pages purgeable")]
43
+ if not page or None in pages:
34
44
  raise OSError("RAM measurement unavailable")
35
45
  try:
36
46
  total = int(total_text.strip())
37
47
  except ValueError:
38
48
  raise OSError("RAM measurement unavailable") from None
39
- available = (int(free[1]) + int(inactive[1]) + int(speculative[1])) * int(page[1])
49
+ available = sum(n for n in pages if n is not None) * int(page[1])
40
50
  if total <= 0 or int(page[1]) <= 0 or available > total:
41
51
  raise OSError("RAM measurement unavailable")
42
52
  return total, available
@@ -0,0 +1,131 @@
1
+ """npm registry signatures, checked without a crypto library (control-side code is stdlib).
2
+
3
+ registry.npmjs.org signs ``<name>@<version>:<dist.integrity>`` of every version with ECDSA
4
+ P-256 and SHA-256 (``dist.signatures``); npmmirror copies those signatures unchanged. When the
5
+ npm registry itself cannot be reached, runtime metadata read from the mirror is accepted only
6
+ if a signature verifies against a key pinned here, so the mirror never decides a digest.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import datetime as dt
13
+ import hashlib
14
+ from collections.abc import Mapping
15
+
16
+ # https://registry.npmjs.org/-/npm/v1/keys, read 2026-11-18. Both are ecdsa-sha2-nistp256 SPKI
17
+ # keys; a key past its ``expires`` is not accepted (fail closed).
18
+ NPM_KEYS = {
19
+ "SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA": (
20
+ "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE1Olb3zMAFFxXKHiIkQO5cJ3Yhl5i6UPp+IhuteBJbuHcA5UogKo0"
21
+ "EWtlWwW6KSaKoTNEYL7JlCQiVnkhBktUgg==",
22
+ "2025-01-29T00:00:00+00:00",
23
+ ),
24
+ "SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U": (
25
+ "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEY6Ya7W++7aUPzvMTrezH6Ycx3c+HOKYCcNGybJZSCJq/fd7Qa8uu"
26
+ "AKtdIkUQtQiEKERhAmE5lMMJhP8OkDOa2g==",
27
+ None,
28
+ ),
29
+ }
30
+
31
+ # NIST P-256 (SEC 2, secp256r1).
32
+ P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
33
+ A = P - 3
34
+ B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
35
+ N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
36
+ G = (
37
+ 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,
38
+ 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5,
39
+ )
40
+ SPKI_PREFIX = bytes.fromhex("3059301306072a8648ce3d020106082a8648ce3d030107034200")
41
+ Point = tuple[int, int] | None
42
+
43
+
44
+ def _add(p1: Point, p2: Point) -> Point:
45
+ if p1 is None:
46
+ return p2
47
+ if p2 is None:
48
+ return p1
49
+ (x1, y1), (x2, y2) = p1, p2
50
+ if x1 == x2 and (y1 + y2) % P == 0:
51
+ return None
52
+ if p1 == p2:
53
+ slope = (3 * x1 * x1 + A) * pow(2 * y1, -1, P) % P
54
+ else:
55
+ slope = (y2 - y1) * pow(x2 - x1, -1, P) % P
56
+ x3 = (slope * slope - x1 - x2) % P
57
+ return x3, (slope * (x1 - x3) - y1) % P
58
+
59
+
60
+ def _multiply(k: int, point: Point) -> Point:
61
+ result: Point = None
62
+ while k:
63
+ if k & 1:
64
+ result = _add(result, point)
65
+ point = _add(point, point)
66
+ k >>= 1
67
+ return result
68
+
69
+
70
+ def public_point(spki_b64: str) -> tuple[int, int]:
71
+ der = base64.b64decode(spki_b64, validate=True)
72
+ if len(der) != 91 or not der.startswith(SPKI_PREFIX) or der[26] != 4:
73
+ raise ValueError("not an uncompressed P-256 public key")
74
+ x, y = int.from_bytes(der[27:59], "big"), int.from_bytes(der[59:91], "big")
75
+ if (y * y - (x * x * x + A * x + B)) % P:
76
+ raise ValueError("public key is not on P-256")
77
+ return x, y
78
+
79
+
80
+ def _der_integer(der: bytes, offset: int) -> tuple[int, int]:
81
+ if der[offset] != 2 or der[offset + 1] > 33:
82
+ raise ValueError("bad DER integer")
83
+ end = offset + 2 + der[offset + 1]
84
+ return int.from_bytes(der[offset + 2 : end], "big"), end
85
+
86
+
87
+ def signature_values(der: bytes) -> tuple[int, int]:
88
+ """(r, s) of a DER ECDSA signature."""
89
+ if len(der) < 8 or der[0] != 0x30 or der[1] != len(der) - 2:
90
+ raise ValueError("bad DER signature")
91
+ r, offset = _der_integer(der, 2)
92
+ s, offset = _der_integer(der, offset)
93
+ if offset != len(der):
94
+ raise ValueError("bad DER signature")
95
+ return r, s
96
+
97
+
98
+ def verify(spki_b64: str, message: bytes, signature_b64: str) -> bool:
99
+ """ECDSA P-256 / SHA-256 verification of ``message``."""
100
+ try:
101
+ q = public_point(spki_b64)
102
+ r, s = signature_values(base64.b64decode(signature_b64, validate=True))
103
+ except (ValueError, IndexError):
104
+ return False
105
+ if not (0 < r < N and 0 < s < N):
106
+ return False
107
+ e = int.from_bytes(hashlib.sha256(message).digest(), "big")
108
+ w = pow(s, -1, N)
109
+ point = _add(_multiply(e * w % N, G), _multiply(r * w % N, q))
110
+ return point is not None and point[0] % N == r
111
+
112
+
113
+ def signed_by_npm(
114
+ name: str, version: str, dist: Mapping[str, object], now: dt.datetime | None = None
115
+ ) -> bool:
116
+ """Whether ``dist.signatures`` holds a valid signature of ``name@version:integrity`` by a
117
+ pinned npm registry key that has not expired."""
118
+ integrity, signatures = dist.get("integrity"), dist.get("signatures")
119
+ if not isinstance(integrity, str) or not isinstance(signatures, list):
120
+ return False
121
+ now = now or dt.datetime.now(dt.timezone.utc)
122
+ message = f"{name}@{version}:{integrity}".encode()
123
+ for entry in signatures:
124
+ if not isinstance(entry, dict):
125
+ continue
126
+ key = NPM_KEYS.get(str(entry.get("keyid")))
127
+ if key is None or (key[1] and dt.datetime.fromisoformat(key[1]) <= now):
128
+ continue
129
+ if verify(key[0], message, str(entry.get("sig", ""))):
130
+ return True
131
+ return False
@@ -100,8 +100,15 @@ class NpmPin(_ArchivePin):
100
100
  version: str
101
101
 
102
102
 
103
+ class NpmCopy(TypedDict):
104
+ package: str
105
+ version: str
106
+
107
+
103
108
  class _NpmBuild(TypedDict, total=False):
104
- npm: NpmPin
109
+ npm: NpmPin # Bifrost: the binary is this package's bifrost-http
110
+ npm_copy: NpmCopy # a GitHub-hosted tool: this package's file of the artifact's name
111
+ path: str # a pi dependency module: its place under pi's package root (since 2026-11-18)
105
112
 
106
113
 
107
114
  class Artifact(_NpmBuild):
@@ -171,6 +178,15 @@ def resolve_region(name: str, version: str, env: Mapping[str, str]) -> str:
171
178
  raise ValueError("SIMPLEX_REGION must be auto, global or cn")
172
179
  if region != "auto":
173
180
  return region
181
+ region = race(name, version, env) or "global"
182
+ host = urlsplit(package_url(name, version, region, env)).netloc
183
+ print(f"localmodels: using npm mirror {host} ({region})", file=sys.stderr)
184
+ return region
185
+
186
+
187
+ def race(name: str, version: str, env: Mapping[str, str]) -> str | None:
188
+ """The registry whose first 256 KiB of the package arrives first (5 s at most), or None when
189
+ neither answers: the probe ``region.current_region`` resolves the download region with."""
174
190
  completed: queue.Queue[tuple[str, bool]] = queue.Queue()
175
191
 
176
192
  def probe(candidate: str) -> None:
@@ -181,28 +197,27 @@ def resolve_region(name: str, version: str, env: Mapping[str, str]) -> str:
181
197
  for candidate in REGISTRIES:
182
198
  threading.Thread(target=probe, args=(candidate,), daemon=True).start()
183
199
  deadline = time.monotonic() + 5
184
- region = "global"
185
200
  for _ in REGISTRIES:
186
201
  try:
187
202
  candidate, success = completed.get(timeout=max(0, deadline - time.monotonic()))
188
203
  except queue.Empty:
189
204
  break
190
205
  if success:
191
- region = candidate
192
- break
193
- host = urlsplit(package_url(name, version, region, env)).netloc
194
- print(f"localmodels: using npm mirror {host} ({region})", file=sys.stderr)
195
- return region
206
+ return candidate
207
+ return None
196
208
 
197
209
 
198
210
  def download_package(pin: Mapping[str, Any], destination: Path, binary_size: int) -> str:
199
- """Only transport failures retry another region. A size or digest mismatch is fatal."""
211
+ """Only transport failures retry another region (and switch the process's region to it).
212
+ A size or digest mismatch is fatal."""
213
+ from localmodels import region as regions # region probes through this module
214
+
200
215
  cap = archive_size_cap(binary_size)
201
216
  if pin.get("bytes"):
202
217
  if not 0 < pin["bytes"] <= cap:
203
218
  raise ValueError("npm archive size pin exceeds limit")
204
219
  cap = pin["bytes"]
205
- region = resolve_region(pin["package"], pin["version"], os.environ)
220
+ region = regions.current_region()
206
221
  for attempt in range(2):
207
222
  url = package_url(pin["package"], pin["version"], region, os.environ)
208
223
  try:
@@ -227,7 +242,8 @@ def download_package(pin: Mapping[str, Any], destination: Path, binary_size: int
227
242
  ):
228
243
  destination.unlink(missing_ok=True)
229
244
  raise ValueError("npm archive SHA256 or size mismatch")
230
- os.environ["SIMPLEX_REGION"] = region
245
+ if attempt:
246
+ regions.fallback_to(region)
231
247
  return region
232
248
  raise AssertionError("unreachable npm failover")
233
249
 
@@ -101,6 +101,10 @@ class CgroupMemory(TypedDict):
101
101
 
102
102
  class _ComputeSince20261024(TypedDict, total=False):
103
103
  in_suite: bool # verified current-user deployment in the suite; never just a cgroup label
104
+ # A Mac process's resident file cache: its resident memory less its physical footprint
105
+ # (mapped GGUF weights that are not wired). The RAM available already counts these pages
106
+ # (metal_probe.available_memory), so a stop gives back only the rest. Absent: unknown.
107
+ cached_bytes: int
104
108
 
105
109
 
106
110
  class ComputeProcess(_ComputeSince20261024):
@@ -121,7 +121,8 @@ def _windows_process(pid: int) -> tuple[str, str, str | None] | None:
121
121
  error = ctypes.get_last_error() # type: ignore[attr-defined]
122
122
  if error == 87: # ERROR_INVALID_PARAMETER: no such process
123
123
  return None
124
- raise OSError(f"cannot open process {pid} (Windows error {error})")
124
+ cls = PermissionError if error == 5 else OSError # ERROR_ACCESS_DENIED
125
+ raise cls(f"cannot open process {pid} (Windows error {error})")
125
126
  try:
126
127
  code = wintypes.DWORD()
127
128
  if not kernel.GetExitCodeProcess(handle, ctypes.byref(code)):
@@ -152,8 +153,8 @@ def _windows_inspect(pid: int) -> Identity | None:
152
153
  return {"pid": pid, "uid": uid, "pgid": pid, "started": started}
153
154
 
154
155
 
155
- def _parent_pids() -> dict[int, int]:
156
- """Windows: {PID: parent PID} of every process (Toolhelp snapshot)."""
156
+ def _toolhelp_processes() -> dict[int, tuple[int, str]]:
157
+ """Windows: {PID: (parent PID, exe name)} of every process (Toolhelp snapshot)."""
157
158
  from ctypes import wintypes
158
159
 
159
160
  d, p = wintypes.DWORD, ctypes.c_void_p
@@ -173,18 +174,33 @@ def _parent_pids() -> dict[int, int]:
173
174
  snapshot = kernel.CreateToolhelp32Snapshot(0x2, 0) # TH32CS_SNAPPROCESS
174
175
  if snapshot in (None, wintypes.HANDLE(-1).value):
175
176
  raise OSError("process snapshot unavailable")
176
- found: dict[int, int] = {}
177
+ found: dict[int, tuple[int, str]] = {}
177
178
  try:
178
179
  entry = Entry(dwSize=ctypes.sizeof(Entry))
179
180
  more = kernel.Process32FirstW(snapshot, ctypes.byref(entry))
180
181
  while more:
181
- found[entry.th32ProcessID] = entry.th32ParentProcessID
182
+ found[entry.th32ProcessID] = (entry.th32ParentProcessID, entry.szExeFile)
182
183
  more = kernel.Process32NextW(snapshot, ctypes.byref(entry))
183
184
  finally:
184
185
  kernel.CloseHandle(snapshot)
185
186
  return found
186
187
 
187
188
 
189
+ def _parent_pids() -> dict[int, int]:
190
+ """Windows: {PID: parent PID} of every process (Toolhelp snapshot)."""
191
+ return {pid: parent for pid, (parent, _) in _toolhelp_processes().items()}
192
+
193
+
194
+ def windows_process_names() -> dict[int, str]:
195
+ """Windows: {PID: executable name} from a Toolhelp snapshot, or {} on failure."""
196
+ if not _windows():
197
+ return {}
198
+ try:
199
+ return {pid: name for pid, (_, name) in _toolhelp_processes().items() if name}
200
+ except OSError:
201
+ return {}
202
+
203
+
188
204
  def adopt_successor(pid_file: str | Path, program: str) -> bool:
189
205
  """Move stale Windows receipt to a single verifiable child running ``program`` (restart
190
206
  without exec, e.g. ``magpie serve``) when parent exited and exactly one newer user child matches."""