@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
@@ -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")
@@ -130,14 +130,16 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
130
130
  return record
131
131
 
132
132
 
133
- def _instance(facts: HostFacts | None) -> hosts.OwnedBifrost | None:
133
+ def ensure_instance(facts: HostFacts | None) -> hosts.OwnedBifrost | None:
134
+ """Return this tool's Bifrost record, installing it first when ``facts`` are supplied."""
134
135
  record = hosts.load_owned()["gateway"].get("bifrost")
135
136
  if record is None and facts is not None:
136
137
  record = _install(facts)
137
138
  return record
138
139
 
139
140
 
140
- def _sheet(app: Path) -> dict[str, Any]:
141
+ def read_sheet(app: Path) -> dict[str, Any]:
142
+ """Read the current model datasheet of ``app``, or an empty mapping when absent."""
141
143
  try:
142
144
  value = json.loads((app / bifrost_datasheet.DATASHEET).read_text(encoding="utf-8"))
143
145
  except (OSError, ValueError):
@@ -145,7 +147,7 @@ def _sheet(app: Path) -> dict[str, Any]:
145
147
  return value if isinstance(value, dict) else {}
146
148
 
147
149
 
148
- def _apply(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict[str, Any]) -> None:
150
+ def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict[str, Any]) -> None:
149
151
  """Write the config and datasheet; restart the instance when they changed. A gateway left
150
152
  with no provider at all (no library model, and nothing of the stack such as its LLM,
151
153
  decision model or foundation services) serves nobody: it is stopped instead, its record
@@ -381,11 +383,11 @@ def _register(
381
383
  shared = stack_provider is not None and _stack_owns_pi()
382
384
  if not shared:
383
385
  _pi_free(pi_provider)
384
- record = _instance(facts)
386
+ record = ensure_instance(facts)
385
387
  assert record is not None
386
388
  app = Path(record["app_dir"])
387
389
  config = gateway_bifrost.read_config(app)
388
- before, before_sheet = copy.deepcopy(config), _sheet(app)
390
+ before, before_sheet = copy.deepcopy(config), read_sheet(app)
389
391
  providers = config.setdefault("providers", {})
390
392
  if stack_provider is not None:
391
393
  providers[pid] = bifrost_provider.render("llm", url, name, key, pid)
@@ -399,7 +401,7 @@ def _register(
399
401
  before_sheet
400
402
  | bifrost_datasheet.sheets(pid, names, context)[bifrost_datasheet.DATASHEET]
401
403
  )
402
- _apply(record, config, sheet)
404
+ apply_config(record, config, sheet)
403
405
  try:
404
406
  if listed_as not in bifrost_models.listed(record["addr"]):
405
407
  raise _fail(f"Bifrost does not list {listed_as}")
@@ -416,7 +418,7 @@ def _register(
416
418
  _pi_add(pi_provider, pi_entry, base)
417
419
  except BaseException: # roll the gateway back to what it was before this call
418
420
  with contextlib.suppress(harness.HarnessError, OSError, ValueError, LibraryError):
419
- _apply(record, before, before_sheet)
421
+ apply_config(record, before, before_sheet)
420
422
  raise
421
423
  except LibraryError:
422
424
  raise
@@ -431,7 +433,7 @@ def _unregister(registration: Registration) -> None:
431
433
  _unwire_member(registration)
432
434
  return
433
435
  _pi_drop(registration.get("pi_provider", PI_PROVIDER), registration["model"])
434
- record = _instance(None)
436
+ record = ensure_instance(None)
435
437
  if record is None:
436
438
  return
437
439
  app = Path(record["app_dir"])
@@ -441,8 +443,8 @@ def _unregister(registration: Registration) -> None:
441
443
  return
442
444
  del providers[registration["provider"]]
443
445
  prefix = registration["provider"] + "/"
444
- sheet = {k: v for k, v in _sheet(app).items() if not k.startswith(prefix)}
445
- _apply(record, config, sheet)
446
+ sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
447
+ apply_config(record, config, sheet)
446
448
  except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
447
449
  raise _fail(str(exc)) from None
448
450
 
@@ -460,7 +462,7 @@ def _unwire_member(registration: Registration) -> None:
460
462
  gateway stops only when nothing at all is left for it to serve."""
461
463
  from localmodels import bifrost_clients, bifrost_pi
462
464
 
463
- record = _instance(None)
465
+ record = ensure_instance(None)
464
466
  app = Path(record["app_dir"]) if record else None
465
467
  config = gateway_bifrost.read_config(app) if app else {}
466
468
  providers = config.get("providers") or {}
@@ -478,5 +480,5 @@ def _unwire_member(registration: Registration) -> None:
478
480
  return
479
481
  _route_agent(config)
480
482
  prefix = registration["provider"] + "/"
481
- sheet = {k: v for k, v in _sheet(app).items() if not k.startswith(prefix)}
482
- _apply(record, config, sheet)
483
+ sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
484
+ apply_config(record, config, sheet)
@@ -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
 
@@ -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."""