@simplexai/localmodels-darwin-arm64 0.1.0-dev.44 → 0.1.0-dev.47

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 +81 -83
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +0 -1
  5. package/modules/localmodels/bifrost_checks.py +3 -127
  6. package/modules/localmodels/bifrost_clients.py +1 -1
  7. package/modules/localmodels/bifrost_config.py +2 -2
  8. package/modules/localmodels/bifrost_pi.py +1 -1
  9. package/modules/localmodels/budget.py +16 -1
  10. package/modules/localmodels/catalog.json +165 -50
  11. package/modules/localmodels/catalog.py +20 -5
  12. package/modules/localmodels/catalog_recipes.py +9 -1
  13. package/modules/localmodels/context_policy.py +32 -9
  14. package/modules/localmodels/deploy.py +20 -14
  15. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +98 -0
  16. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +41 -1
  17. package/modules/localmodels/engines.py +28 -2
  18. package/modules/localmodels/estimator.py +12 -3
  19. package/modules/localmodels/gateway.py +50 -15
  20. package/modules/localmodels/gateway_accept.py +8 -5
  21. package/modules/localmodels/gateway_bifrost.py +108 -34
  22. package/modules/localmodels/gateway_cli.py +5 -2
  23. package/modules/localmodels/gateway_requests.py +9 -2
  24. package/modules/localmodels/gguf.py +6 -2
  25. package/modules/localmodels/harness.py +38 -11
  26. package/modules/localmodels/harness_gateway.py +1 -1
  27. package/modules/localmodels/harness_probe.py +60 -13
  28. package/modules/localmodels/hosts.py +7 -20
  29. package/modules/localmodels/library_gateway.py +12 -9
  30. package/modules/localmodels/library_pricing.py +7 -9
  31. package/modules/localmodels/library_state.py +6 -4
  32. package/modules/localmodels/npm_transport.py +62 -54
  33. package/modules/localmodels/probe.py +38 -11
  34. package/modules/localmodels/process_identity.py +47 -33
  35. package/modules/localmodels/process_identity_linux.py +135 -0
  36. package/modules/localmodels/process_windows.py +150 -1
  37. package/modules/localmodels/recommend.py +1 -1
  38. package/modules/localmodels/recommend_cli.py +2 -2
  39. package/modules/localmodels/remote_ops.py +14 -6
  40. package/modules/localmodels/remote_ops_download.py +1 -1
  41. package/modules/localmodels/remote_ops_verify.py +0 -33
  42. package/modules/localmodels/runtime_install.py +2 -1
  43. package/modules/localmodels/runtime_io.py +149 -34
  44. package/modules/localmodels/runtime_windows_acl.py +100 -0
  45. package/modules/localmodels/service_probe.py +26 -20
  46. package/modules/localmodels/setup_inspection.py +132 -36
  47. package/modules/localmodels/setup_text.py +14 -0
  48. package/modules/localmodels/source_byok.py +6 -3
  49. package/modules/localmodels/source_cli.py +8 -1
  50. package/modules/localmodels/stack.py +1 -5
  51. package/modules/localmodels/stack_args.py +6 -8
  52. package/modules/localmodels/stack_binding.py +61 -3
  53. package/modules/localmodels/stack_compose.py +3 -8
  54. package/modules/localmodels/stack_events.py +2 -1
  55. package/modules/localmodels/stack_lifecycle.py +7 -4
  56. package/modules/localmodels/stack_plan.py +1 -4
  57. package/modules/localmodels/stack_ports.py +0 -1
  58. package/modules/localmodels/stack_run.py +15 -30
  59. package/modules/localmodels/stack_suite.py +23 -46
  60. package/modules/localmodels/stack_summary.py +0 -1
  61. package/modules/localmodels/stack_try.py +3 -92
  62. package/modules/localmodels/stack_up.py +7 -3
  63. package/modules/localmodels/stack_update.py +5 -5
  64. package/modules/localmodels/stack_view_apply.py +1 -1
  65. package/modules/localmodels/stack_view_llm.py +1 -1
  66. package/modules/localmodels/stack_view_sandbox.py +3 -3
  67. package/modules/localmodels/stack_view_text.py +0 -1
  68. package/modules/localmodels/stack_view_words.py +0 -1
  69. package/modules/localmodels/stack_warm.py +18 -7
  70. package/modules/localmodels/strata_poly_server.py +4 -2
  71. package/modules/localmodels/suite.py +4 -7
  72. package/modules/localmodels/transport.py +7 -1
  73. package/modules/localmodels/tui_dialogs.py +0 -1
  74. package/modules/localmodels/web/view/view.css +0 -3
  75. package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/METADATA +1 -1
  76. package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/RECORD +78 -80
  77. package/package.json +1 -1
  78. package/tool.json +1 -1
  79. package/modules/localmodels/bifrost_search.py +0 -66
  80. package/modules/localmodels/gateway_search.py +0 -223
  81. package/modules/localmodels/search-ddgs-9.16.1.txt +0 -222
  82. package/modules/localmodels/search_server.py +0 -474
  83. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/WHEEL +0 -0
  84. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/entry_points.txt +0 -0
  85. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/licenses/NOTICE +0 -0
  86. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev47.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -342,9 +342,12 @@ def ensure_binary(root: Path, kind: str, event: runtime_io.Event) -> None:
