@simplexai/localmodels-darwin-arm64 0.1.0-dev.37 → 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 (86) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +85 -78
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/bifrost_checks.py +9 -6
  6. package/modules/localmodels/bifrost_config.py +35 -1
  7. package/modules/localmodels/bifrost_datasheet.py +12 -2
  8. package/modules/localmodels/catalog.json +155 -8
  9. package/modules/localmodels/catalog.py +19 -1
  10. package/modules/localmodels/catalog_recipes.py +33 -2
  11. package/modules/localmodels/cli_parser.py +26 -3
  12. package/modules/localmodels/deploy.py +37 -9
  13. package/modules/localmodels/deploy_steps.py +6 -3
  14. package/modules/localmodels/download-mirrors.json +52 -4
  15. package/modules/localmodels/engines-b11583.json +20 -4
  16. package/modules/localmodels/engines-b12167.json +5 -1
  17. package/modules/localmodels/engines-strata-0.1.47.json +5 -1
  18. package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
  19. package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
  20. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
  21. package/modules/localmodels/engines-whisper-b5454.json +5 -1
  22. package/modules/localmodels/engines.json +55 -11
  23. package/modules/localmodels/frontend.py +5 -2
  24. package/modules/localmodels/gateway_bifrost.py +11 -9
  25. package/modules/localmodels/gateway_cli.py +4 -2
  26. package/modules/localmodels/guard.py +15 -6
  27. package/modules/localmodels/harness.py +65 -33
  28. package/modules/localmodels/harness_gateway.py +9 -3
  29. package/modules/localmodels/hf_repo.py +15 -8
  30. package/modules/localmodels/library_gateway.py +26 -13
  31. package/modules/localmodels/library_jobs.py +51 -3
  32. package/modules/localmodels/library_model.py +10 -0
  33. package/modules/localmodels/library_pricing.py +29 -22
  34. package/modules/localmodels/library_serve.py +5 -0
  35. package/modules/localmodels/library_state.py +9 -1
  36. package/modules/localmodels/library_status.py +30 -0
  37. package/modules/localmodels/llm_rank.py +83 -30
  38. package/modules/localmodels/metal_probe.py +16 -6
  39. package/modules/localmodels/npm_signatures.py +131 -0
  40. package/modules/localmodels/npm_transport.py +26 -10
  41. package/modules/localmodels/process_identity.py +32 -5
  42. package/modules/localmodels/recommend.py +5 -2
  43. package/modules/localmodels/region.py +244 -0
  44. package/modules/localmodels/remote_ops.py +69 -13
  45. package/modules/localmodels/remote_ops_download.py +210 -10
  46. package/modules/localmodels/remote_ops_prepare.py +61 -8
  47. package/modules/localmodels/runtime-lock.json +13 -13
  48. package/modules/localmodels/runtime_args.py +4 -2
  49. package/modules/localmodels/runtime_cli.py +19 -37
  50. package/modules/localmodels/runtime_discovery.py +30 -0
  51. package/modules/localmodels/runtime_install.py +81 -6
  52. package/modules/localmodels/runtime_io.py +61 -5
  53. package/modules/localmodels/runtime_pi.py +79 -0
  54. package/modules/localmodels/runtime_process.py +99 -15
  55. package/modules/localmodels/runtime_releases.py +51 -71
  56. package/modules/localmodels/search_server.py +5 -1
  57. package/modules/localmodels/service_probe.py +62 -4
  58. package/modules/localmodels/setup_inspection.py +21 -4
  59. package/modules/localmodels/setup_text.py +6 -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.py +31 -14
  64. package/modules/localmodels/stack_args.py +8 -4
  65. package/modules/localmodels/stack_binding.py +47 -4
  66. package/modules/localmodels/stack_cli.py +2 -0
  67. package/modules/localmodels/stack_compose.py +5 -5
  68. package/modules/localmodels/stack_events.py +3 -0
  69. package/modules/localmodels/stack_hardware.py +21 -6
  70. package/modules/localmodels/stack_llm_ram.py +16 -6
  71. package/modules/localmodels/stack_picks.py +4 -4
  72. package/modules/localmodels/stack_progress.py +9 -1
  73. package/modules/localmodels/stack_run.py +29 -0
  74. package/modules/localmodels/stack_suite.py +10 -3
  75. package/modules/localmodels/stack_warm.py +45 -4
  76. package/modules/localmodels/tools.json +1396 -32
  77. package/modules/localmodels/transport.py +40 -13
  78. package/modules/localmodels/windows_job.py +69 -0
  79. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/METADATA +1 -1
  80. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/RECORD +82 -75
  81. package/package.json +1 -1
  82. package/tool.json +1 -1
  83. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/WHEEL +0 -0
  84. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/entry_points.txt +0 -0
  85. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/NOTICE +0 -0
  86. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -11,6 +11,7 @@ stay in ``catalog``.