342
342
  if reuse_binary(artifact, staged):
343
343
  event({"kind": "stage", "stage": f"reuse-{kind}", "state": "succeeded"})
344
344
  elif kind == "bifrost" and "npm" in artifact:
345
- from localmodels.npm_transport import install_bifrost
345
+ from localmodels.npm_transport import fetch_bifrost
346
346
 
347
- install_bifrost(artifact, staged)
347
+ # Beside the binary, not in the staging directory: a later ensure resumes it,
348
+ # and removing the gateway root removes it too.
349
+ tarball = root / f".{artifact['name']}.tgz" # versioned: no stale resume
350
+ fetch_bifrost(artifact, staged, tarball, event)
348
351
  else:
349
352
  runtime_io.download(artifact, staged, event)
350
353
  staged.chmod(0o700)
@@ -13,6 +13,14 @@ from localmodels import catalog
13
13
  from localmodels.remote_ops import RERANK_DOCS, RERANK_QUERY, RERANK_RELEVANT
14
14
 
15
15
 
16
+ class Check(TypedDict):
17
+ """One named result of a gateway step: wiring, removal or acceptance."""
18
+
19
+ check: str
20
+ ok: bool
21
+ detail: str
22
+
23
+
16
24
  class _AuxService(TypedDict):
17
25
  contract: str # one of gateway.WIRED
18
26
  url: str
@@ -21,8 +29,7 @@ class _AuxService(TypedDict):
21
29
 
22
30
 
23
31
  class AuxEndpoint(_AuxService, total=False):
24
- """A running embedding, reranker, STT or search service, with the key the gateway sends it
25
- (the search service takes none)."""
32
+ """A running embedding, reranker or STT service, with the key the gateway sends it."""
26
33
 
27
34
  fixture: dict[str, object] # STT: the recording acceptance sends
28
35
 
@@ -86,9 +86,13 @@ _GGML_TYPE_SIZES = {
86
86
  29: (56, 256),
87
87
  30: (2, 1),
88
88
  39: (17, 32), # MXFP4 — 32 elements per 17-byte block (gpt-oss family)
89
- # Type 42, 9 bytes per 32 elements: the tensor offsets of ISTA-DASLab's Qwen3.8-Flash-Next
90
- # GSQ-RCO IQ2_XS GGUF (ed59f920) show exactly 0.28125 bytes per element (2026-10-29).
89
+ # b12588 ggml-common.h: NVFP4 (QK_NVFP4=64, 4 E4M3 sub-block scales + 32 packed bytes),
90
+ # Q1_0 (QK1_0=128, fp16 scale + 16 packed bytes), Q2_0 (QK2_0=64, 18 bytes = 9/32),
91
+ # F8_E4M3 (1 byte per element). Inkling-2-Mini GGUFs use NVFP4 tensors.
92
+ 40: (36, 64),
93
+ 41: (18, 128),
91
94
  42: (9, 32),
95
+ 43: (1, 1),
92
96
  }
93
97
 
94
98
  # GGUF metadata value types -> struct format; STRING (8) and ARRAY (9) are variable-length.
@@ -48,10 +48,10 @@ from localmodels.harness_probe import listener_uids as listener_uids
48
48
  from localmodels.harness_probe import shown_pi_model as shown_pi_model
49
49
  from localmodels.npm_transport import Artifact as Artifact
50
50
  from localmodels.npm_transport import ToolBuild as ToolBuild
51
- from localmodels.npm_transport import install_bifrost
51
+ from localmodels.npm_transport import fetch_bifrost
52
52
  from localmodels.remote_ops import Archive, fetch
53
53
  from localmodels.remote_ops_download import npm_copies
54
- from localmodels.runtime_io import error_cause
54
+ from localmodels.runtime_io import Event, error_cause
55
55
  from localmodels.stack_events import CombinedEvents as _CombinedEvents
56
56
  from localmodels.stack_events import ToolEvents
57
57
  from localmodels.tool_archive import (
@@ -509,15 +509,41 @@ def tool_path(plan: ToolPlan, tool: str) -> str:
509
509
  # ---------------------------------------------------------------------------- installation
510
510
 
511
511
 
512
- def _fetch(tools_dir: Path, artifact: Artifact, log: Callable[[str], None]) -> Path:
512
+ def archive_files(tools_dir: Path, artifact: Artifact) -> list[str]:
513
+ """The files ``_fetch`` may leave in ``.archives`` for ``artifact``: the archive, fetch's
514
+ verification marker and, for an npm build, its lock and the tarball with its partial
515
+ download (gone after a successful fetch). The owned manifest lists them for ``--purge``."""
516
+ path = str(tools_dir / ".archives" / artifact["name"])
517
+ suffixes = ("", ".sha256", *((".lock", ".tgz", ".tgz.part") if "npm" in artifact else ()))
518
+ return [path + suffix for suffix in suffixes]
519
+
520
+
521
+ def own_downloads(tools_dir: Path, artifacts: list[Artifact]) -> None:
522
+ """List ``artifacts``' archive files in the owned manifest before fetching them, so
523
+ ``--purge`` also finds the partial download of an install that failed or was killed."""
524
+ files = {f for a in artifacts for f in archive_files(tools_dir, a)}
525
+ hosts.update_owned(
526
+ lambda doc: doc.__setitem__("archives", sorted(set(doc["archives"]) | files)), tools_dir
527
+ )
528
+
529
+
530
+ def _fetch(
531
+ tools_dir: Path,
532
+ artifact: Artifact,
533
+ log: Callable[[str], None],
534
+ event: Event = lambda _: None,
535
+ ) -> Path:
513
536
  path = tools_dir / ".archives" / artifact["name"]
514
537
  if "npm" in artifact:
515
- if not path.is_file() or digest(str(path)) != artifact["sha256"]:
516
- path.parent.mkdir(parents=True, exist_ok=True)
517
- with tempfile.TemporaryDirectory(dir=path.parent) as temporary:
518
- staged = Path(temporary) / "bifrost-http"
519
- install_bifrost(artifact, staged)
520
- staged.replace(path)
538
+ path.parent.mkdir(parents=True, exist_ok=True)
539
+ # stack apply and source apply may fetch it at once: one writes the tarball, the other
540
+ # waits and then reuses the binary it published.
541
+ with hosts.file_lock(path.with_name(path.name + ".lock")):
542
+ if not path.is_file() or digest(str(path)) != artifact["sha256"]:
543
+ with tempfile.TemporaryDirectory(dir=path.parent) as temporary:
544
+ staged = Path(temporary) / "bifrost-http"
545
+ fetch_bifrost(artifact, staged, path.with_name(path.name + ".tgz"), event)
546
+ staged.replace(path)
521
547
  return path
522
548
  with contextlib.redirect_stdout(_Events(log)):
523
549
  _download(path, artifact)
@@ -643,6 +669,7 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
643
669
  if "bifrost" in actions and actions["bifrost"]["action"] == "install":
644
670
  from localmodels import gateway_bifrost
645
671
 
672
+ own_downloads(tools_dir, actions["bifrost"]["artifacts"])
646
673
  if made := gateway_bifrost.install_binary(tools_dir, actions["bifrost"], log):
647
674
  owned.append(made)
648
675
  if "magpie" in actions and actions["magpie"]["action"] == "install":
@@ -662,11 +689,11 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
662
689
  owned.append(str(target))
663
690
  log(f"Magpie {actions['magpie']['version']} installed: {target}")
664
691
  fetched = [
665
- str(tools_dir / ".archives" / a["name"]) + suffix
692
+ file
666
693
  for t in plan["tools"]
667
694
  if t["action"] == "install"
668
695
  for a in t["artifacts"]
669
- for suffix in ("", ".sha256") # fetch's verification marker
696
+ for file in archive_files(tools_dir, a)
670
697
  ]
671
698
  if owned or fetched:
672
699
  created: list[hosts.OwnedTool] = [{"path": p, "sha256": digest(p)} for p in owned]
@@ -20,7 +20,7 @@ from localmodels import (
20
20
  remote_ops_service,
21
21
  runtime_io,
22
22
  )
23
- from localmodels.gateway_search import Check
23
+ from localmodels.gateway_requests import Check
24
24
 
25
25
  SERVE_PID = "magpie-serve.pid" # with magpie-serve.pid.identity.json: process_identity.save
26
26
  SERVE_STOPPED = {
@@ -110,7 +110,60 @@ def listener_uids(addr: str, tables: tuple[str, ...] | None = None) -> set[int]:
110
110
  return uids
111
111
 
112
112
 
113
- def port_holder(port: int, proc: str = "/proc") -> str | None:
113
+ _PROC = "/proc"
114
+
115
+
116
+ def _linux_socket_owner_pids(
117
+ inodes: set[str], proc: str = _PROC, *, uid: int | None = None
118
+ ) -> set[int]:
119
+ owners: set[int] = set()
120
+ for pid in (p for p in _listdir(proc) if p.isdigit()):
121
+ if uid is not None:
122
+ try:
123
+ if Path(proc, pid).stat().st_uid != uid:
124
+ continue
125
+ except OSError:
126
+ continue
127
+ for fd in _listdir(f"{proc}/{pid}/fd"):
128
+ try:
129
+ target = Path(proc, pid, "fd", fd).readlink()
130
+ except OSError:
131
+ continue
132
+ if str(target).removeprefix("socket:[").removesuffix("]") in inodes:
133
+ owners.add(int(pid))
134
+ break
135
+ return owners
136
+
137
+
138
+ def loopback_listener_pids(port: int, proc: str = _PROC) -> set[int] | None:
139
+ """PIDs of processes listening on TCP ``port`` (this user's on Linux), or None when unknown."""
140
+ if sys.platform == "win32":
141
+ from localmodels import process_identity
142
+
143
+ return process_identity.listener_pids(port)
144
+ if sys.platform == "darwin":
145
+ from localmodels.harness import run_tool
146
+
147
+ out = run_tool(
148
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"], timeout=10
149
+ )
150
+ lines = out.stdout.splitlines()
151
+ if out.returncode not in (0, 1) or any(not ln[1:].isdecimal() for ln in lines):
152
+ return None
153
+ return {int(ln[1:]) for ln in lines if ln[:1] == "p"}
154
+ if not sys.platform.startswith("linux"):
155
+ return None
156
+ from localmodels import remote_ops_service
157
+
158
+ inodes = remote_ops_service.loopback_listener_inodes(port)
159
+ if inodes is None:
160
+ return None
161
+ if not inodes:
162
+ return set()
163
+ return _linux_socket_owner_pids(inodes, proc, uid=os.getuid())
164
+
165
+
166
+ def port_holder(port: int, proc: str = _PROC) -> str | None:
114
167
  """Who listens on ``port``, for a refusal the operator can act on: "name (pid N)" for this
115
168
  user's own process, "a process of user uid N" for another user's, None when /proc shows no
116
169
  listener or cannot be read (Linux only; the caller then says nothing more)."""
@@ -126,18 +179,12 @@ def port_holder(port: int, proc: str = "/proc") -> str | None:
126
179
  inodes[f[9]] = int(f[7])
127
180
  if not inodes:
128
181
  return None
129
- for pid in (p for p in _listdir(proc) if p.isdigit()):
130
- for fd in _listdir(f"{proc}/{pid}/fd"):
131
- try:
132
- target = Path(proc, pid, "fd", fd).readlink()
133
- except OSError:
134
- continue
135
- if str(target).removeprefix("socket:[").removesuffix("]") in inodes:
136
- try:
137
- name = Path(proc, pid, "comm").read_text(encoding="utf-8").strip()
138
- except OSError:
139
- name = "?"
140
- return f"{name} (pid {pid})"
182
+ for pid in sorted(_linux_socket_owner_pids(set(inodes), proc)):
183
+ try:
184
+ name = Path(proc, str(pid), "comm").read_text(encoding="utf-8").strip()
185
+ except OSError:
186
+ name = "?"
187
+ return f"{name} (pid {pid})"
141
188
  uid = next(iter(inodes.values()))
142
189
  return f"a process of user uid {uid}"
143
190
 
@@ -348,8 +348,10 @@ class OwnedBifrost(_OwnedBifrostSince20261110):
348
348
 
349
349
  class _OwnedGatewaySince20261031(TypedDict, total=False):
350
350
  caller_keys: list[str] # ids of the Magpie gateway keys (callers' keys) this tool added
351
- search: str # the searxng search API URL this tool added to Magpie's searches
352
- search_you: bool # this tool added Magpie's You.com search API, the free fallback after it
351
+ # The Magpie search APIs this tool added for the web search service the stack used to run:
352
+ # stack remove takes them out again.
353
+ search: str # the searxng search API URL
354
+ search_you: bool # Magpie's You.com search API, the free fallback after it
353
355
  bifrost: OwnedBifrost # since 2026-11-02: the Bifrost gateway this tool runs
354
356
 
355
357
 
@@ -518,26 +520,11 @@ def own_gateway(
518
520
  update_owned(change, tools_dir)
519
521
 
520
522
 
521
- def own_search(tools_dir: str | Path, url: str | None) -> None:
522
- """Record (or, with None, forget) the searxng search API this tool added to Magpie."""
523
+ def forget_search(tools_dir: str | Path, field: Literal["search", "search_you"]) -> None:
524
+ """Forget a Magpie search API this tool added for the web search service it used to run."""
523
525
 
524
526
  def change(doc: Owned) -> None:
525
- if url:
526
- doc["gateway"]["search"] = url
527
- else:
528
- doc["gateway"].pop("search", None)
529
-
530
- update_owned(change, tools_dir)
531
-
532
-
533
- def own_search_you(tools_dir: str | Path, owned: bool) -> None:
534
- """Record (or forget) that this tool added Magpie's You.com search API."""
535
-
536
- def change(doc: Owned) -> None:
537
- if owned:
538
- doc["gateway"]["search_you"] = True
539
- else:
540
- doc["gateway"].pop("search_you", None)
527
+ doc["gateway"].pop(field, None)
541
528
 
542
529
  update_owned(change, tools_dir)
543
530
 
@@ -33,6 +33,7 @@ from localmodels import (
33
33
  harness_probe,
34
34
  hosts,
35
35
  library_state,
36
+ runtime_io,
36
37
  vision,
37
38
  )
38
39
  from localmodels import catalog as cat
@@ -85,7 +86,7 @@ def _fail(detail: str) -> LibraryError:
85
86
  # ---------------------------------------------------------------------------- Bifrost
86
87
 
87
88
 
88
- def _install(facts: HostFacts) -> hosts.OwnedBifrost:
89
+ def _install(facts: HostFacts, event: runtime_io.Event = lambda _: None) -> hosts.OwnedBifrost:
89
90
  """This tool's Bifrost where none is recorded: the pinned binary, its record, an empty
90
91
  config with management authentication, then the instance itself."""
91
92
  addr = harness.bifrost_addr()
@@ -106,8 +107,9 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
106
107
  tools = Path(os.path.expanduser(tools_root))
107
108
  binary = next(a for a in actions if a["tool"] == "bifrost")
108
109
  if binary["action"] == "install":
109
- made = gateway_bifrost.install_binary(tools, binary, lambda _line: None)
110
- fetched = [str(tools / ".archives" / a["name"]) for a in binary["artifacts"]]
110
+ harness.own_downloads(tools, binary["artifacts"])
111
+ made = gateway_bifrost.install_binary(tools, binary, lambda _line: None, event)
112
+ fetched = [f for a in binary["artifacts"] for f in harness.archive_files(tools, a)]
111
113
 
112
114
  def own(doc: hosts.Owned) -> None:
113
115
  if made:
@@ -115,9 +117,7 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
115
117
  [*doc["tools"], {"path": made, "sha256": harness.digest(made)}],
116
118
  key=lambda t: t["path"],
117
119
  )
118
- doc["archives"] = sorted(
119
- set(doc["archives"]) | {p + s for p in fetched for s in ("", ".sha256")}
120
- )
120
+ doc["archives"] = sorted(set(doc["archives"]) | set(fetched))
121
121
 
122
122
  hosts.update_owned(own)
123
123
  gateway_bifrost.ensure(plan)
@@ -142,11 +142,14 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
142
142
  return record
143
143
 
144
144
 
145
- def ensure_instance(facts: HostFacts | None) -> hosts.OwnedBifrost | None:
146
- """Return this tool's Bifrost record, installing it first when ``facts`` are supplied."""
145
+ def ensure_instance(
146
+ facts: HostFacts | None, event: runtime_io.Event = lambda _: None
147
+ ) -> hosts.OwnedBifrost | None:
148
+ """Return this tool's Bifrost record, installing it first when ``facts`` are supplied;
149
+ ``event`` receives the binary's download events."""
147
150
  record = hosts.load_owned()["gateway"].get("bifrost")
148
151
  if record is None and facts is not None:
149
- record = _install(facts)
152
+ record = _install(facts, event)
150
153
  return record
151
154
 
152
155
 
@@ -46,11 +46,7 @@ from localmodels.stack_plan import platform_error
46
46
 
47
47
  POOL_RAM_FRACTION = 0.8 # a "system" pool's budget: RAM x 0.8 (contract v2)
48
48
  UNIFIED_RESERVE_BYTES = metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
49
- # Cap on observed non-model GPU VRAM kept back as a desktop/WDDM baseline on Windows and
50
- # display-active GPUs: keeps real desktop overhead (Windows 11 WDDM + DWM + Linger, ~2.2-2.5 GiB)
51
- # from pretending the card is empty, without letting a transient game or foreign server hide
52
- # models that fit once that program closes.
53
- DESKTOP_VRAM_BASELINE_CAP_BYTES = 3 * metal.GIB
49
+ DESKTOP_VRAM_BASELINE_CAP_BYTES = budget.DESKTOP_VRAM_BASELINE_CAP_BYTES
54
50
 
55
51
 
56
52
  @functools.cache
@@ -86,9 +82,10 @@ def is_chat(entry: cat.CatalogEntry) -> bool:
86
82
 
87
83
 
88
84
  def shown(facts: HostFacts, catalog: Iterable[cat.CatalogEntry]) -> list[Model]:
89
- """The chat models validated for this platform, and the candidates ``stack --llm auto``
90
- picks here too (the Mac small-memory ladder, the Windows NVIDIA fallback): one row per
91
- variant. Ling-3.0-tiny, which the ladder replaces in automatic selection, stays listed."""
85
+ """The chat models validated for this platform, library-listed candidates, and the candidates
86
+ ``stack --llm auto`` picks here too (the Mac small-memory ladder, the Windows NVIDIA
87
+ fallback): one row per variant. Ling-3.0-tiny, which the ladder replaces in automatic
88
+ selection, stays listed."""
92
89
  return [
93
90
  Model(e, v)
94
91
  for e in catalog
@@ -97,6 +94,7 @@ def shown(facts: HostFacts, catalog: Iterable[cat.CatalogEntry]) -> list[Model]:
97
94
  cat.validated_here(e, facts["platform"])
98
95
  or llm_rank.mac_rung(e, facts)
99
96
  or llm_rank.windows_fallback(e, facts)
97
+ or (e.library and e.status == "candidate")
100
98
  )
101
99
  for v in e.variants
102
100
  ]
@@ -375,7 +373,7 @@ def _min_pool_need(model: Model, pool: str, exc: deploy.AgentMemoryError) -> int
375
373
  return exc.needed_bytes + AGENT_VRAM_RESERVE_BYTES
376
374
  if pool == "unified":
377
375
  profile = model.entry.profile(model.variant)
378
- mac_posture = context_policy.posture_for(posture(), "metal")
376
+ mac_posture = model.entry.agent_posture(context_policy.posture_for(posture(), "metal"))
379
377
  host_side = context_policy.cache_floor_bytes(
380
378
  mac_posture, profile
381
379
  ) + context_policy.metal_host_bytes(profile, mac_posture)
@@ -395,15 +395,17 @@ def stop_process(saved: process_identity.Identity, grace: float = 20.0) -> str:
395
395
  import signal
396
396
  import time
397
397
 
398
- if process_identity.inspect(saved["pid"]) != saved:
398
+ current = process_identity.inspect(saved["pid"])
399
+ if not process_identity.matches(current, saved):
399
400
  return "gone"
401
+ assert current is not None
400
402
  if os.name == "nt":
401
403
  deadline = time.monotonic() + grace
402
404
  while time.monotonic() < deadline:
403
- if process_identity.inspect(saved["pid"]) != saved:
405
+ if process_identity.inspect(saved["pid"]) != current:
404
406
  return "stopped"
405
407
  time.sleep(0.1)
406
- if process_identity.windows_stop_tree(saved["pid"], saved, grace):
408
+ if process_identity.windows_stop_tree(saved["pid"], current, grace):
407
409
  return "stopped"
408
410
  raise RuntimeError(f"process {saved['pid']} is still running")
409
411
  for sig in (signal.SIGTERM, signal.SIGKILL):
@@ -411,7 +413,7 @@ def stop_process(saved: process_identity.Identity, grace: float = 20.0) -> str:
411
413
  os.killpg(saved["pgid"], sig)
412
414
  deadline = time.monotonic() + grace
413
415
  while time.monotonic() < deadline:
414
- if process_identity.inspect(saved["pid"]) != saved:
416
+ if process_identity.inspect(saved["pid"]) != current:
415
417
  return "stopped"
416
418
  time.sleep(0.1)
417
419
  raise RuntimeError(f"process group {saved['pgid']} is still running after SIGKILL")
@@ -6,13 +6,14 @@ import hashlib
6
6
  import http.client
7
7
  import os
8
8
  import queue
9
+ import re
9
10
  import sys
10
11
  import tarfile
11
12
  import threading
12
13
  import time
13
14
  import urllib.error
14
15
  import urllib.request
15
- from collections.abc import Mapping
16
+ from collections.abc import Callable, Mapping
16
17
  from pathlib import Path
17
18
  from typing import Any, TypedDict
18
19
  from urllib.parse import urljoin, urlsplit
@@ -31,12 +32,16 @@ def archive_size_cap(binary_size: int) -> int:
31
32
  return min(binary_size + NPM_OVERHEAD_BYTES, MAX_ARCHIVE_BYTES)
32
33
 
33
34
 
35
+ class UnsafeRedirect(urllib.error.URLError):
36
+ """A URL or redirect target without HTTPS, or with credentials, that is never contacted."""
37
+
38
+
34
39
  def _check_url(url: str, *, redirect: bool = False) -> str:
35
40
  try:
36
41
  parts = urlsplit(url)
37
42
  _ = parts.port
38
43
  except ValueError as error:
39
- raise urllib.error.URLError("invalid npm URL") from error
44
+ raise UnsafeRedirect("invalid npm URL") from error
40
45
  local_fixture = (
41
46
  not redirect
42
47
  and parts.scheme == "http"
@@ -49,19 +54,19 @@ def _check_url(url: str, *, redirect: bool = False) -> str:
49
54
  or parts.username is not None
50
55
  or parts.password is not None
51
56
  ):
52
- raise urllib.error.URLError("npm URL must use HTTPS without credentials")
57
+ raise UnsafeRedirect("npm URL must use HTTPS without credentials")
53
58
  return url
54
59
 
55
60
 
56
61
  def _redirect_target(url: str, location: str, hops: int) -> str:
57
62
  if hops >= 5:
58
- raise urllib.error.URLError("npm redirect limit exceeded")
63
+ raise UnsafeRedirect("npm redirect limit exceeded")
59
64
  if not location:
60
- raise urllib.error.URLError("npm redirect is missing its target")
65
+ raise UnsafeRedirect("npm redirect is missing its target")
61
66
  try:
62
67
  target = urljoin(url, location)
63
68
  except ValueError as error:
64
- raise urllib.error.URLError("invalid npm redirect URL") from error
69
+ raise UnsafeRedirect("invalid npm redirect URL") from error
65
70
  return _check_url(target, redirect=True)
66
71
 
67
72
 
@@ -207,47 +212,6 @@ def race(name: str, version: str, env: Mapping[str, str]) -> str | None:
207
212
  return None
208
213
 
209
214
 
210
- def download_package(pin: Mapping[str, Any], destination: Path, binary_size: int) -> str:
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
-
215
- cap = archive_size_cap(binary_size)
216
- if pin.get("bytes"):
217
- if not 0 < pin["bytes"] <= cap:
218
- raise ValueError("npm archive size pin exceeds limit")
219
- cap = pin["bytes"]
220
- region = regions.current_region()
221
- for attempt in range(2):
222
- url = package_url(pin["package"], pin["version"], region, os.environ)
223
- try:
224
- digest = hashlib.sha256()
225
- size = 0
226
- with https_opener().open(_check_url(url), timeout=300) as response:
227
- with destination.open("wb") as output:
228
- while chunk := response.read(65536):
229
- size += len(chunk)
230
- if size > cap:
231
- raise ValueError("npm archive size exceeds limit")
232
- digest.update(chunk)
233
- output.write(chunk)
234
- except (ConnectionError, TimeoutError, urllib.error.URLError, http.client.HTTPException):
235
- destination.unlink(missing_ok=True)
236
- if attempt:
237
- raise
238
- region = "cn" if region == "global" else "global"
239
- continue
240
- if (pin.get("bytes") and size != pin["bytes"]) or (
241
- pin.get("sha256") and digest.hexdigest() != pin["sha256"]
242
- ):
243
- destination.unlink(missing_ok=True)
244
- raise ValueError("npm archive SHA256 or size mismatch")
245
- if attempt:
246
- regions.fallback_to(region)
247
- return region
248
- raise AssertionError("unreachable npm failover")
249
-
250
-
251
215
  def extract_bifrost(archive: Path, destination: Path, digest: str, size: int) -> None:
252
216
  with tarfile.open(archive) as source:
253
217
  binaries = []
@@ -277,10 +241,54 @@ def extract_bifrost(archive: Path, destination: Path, digest: str, size: int) ->
277
241
  destination.chmod(0o755)
278
242
 
279
243
 
280
- def install_bifrost(build: Mapping[str, Any], destination: Path) -> None:
281
- archive = destination.with_suffix(".tgz")
282
- try:
283
- download_package(build["npm"], archive, build["size_bytes"])
284
- extract_bifrost(archive, destination, build["sha256"], build["size_bytes"])
285
- finally:
286
- archive.unlink(missing_ok=True)
244
+ def _archive_pin(build: Mapping[str, Any]) -> tuple[str, int]:
245
+ """The npm tarball's SHA256 and size, which every Bifrost build of the tool lock carries."""
246
+ pin = build["npm"]
247
+ digest, size = pin.get("sha256"), pin.get("bytes")
248
+ if (
249
+ not isinstance(digest, str)
250
+ or not re.fullmatch("[0-9a-f]{64}", digest)
251
+ or type(size) is not int
252
+ or not 0 < size <= archive_size_cap(build["size_bytes"])
253
+ ):
254
+ raise ValueError(
255
+ "Bifrost npm archive pin is missing or invalid (the tool lock needs npm sha256 and"
256
+ " bytes)"
257
+ )
258
+ return digest, size
259
+
260
+
261
+ def _sha256(path: Path) -> str:
262
+ digest = hashlib.sha256()
263
+ with path.open("rb") as stream:
264
+ for chunk in iter(lambda: stream.read(1 << 20), b""):
265
+ digest.update(chunk)
266
+ return digest.hexdigest()
267
+
268
+
269
+ def fetch_bifrost(
270
+ build: Mapping[str, Any],
271
+ destination: Path,
272
+ archive: Path,
273
+ event: Callable[[dict[str, Any]], None],
274
+ ) -> None:
275
+ """Put the pinned Bifrost binary of ``build`` at ``destination``. The npm tarball downloads
276
+ to ``archive``, which must outlive this call: an interrupted download keeps
277
+ ``archive.part`` for the next call to resume (``runtime_io.download``, which also moves
278
+ between the npm registry and its mirror), and a complete tarball left by a crash before
279
+ extraction is reused when it matches the pin. The tarball is deleted once extracted."""
280
+ from localmodels import runtime_io # runtime_io reaches the region through this module
281
+
282
+ digest, size = _archive_pin(build)
283
+ if archive.exists() or archive.is_symlink():
284
+ if archive.is_file() and not archive.is_symlink() and _sha256(archive) == digest:
285
+ event({"kind": "stage", "stage": "download", "state": "reused"})
286
+ else:
287
+ archive.unlink()
288
+ if not archive.exists():
289
+ pin = build["npm"]
290
+ url = _check_url(package_url(pin["package"], pin["version"], "global", os.environ))
291
+ artifact = {"url": url, "algorithm": "sha256", "digest": digest, "maxBytes": size}
292
+ runtime_io.download(artifact, archive, event)
293
+ extract_bifrost(archive, destination, build["sha256"], build["size_bytes"])
294
+ archive.unlink()