11
11
  from __future__ import annotations
12
12
 
13
13
  from collections.abc import Iterable, Mapping
14
+ from dataclasses import dataclass
14
15
 
15
16
  from localmodels import metal, vision
16
17
  from localmodels.budget import HARNESS_RAM, RAM_FLOOR, host_ram
@@ -70,37 +71,79 @@ PRODUCT_DEFAULTS = {
70
71
  }
71
72
 
72
73
 
73
- # The installed SimplexAI score at which a fitting model takes over from the user-selected small-Mac
74
- # default (roadmap decision 40, 2026-11-09: intelligence first): 50 is the AIHOT reference-model
75
- # mean. A 24 GB Mac with the memory free holds Qwen3.8-27B UD-IQ3_S (52); one under desktop load,
76
- # and every 16 GB Mac, keeps LFM3 rather than a lower-scored model such as Ling-3.0-tiny (25).
74
+ # The installed SimplexAI score at which a validated model takes over from the Mac ladder
75
+ # (roadmap decision 40, 2026-11-09: intelligence first): 50 is the AIHOT reference-model mean.
76
+ # A 24 GB Mac with the memory free holds Qwen3.8-27B UD-IQ3_S (52); one under desktop load, and
77
+ # every 16 GB Mac, stays on the ladder rather than a lower-scored model such as Qwen3.6-35B-A3B.
77
78
  MAC_DEFAULT_YIELD_SCORE = 50
78
79
 
80
+ # The Mac small-memory ladder (roadmap decision 57, 2026-11-16, user-selected; it replaces
81
+ # decision 39's LFM3-1.7B): on every Apple Silicon Mac of MAC_LADDER_MIN_BYTES or more, while no
82
+ # validated model scoring MAC_DEFAULT_YIELD_SCORE or more fits, the smartest pick is the first
83
+ # rung that fits, best first. The rungs are candidates outside SimplexAI ranking: their catalog
84
+ # numbers are unranked (0) or vendor anchors and never compete with installed scores.
85
+ MAC_LADDER = ("spark-x2.6-4b-q4km", "spark-x2.6-1.7b")
86
+ MAC_LADDER_MIN_BYTES = 16 * metal.GIB
87
+ # --prefer fastest on a Mac below this much memory tries the small rung first (16 GB: the 1.7B);
88
+ # larger Macs try the 4B first (24 GB: Spark-X2.6-4B Q4_K_M), beside any validated model.
89
+ MAC_SMALL_BELOW_BYTES = 20 * metal.GIB
90
+ # Validated darwin entries the ladder replaces in automatic selection (decision 57): Ling-3.0-tiny
91
+ # (25) was the 32 GB+ fallback. Explicit --llm still installs it.
92
+ MAC_LADDER_REPLACES = frozenset({"ling-3.0-tiny"})
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class MacLadder:
97
+ """One Mac's ladder: ``smartest`` in fallback order, ``fastest`` in the order --prefer fastest
98
+ tries the rungs (one rung at most joins the validated models in the speed race)."""
99
+
100
+ smartest: tuple[str, ...]
101
+ fastest: tuple[str, ...]
102
+
103
+ def rename(self, ids: Mapping[str, str]) -> MacLadder:
104
+ """The same ladder under other ids (a library's model ids), dropping absent rungs."""
105
+ return MacLadder(
106
+ tuple(ids[i] for i in self.smartest if i in ids),
107
+ tuple(ids[i] for i in self.fastest if i in ids),
108
+ )
79
109
 
80
- def mac_default(facts: HostFacts) -> str | None:
81
- """User-selected small-Mac default (roadmap decision 39), outside SimplexAI ranking; it yields
82
- to a fitting model scoring MAC_DEFAULT_YIELD_SCORE or more (decision 40, ``keeps_default``)."""
83
- if metal.supported(facts) and 16 * metal.GIB <= facts["ram"]["total_bytes"] <= 24 * metal.GIB:
84
- return "lfm3-1.7b"
85
- return None
110
+
111
+ def mac_ladder(facts: HostFacts) -> MacLadder | None:
112
+ """This Mac's ladder (decision 57), or None off Apple Silicon and below 16 GB."""
113
+ if not metal.supported(facts) or facts["ram"]["total_bytes"] < MAC_LADDER_MIN_BYTES:
114
+ return None
115
+ small = facts["ram"]["total_bytes"] < MAC_SMALL_BELOW_BYTES
116
+ return MacLadder(MAC_LADDER, tuple(reversed(MAC_LADDER)) if small else MAC_LADDER)
117
+
118
+
119
+ def mac_rung(entry: CatalogEntry, facts: HostFacts) -> bool:
120
+ """The entry is a rung of this Mac's ladder."""
121
+ ladder = mac_ladder(facts)
122
+ return ladder is not None and entry.status != "deprecated" and entry.id in ladder.smartest
86
123
 
87
124
 
88
125
  def keeps_default(scores: Iterable[int]) -> bool:
89
- """The small-Mac default stands unless one of the fitting models' scores reaches the yield."""
126
+ """The ladder stands unless one of the other fitting models' scores reaches the yield."""
90
127
  return all(score < MAC_DEFAULT_YIELD_SCORE for score in scores)
91
128
 
92
129
 
93
130
  def listed_default(facts: HostFacts, fits: list[tuple[str, int]]) -> str | None:
94
- """The small-Mac default to list first among ``(id, score)`` fits, or None once another fit
95
- reaches the yield score (decision 40)."""
96
- default = mac_default(facts)
97
- return default if keeps_default(q for i, q in fits if i != default) else None
131
+ """The ladder rung to list first among ``(id, score)`` fits, or None once another fit
132
+ reaches the yield score (decision 40) or no rung fits."""
133
+ ladder = mac_ladder(facts)
134
+ if ladder is None:
135
+ return None
136
+ rungs = [i for i in ladder.smartest if i in {i for i, _ in fits}]
137
+ others = (q for i, q in fits if i not in ladder.smartest)
138
+ return rungs[0] if rungs and keeps_default(others) else None
98
139
 
99
140
 
100
141
  def automatic_here(entry: CatalogEntry, facts: HostFacts) -> bool:
101
- """Validated entries and the scoped Mac default / Windows fallback candidates."""
142
+ """Validated entries and the scoped Mac ladder / Windows fallback candidates."""
143
+ if entry.id in MAC_LADDER_REPLACES and mac_ladder(facts) is not None:
144
+ return False
102
145
  return (
103
- (entry.status != "deprecated" and entry.id == mac_default(facts))
146
+ mac_rung(entry, facts)
104
147
  or windows_fallback(entry, facts)
105
148
  or validated_here(entry, facts["platform"])
106
149
  )
@@ -261,24 +304,34 @@ def rank_key(
261
304
  def choose(
262
305
  ranked: list[tuple[tuple[int, float], str, int]],
263
306
  prefer: str,
264
- default: str | None = None,
307
+ ladder: MacLadder | None = None,
265
308
  *,
266
309
  fallback_ids: Iterable[str] = (),
267
310
  ) -> tuple[str, int]:
268
311
  """(entry id, card index) out of ``(rank_key, id, card)`` triples for one scenario: fastest
269
- takes the highest decode speed whatever the score (the score breaks ties); otherwise the
270
- small-Mac ``default`` when it fits and keeps_default holds for the others; else smartest and
312
+ takes the highest decode speed whatever the score (the score breaks ties); smartest and
271
313
  concurrent take the best score (speed breaks ties); fast takes the fastest whose score is
272
- within FAST_QUALITY_BAND of the best. Scoped ``fallback_ids`` are considered only when
273
- no primary fits on any eligible card."""
314
+ within FAST_QUALITY_BAND of the best. Scoped ``fallback_ids`` are considered only when no
315
+ primary fits on any eligible card. On a Mac ``ladder`` rungs never rank by score: smartest
316
+ takes the first fitting rung while keeps_default holds for the other fits, and fastest races
317
+ the first fitting rung of ``ladder.fastest`` against the other fits."""
274
318
  fallback = set(fallback_ids)
275
319
  ranked = [row for row in ranked if row[1] not in fallback] or ranked
320
+ if ladder is not None:
321
+ rungs = {row[1]: row for row in ranked if row[1] in ladder.smartest}
322
+ primary = [row for row in ranked if row[1] not in rungs]
323
+ if prefer == "fastest":
324
+ rung = next((rungs[i] for i in ladder.fastest if i in rungs), None)
325
+ pool = primary + ([rung] if rung is not None else [])
326
+ _, entry_id, index = max(pool, key=lambda t: (t[0][1], t[0][0]))
327
+ return entry_id, index
328
+ if rungs and keeps_default(key[0] for key, _, _ in primary):
329
+ _, entry_id, index = next(rungs[i] for i in ladder.smartest if i in rungs)
330
+ return entry_id, index
331
+ ranked = primary or ranked
276
332
  if prefer == "fastest":
277
333
  _, entry_id, index = max(ranked, key=lambda t: (t[0][1], t[0][0]))
278
334
  return entry_id, index
279
- mine = [(entry_id, index) for _, entry_id, index in ranked if entry_id == default]
280
- if mine and keeps_default(key[0] for key, entry_id, _ in ranked if entry_id != default):
281
- return mine[0]
282
335
  if prefer == "fast":
283
336
  best = max(key[0] for key, _, _ in ranked)
284
337
  near = [t for t in ranked if t[0][0] >= best - FAST_QUALITY_BAND]
@@ -293,7 +346,7 @@ def recommended_entry(
293
346
  entries: tuple[CatalogEntry, ...],
294
347
  *,
295
348
  backend: str = "auto",
296
- default_id: str | None = None,
349
+ ladder: tuple[str, ...] = (),
297
350
  ) -> tuple[CatalogEntry, str] | None:
298
351
  """The default pick for THIS budget, with its reason key: product-default,
299
352
  best-quality-resident, or speed-gated-quality. Only resident entries that pass
@@ -312,10 +365,10 @@ def recommended_entry(
312
365
  return predicted_decode_tok_s(t[0], t[1].variant, budget, backend=backend)
313
366
 
314
367
  resident = [(e, c) for e, c in fitting if c.zero_spill and agent_ready(e, c.variant, budget)]
315
- if keeps_default(e.quality for e, _ in resident if e.id != default_id):
316
- for entry, _ in resident:
317
- if entry.id == default_id:
318
- return entry, "user-default"
368
+ rungs = {e.id: e for e, _ in resident if e.id in ladder}
369
+ resident = [(e, c) for e, c in resident if e.id not in rungs]
370
+ if rungs and keeps_default(e.quality for e, _ in resident):
371
+ return next(rungs[i] for i in ladder if i in rungs), "user-default"
319
372
  product_default = PRODUCT_DEFAULTS.get(hardware_key(budget, backend))
320
373
  for entry, _ in resident:
321
374
  if entry.id == product_default:
@@ -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."""
@@ -278,6 +294,17 @@ def _taskkill(pid: int, force: bool) -> bool:
278
294
  return subprocess.run(argv, capture_output=True, timeout=30, check=False).returncode == 0
279
295
 
280
296
 
297
+ def stop_children(pid: int) -> int:
298
+ """Windows: force-end the trees of ``pid``'s child processes (not ``pid`` itself); how many
299
+ children it found. A download ends the helper it runs this way when it is cancelled."""
300
+ if not _windows():
301
+ raise RuntimeError("stop_children is for Windows")
302
+ children = [child for child, parent in _parent_pids().items() if parent == pid and child > 0]
303
+ for child in children:
304
+ _taskkill(child, True)
305
+ return len(children)
306
+
307
+
281
308
  def windows_stop_tree(pid: int, saved: Identity, grace: float) -> bool:
282
309
  """Stop PID and descendants via polite ``taskkill /T`` (capped at 2 s) then ``/F``."""
283
310
  import time
@@ -77,7 +77,10 @@ _QUANT_REASONS = {
77
77
  }
78
78
  RECOMMENDED_REASONS = {
79
79
  "windows-candidate-fallback": llm_rank.WINDOWS_FALLBACK_WARNING,
80
- "user-default": "User-selected small-Mac default; SimplexAI score and full acceptance pending.",
80
+ "user-default": (
81
+ "User-selected Mac small-memory ladder (Spark-X2.6, 64K shared by two slots); "
82
+ "SimplexAI score and full acceptance pending."
83
+ ),
81
84
  "product-default": "This machine's default model, chosen by its maker.",
82
85
  "best-quality-resident": (
83
86
  "Candidates that pass the agent capacity gate are ranked by capability score first, "
@@ -171,7 +174,7 @@ def recommendation(
171
174
  placement.budget,
172
175
  live,
173
176
  backend=placement.backend,
174
- default_id=llm_rank.mac_default(facts),
177
+ ladder=ladder.smartest if (ladder := llm_rank.mac_ladder(facts)) else (),
175
178
  )
176
179
  if picked is not None:
177
180
  return picked[0], picked[1], placement