@simplexai/localmodels-darwin-x64 0.1.0-dev.60 → 0.1.0-dev.62

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 (79) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +78 -64
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +5 -3
  5. package/modules/localmodels/auth_proxy.py +185 -19
  6. package/modules/localmodels/catalog.json +363 -0
  7. package/modules/localmodels/catalog.py +1 -1
  8. package/modules/localmodels/catalog_add.py +5 -5
  9. package/modules/localmodels/catalog_license.py +2 -0
  10. package/modules/localmodels/catalog_recipes.py +2 -0
  11. package/modules/localmodels/cli_parser.py +6 -2
  12. package/modules/localmodels/context_policy.py +40 -4
  13. package/modules/localmodels/custom_hub_http.py +27 -104
  14. package/modules/localmodels/debug_mode.py +13 -0
  15. package/modules/localmodels/debug_stub_server.py +156 -1
  16. package/modules/localmodels/deploy.py +11 -2
  17. package/modules/localmodels/download-mirrors.json +12 -0
  18. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  19. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  20. package/modules/localmodels/gateway_app_bifrost.py +14 -14
  21. package/modules/localmodels/gateway_bifrost.py +4 -1
  22. package/modules/localmodels/gateway_cli.py +14 -80
  23. package/modules/localmodels/gateway_server.py +88 -16
  24. package/modules/localmodels/gpu_specs.py +35 -1
  25. package/modules/localmodels/harness.py +1 -2
  26. package/modules/localmodels/hf_repo.py +12 -4
  27. package/modules/localmodels/install.py +4 -4
  28. package/modules/localmodels/library_jobs.py +4 -0
  29. package/modules/localmodels/library_serve.py +69 -13
  30. package/modules/localmodels/memcalc_load.py +9 -4
  31. package/modules/localmodels/npm_transport.py +4 -58
  32. package/modules/localmodels/recommend_cli.py +2 -1
  33. package/modules/localmodels/remote_ops.py +120 -713
  34. package/modules/localmodels/remote_ops_common.py +670 -0
  35. package/modules/localmodels/remote_ops_download.py +399 -381
  36. package/modules/localmodels/remote_ops_mirrors.py +27 -66
  37. package/modules/localmodels/remote_ops_prepare.py +43 -35
  38. package/modules/localmodels/remote_ops_ranges.py +102 -63
  39. package/modules/localmodels/remote_ops_redirect.py +393 -0
  40. package/modules/localmodels/remote_ops_remove.py +30 -22
  41. package/modules/localmodels/remote_ops_service.py +102 -95
  42. package/modules/localmodels/remote_ops_verify.py +94 -63
  43. package/modules/localmodels/runtime_cli.py +15 -5
  44. package/modules/localmodels/runtime_io.py +54 -1
  45. package/modules/localmodels/source_cli.py +136 -23
  46. package/modules/localmodels/speech-sv.txt +93 -0
  47. package/modules/localmodels/speech_admission.py +437 -0
  48. package/modules/localmodels/speech_catalog.py +170 -0
  49. package/modules/localmodels/speech_cli.py +273 -0
  50. package/modules/localmodels/speech_jobs.py +776 -0
  51. package/modules/localmodels/speech_model.py +404 -0
  52. package/modules/localmodels/speech_serve.py +287 -0
  53. package/modules/localmodels/speech_server.py +837 -0
  54. package/modules/localmodels/speech_state.py +697 -0
  55. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  56. package/modules/localmodels/speech_workers.py +783 -0
  57. package/modules/localmodels/stack.py +0 -33
  58. package/modules/localmodels/stack_auto.py +5 -3
  59. package/modules/localmodels/stack_aux_gpu.py +45 -4
  60. package/modules/localmodels/stack_capacity.py +77 -8
  61. package/modules/localmodels/stack_cli.py +16 -1
  62. package/modules/localmodels/stack_compose.py +1 -1
  63. package/modules/localmodels/stack_down.py +24 -1
  64. package/modules/localmodels/stack_hardware.py +57 -88
  65. package/modules/localmodels/stack_hardware_text.py +4 -59
  66. package/modules/localmodels/stack_memory.py +13 -3
  67. package/modules/localmodels/stack_suite.py +9 -10
  68. package/modules/localmodels/stack_summary.py +4 -4
  69. package/modules/localmodels/stack_view_llm.py +1 -1
  70. package/modules/localmodels/transport.py +4 -2
  71. package/modules/localmodels/tui_views.py +2 -2
  72. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/METADATA +1 -1
  73. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/RECORD +75 -61
  74. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/NOTICE +9 -0
  75. package/package.json +1 -1
  76. package/tool.json +1 -1
  77. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/WHEEL +0 -0
  78. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/entry_points.txt +0 -0
  79. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -4,13 +4,13 @@ from __future__ import annotations
4
4
 
5
5
  import os
6
6
  import subprocess
7
+ from collections.abc import Callable
7
8
  from pathlib import Path
8
9
  from typing import Any
9
10
 
10
11
  from localmodels import (
11
12
  bifrost_config,
12
13
  gateway_bifrost,
13
- gateway_cli,
14
14
  gateway_foundations,
15
15
  harness,
16
16
  process_identity,
@@ -69,9 +69,15 @@ def render(
69
69
 
70
70
 
71
71
  class Upstream:
72
- def __init__(self, root: Path, state: dict[str, Any]):
72
+ def __init__(
73
+ self,
74
+ root: Path,
75
+ state: dict[str, Any],
76
+ resolve: Callable[[], tuple[dict[str, Any] | None, bool]],
77
+ ):
73
78
  self.root = root
74
79
  self.state = state
80
+ self._resolve = resolve
75
81
  self.app = root / "bifrost"
76
82
  runtime_io.private_directory(self.app)
77
83
  for name in ("admin-password", "config.json", "config.json.tmp"):
@@ -83,25 +89,19 @@ class Upstream:
83
89
  self.authenticated = False
84
90
 
85
91
  def refresh(self) -> None:
86
- from localmodels import gateway_server
87
-
88
- row = gateway_cli.selected_runtime(
89
- Path(self.state["harnessRoot"]), self.state["runtime"], self.state.get("node")
90
- )
91
- env = gateway_cli.gateway_environment(self.root / "home", row)
92
- provider = gateway_server.api_provider(row, env, self.state)
92
+ provider, authed = self._resolve()
93
93
  source = self.state.get("foundationsRoot")
94
94
  config = render(provider, Path(source) if source else None, self.app, self.password)
95
95
  if config != gateway_bifrost.read_config(self.app):
96
96
  running = self.child is not None
97
97
  self.stop()
98
- gateway_bifrost._write_config(self.app, config)
98
+ gateway_bifrost.write_config(self.app, config)
99
99
  if running:
100
100
  self.start()
101
- self.authenticated = provider is not None and row["authenticated"] is True
101
+ self.authenticated = provider is not None and authed
102
102
 
103
103
  def start(self) -> None:
104
- gateway_bifrost._stop_serve(self.app)
104
+ gateway_bifrost.stop_serve(self.app)
105
105
  env = dict(os.environ, NO_PROXY="*", no_proxy="*")
106
106
  # Explicit config owns all providers; inherited credential variables must not add any.
107
107
  for name in tuple(env):
@@ -131,12 +131,12 @@ class Upstream:
131
131
  try:
132
132
  process_identity.save(self.app / "bifrost.pid", self.child.pid)
133
133
  except (OSError, ValueError, RuntimeError, subprocess.SubprocessError):
134
- runtime_process._terminate_tree(self.child)
134
+ runtime_process.terminate_tree(self.child)
135
135
  self.child = None
136
136
  raise harness.HarnessError("Cannot record Bifrost process identity") from None
137
137
 
138
138
  def stop(self) -> None:
139
- gateway_bifrost._stop_serve(self.app)
139
+ gateway_bifrost.stop_serve(self.app)
140
140
  if self.child is not None:
141
141
  self.child.wait(timeout=10)
142
142
  self.child = None
@@ -583,7 +583,7 @@ def _stop_owned_serve(record: hosts.OwnedBifrost) -> None:
583
583
  _stop_orphaned_serve(record)
584
584
 
585
585
 
586
- def _stop_serve(app: Path) -> None:
586
+ def stop_serve(app: Path) -> None:
587
587
  """Only the process group the identity receipt proves is ours; anything else is kept."""
588
588
  try:
589
589
  outcome = process_identity.stop(app / "bifrost.pid")
@@ -596,6 +596,9 @@ def _stop_serve(app: Path) -> None:
596
596
  _stop_orphaned_serve(record)
597
597
 
598
598
 
599
+ _stop_serve = stop_serve
600
+
601
+
599
602
  def pause(record: hosts.OwnedBifrost) -> str:
600
603
  """Stop the proven instance, retaining its unit, configuration and ownership record."""
601
604
  running = owned_listener(record)
@@ -23,13 +23,16 @@ from typing import Any
23
23
  from localmodels import (
24
24
  cli_help,
25
25
  gateway_bifrost,
26
+ gateway_server,
26
27
  harness,
27
28
  http_local,
28
29
  runtime_cli,
29
30
  runtime_io,
30
31
  )
31
-
32
- SCHEMA = "localmodels.gateway-owned/v1"
32
+ from localmodels.gateway_server import SCHEMA as SCHEMA
33
+ from localmodels.gateway_server import gateway_environment as gateway_environment
34
+ from localmodels.gateway_server import read_state as read_state
35
+ from localmodels.gateway_server import selected_runtime as selected_runtime
33
36
 
34
37
 
35
38
  def artifact_for(native_platform: str, kind: str = "magpie") -> dict[str, Any]:
@@ -80,13 +83,11 @@ def reuse_binary(artifact: dict[str, Any], destination: Path) -> bool:
80
83
  def choose_kind(
81
84
  choice: str, runtime: str | None, row: dict[str, Any], root: Path, state: dict[str, Any]
82
85
  ) -> str:
83
- from localmodels import gateway_server
84
-
85
86
  if choice not in ("auto", "bifrost", "magpie"):
86
87
  raise ValueError("Unknown gateway kind")
87
88
  if choice == "magpie":
88
89
  return choice
89
- platform, arch = runtime_cli._platform().split("-", 1)
90
+ platform, arch = runtime_cli.platform().split("-", 1)
90
91
  # Windows keeps Magpie (decisions 32 and 48): its Bifrost build (since localmodels.6) serves
91
92
  # the model library, whose own gateway is a different instance; this one is not verified there.
92
93
  available = platform != "win32" and any(
@@ -99,8 +100,8 @@ def choose_kind(
99
100
  raise ValueError("Bifrost needs a selected runtime")
100
101
  env = gateway_environment(root / "home", row)
101
102
  if choice == "auto" and runtime == "pi":
102
- profile = runtime_cli._active_profile(runtime, env)
103
- auth = gateway_server._read_json(profile / "auth.json")
103
+ profile = runtime_cli.active_profile(runtime, env)
104
+ auth = gateway_server.read_json(profile / "auth.json")
104
105
  if any(isinstance(entry, dict) and entry.get("type") == "oauth" for entry in auth.values()):
105
106
  return "magpie"
106
107
  provider = gateway_server.api_provider(row, env, state)
@@ -127,10 +128,10 @@ def build_plan(
127
128
  runtime_io.validate_runtime_root(source)
128
129
  row = {
129
130
  "runtime": runtime,
130
- "environment": runtime_cli._runtime_env(source, runtime) if runtime else {},
131
+ "environment": runtime_cli.runtime_env(source, runtime) if runtime else {},
131
132
  }
132
133
  kind = choose_kind(gateway, runtime, row, root, state)
133
- platform = runtime_cli._platform()
134
+ platform = runtime_cli.platform()
134
135
  artifact = artifact_for(platform) if kind == "magpie" else artifact_for(platform, kind)
135
136
  target = root / artifact["executable"]
136
137
  action, download_bytes, disk_bytes = "download", artifact["size_bytes"], artifact["size_bytes"]
@@ -166,30 +167,6 @@ def write_key(path: Path, key: str) -> None:
166
167
  runtime_io.private_permissions(path, created=True)
167
168
 
168
169
 
169
- def read_state(root: Path) -> dict[str, Any]:
170
- runtime_io.validate_runtime_root(root)
171
- path = root / "gateway.json"
172
- runtime_io.private_permissions(path)
173
- value: dict[str, Any] = json.loads(path.read_text())
174
- if value.get("schema") != SCHEMA or value.get("runtime") not in runtime_cli.RUNTIMES:
175
- raise ValueError("Invalid gateway ownership")
176
- if value.get("kind", "magpie") not in ("magpie", "bifrost"):
177
- raise ValueError("Invalid gateway kind")
178
- for field in ("port", "upstreamPort"):
179
- if type(value.get(field)) is not int or not 1 <= value[field] <= 65535:
180
- raise ValueError("Invalid gateway port")
181
- if value["port"] == value["upstreamPort"]:
182
- raise ValueError("Invalid gateway port allocation")
183
- if not isinstance(value.get("instance"), str) or not value["instance"]:
184
- raise ValueError("Invalid gateway ownership")
185
- source = value.get("foundationsRoot")
186
- if source is not None and (
187
- not isinstance(source, str) or not Path(source).is_absolute() or ".." in Path(source).parts
188
- ):
189
- raise ValueError("Invalid foundation source root")
190
- return value
191
-
192
-
193
170
  def _request(
194
171
  root: Path, state: dict[str, Any], path: str, *, method: str = "GET", timeout: float = 2
195
172
  ) -> dict[str, Any]:
@@ -263,7 +240,7 @@ def _stop(root: Path) -> dict[str, Any]:
263
240
  pass # The server may have closed between its status and stop requests.
264
241
  if worker_idle(root):
265
242
  if state.get("kind") == "bifrost":
266
- gateway_bifrost._stop_serve(root / "bifrost")
243
+ gateway_bifrost.stop_serve(root / "bifrost")
267
244
  result = status(root)
268
245
  if result["ready"]:
269
246
  raise ValueError("Gateway worker ownership unavailable")
@@ -279,47 +256,6 @@ def stop(root: Path) -> dict[str, Any]:
279
256
  return _stop(root)
280
257
 
281
258
 
282
- def gateway_environment(home: Path, row: dict[str, Any]) -> dict[str, str]:
283
- env = {k: v for k, v in os.environ.items() if not k.startswith("MAGPIE_")}
284
- claude_profile = row["environment"].get("CLAUDE_CONFIG_DIR") or env.get("CLAUDE_CONFIG_DIR")
285
- native_claude = row["runtime"] == "claude" and not (
286
- claude_profile and runtime_cli._owned_profile(Path(claude_profile))
287
- )
288
- env.update(
289
- HOME=str(home),
290
- USERPROFILE=str(home),
291
- XDG_CONFIG_HOME=str(home / ".config"),
292
- XDG_DATA_HOME=str(home / ".local/share"),
293
- XDG_CACHE_HOME=str(home / ".cache"),
294
- APPDATA=str(home / "AppData/Roaming"),
295
- LOCALAPPDATA=str(home / "AppData/Local"),
296
- )
297
- if native_claude:
298
- # Keychain search lists follow the caller's native home, independently of Magpie's XDG files.
299
- env["HOME"] = os.environ.get("HOME", str(Path.home()))
300
- env["USERPROFILE"] = os.environ.get("USERPROFILE", str(Path.home()))
301
- env.update(row["environment"])
302
- for runtime, key in runtime_cli.PROFILE_KEYS.items():
303
- # An isolated Magpie HOME must never cause credentials to be read from it.
304
- if runtime == row["runtime"]:
305
- if runtime != "claude":
306
- env.setdefault(key, str(Path.home() / runtime_cli.PROFILE_DIRS[runtime]))
307
- else:
308
- env[key] = str(home / runtime_cli.PROFILE_DIRS[runtime])
309
- executable = row.get("executable")
310
- if executable:
311
- env["PATH"] = str(Path(executable).parent) + os.pathsep + env.get("PATH", "")
312
- return env
313
-
314
-
315
- def selected_runtime(root: Path, runtime: str, node: str | None = None) -> dict[str, Any]:
316
- return next(
317
- row
318
- for row in runtime_cli.inspect_runtimes(root, node=node)["runtimes"]
319
- if row["runtime"] == runtime
320
- )
321
-
322
-
323
259
  def _port() -> int:
324
260
  with socket.socket() as reservation:
325
261
  reservation.bind(("127.0.0.1", 0))
@@ -328,9 +264,9 @@ def _port() -> int:
328
264
 
329
265
  def ensure_binary(root: Path, kind: str, event: runtime_io.Event) -> None:
330
266
  artifact = (
331
- artifact_for(runtime_cli._platform())
267
+ artifact_for(runtime_cli.platform())
332
268
  if kind == "magpie"
333
- else artifact_for(runtime_cli._platform(), kind)
269
+ else artifact_for(runtime_cli.platform(), kind)
334
270
  )
335
271
  binary = root / artifact["executable"]
336
272
  if binary.exists() or binary.is_symlink():
@@ -343,12 +279,10 @@ def ensure_binary(root: Path, kind: str, event: runtime_io.Event) -> None:
343
279
  if reuse_binary(artifact, staged):
344
280
  event({"kind": "stage", "stage": f"reuse-{kind}", "state": "succeeded"})
345
281
  elif kind == "bifrost" and "npm" in artifact:
346
- from localmodels.npm_transport import fetch_bifrost
347
-
348
282
  # Beside the binary, not in the staging directory: a later ensure resumes it,
349
283
  # and removing the gateway root removes it too.
350
284
  tarball = root / f".{artifact['name']}.tgz" # versioned: no stale resume
351
- fetch_bifrost(artifact, staged, tarball, event)
285
+ runtime_io.fetch_bifrost(artifact, staged, tarball, event)
352
286
  else:
353
287
  runtime_io.download(artifact, staged, event)
354
288
  staged.chmod(0o700)
@@ -23,7 +23,6 @@ from localmodels import (
23
23
  auth_proxy,
24
24
  gateway,
25
25
  gateway_app_bifrost,
26
- gateway_cli,
27
26
  gateway_foundations,
28
27
  harness,
29
28
  http_local,
@@ -33,8 +32,75 @@ from localmodels import (
33
32
  runtime_process,
34
33
  )
35
34
 
35
+ SCHEMA = "localmodels.gateway-owned/v1"
36
+
37
+
38
+ def read_state(root: Path) -> dict[str, Any]:
39
+ runtime_io.validate_runtime_root(root)
40
+ path = root / "gateway.json"
41
+ runtime_io.private_permissions(path)
42
+ value: dict[str, Any] = json.loads(path.read_text())
43
+ if value.get("schema") != SCHEMA or value.get("runtime") not in runtime_cli.RUNTIMES:
44
+ raise ValueError("Invalid gateway ownership")
45
+ if value.get("kind", "magpie") not in ("magpie", "bifrost"):
46
+ raise ValueError("Invalid gateway kind")
47
+ for field in ("port", "upstreamPort"):
48
+ if type(value.get(field)) is not int or not 1 <= value[field] <= 65535:
49
+ raise ValueError("Invalid gateway port")
50
+ if value["port"] == value["upstreamPort"]:
51
+ raise ValueError("Invalid gateway port allocation")
52
+ if not isinstance(value.get("instance"), str) or not value["instance"]:
53
+ raise ValueError("Invalid gateway ownership")
54
+ source = value.get("foundationsRoot")
55
+ if source is not None and (
56
+ not isinstance(source, str) or not Path(source).is_absolute() or ".." in Path(source).parts
57
+ ):
58
+ raise ValueError("Invalid foundation source root")
59
+ return value
36
60
 
37
- def _read_json(path: Path, *, private: bool = True) -> dict[str, Any]:
61
+
62
+ def gateway_environment(home: Path, row: dict[str, Any]) -> dict[str, str]:
63
+ env = {k: v for k, v in os.environ.items() if not k.startswith("MAGPIE_")}
64
+ claude_profile = row["environment"].get("CLAUDE_CONFIG_DIR") or env.get("CLAUDE_CONFIG_DIR")
65
+ native_claude = row["runtime"] == "claude" and not (
66
+ claude_profile and runtime_cli.owned_profile(Path(claude_profile))
67
+ )
68
+ env.update(
69
+ HOME=str(home),
70
+ USERPROFILE=str(home),
71
+ XDG_CONFIG_HOME=str(home / ".config"),
72
+ XDG_DATA_HOME=str(home / ".local/share"),
73
+ XDG_CACHE_HOME=str(home / ".cache"),
74
+ APPDATA=str(home / "AppData/Roaming"),
75
+ LOCALAPPDATA=str(home / "AppData/Local"),
76
+ )
77
+ if native_claude:
78
+ # Keychain search lists follow the caller's native home, independently of Magpie's XDG files.
79
+ env["HOME"] = os.environ.get("HOME", str(Path.home()))
80
+ env["USERPROFILE"] = os.environ.get("USERPROFILE", str(Path.home()))
81
+ env.update(row["environment"])
82
+ for runtime, key in runtime_cli.PROFILE_KEYS.items():
83
+ # An isolated Magpie HOME must never cause credentials to be read from it.
84
+ if runtime == row["runtime"]:
85
+ if runtime != "claude":
86
+ env.setdefault(key, str(Path.home() / runtime_cli.PROFILE_DIRS[runtime]))
87
+ else:
88
+ env[key] = str(home / runtime_cli.PROFILE_DIRS[runtime])
89
+ executable = row.get("executable")
90
+ if executable:
91
+ env["PATH"] = str(Path(executable).parent) + os.pathsep + env.get("PATH", "")
92
+ return env
93
+
94
+
95
+ def selected_runtime(root: Path, runtime: str, node: str | None = None) -> dict[str, Any]:
96
+ return next(
97
+ row
98
+ for row in runtime_cli.inspect_runtimes(root, node=node)["runtimes"]
99
+ if row["runtime"] == runtime
100
+ )
101
+
102
+
103
+ def read_json(path: Path, *, private: bool = True) -> dict[str, Any]:
38
104
  if not path.exists():
39
105
  return {}
40
106
  if private:
@@ -79,11 +145,11 @@ def api_provider(
79
145
  ) -> dict[str, Any] | None:
80
146
  """Read the selected native credential format; never execute Pi key shell expressions."""
81
147
  runtime = row["runtime"]
82
- profile = runtime_cli._active_profile(runtime, env)
148
+ profile = runtime_cli.active_profile(runtime, env)
83
149
  auth = (
84
150
  {}
85
151
  if runtime == "codex"
86
- else _read_json(
152
+ else read_json(
87
153
  profile / ("settings.json" if runtime == "claude" else "auth.json"),
88
154
  private=runtime != "claude",
89
155
  )
@@ -111,8 +177,8 @@ def api_provider(
111
177
  provider = "anthropic"
112
178
  base = settings_env.get("ANTHROPIC_BASE_URL") or env.get("ANTHROPIC_BASE_URL")
113
179
  else:
114
- config = _read_json(profile / "models.json", private=False).get("providers", {})
115
- selected = _read_json(profile / "settings.json", private=False).get("defaultProvider")
180
+ config = read_json(profile / "models.json", private=False).get("providers", {})
181
+ selected = read_json(profile / "settings.json", private=False).get("defaultProvider")
116
182
  names = (
117
183
  [selected]
118
184
  if selected
@@ -171,11 +237,15 @@ def api_provider(
171
237
  )
172
238
 
173
239
 
240
+ def resolve_provider(root: Path, state: dict[str, Any]) -> tuple[dict[str, Any] | None, bool]:
241
+ row = selected_runtime(Path(state["harnessRoot"]), state["runtime"], state.get("node"))
242
+ env = gateway_environment(root / "home", row)
243
+ return api_provider(row, env, state), row["authenticated"] is True
244
+
245
+
174
246
  def configure(root: Path, state: dict[str, Any]) -> tuple[dict[str, str], bool]:
175
- row = gateway_cli.selected_runtime(
176
- Path(state["harnessRoot"]), state["runtime"], state.get("node")
177
- )
178
- env = gateway_cli.gateway_environment(root / "home", row)
247
+ row = selected_runtime(Path(state["harnessRoot"]), state["runtime"], state.get("node"))
248
+ env = gateway_environment(root / "home", row)
179
249
  env["MAGPIE_ADDR"] = f"127.0.0.1:{state['upstreamPort']}"
180
250
  config = root / "home" / ".config" / "magpie"
181
251
  runtime_io.private_directory(config)
@@ -186,7 +256,7 @@ def configure(root: Path, state: dict[str, Any]) -> tuple[dict[str, str], bool]:
186
256
  provider = api_provider(row, env, state)
187
257
  providers = config / "providers.json"
188
258
  existing = providers.exists()
189
- catalog = _read_json(providers) if existing else {"providers": [provider] if provider else []}
259
+ catalog = read_json(providers) if existing else {"providers": [provider] if provider else []}
190
260
  entries = catalog.setdefault("providers", [])
191
261
  for account in ("claude", "codex", "copilot", "gemini", "antigravity", "chatgpt-api"):
192
262
  pick: dict[str, Any] = next(
@@ -364,16 +434,18 @@ def ingress_handler(
364
434
 
365
435
 
366
436
  def serve(root: Path) -> None:
367
- state = gateway_cli.read_state(root)
437
+ state = read_state(root)
368
438
  runtime_io.private_permissions(root / "caller.key")
369
439
  key = (root / "caller.key").read_text().strip()
370
440
  runtime_io.private_permissions(root / "control.key")
371
441
  control_key = (root / "control.key").read_text().strip()
372
442
  with runtime_io.private_lock(root / "worker.lock", blocking=False):
373
- if gateway_cli.read_state(root).get("desiredState") == "stopped":
443
+ if read_state(root).get("desiredState") == "stopped":
374
444
  return
375
445
  bifrost = (
376
- gateway_app_bifrost.Upstream(root, state) if state.get("kind") == "bifrost" else None
446
+ gateway_app_bifrost.Upstream(root, state, lambda: resolve_provider(root, state))
447
+ if state.get("kind") == "bifrost"
448
+ else None
377
449
  )
378
450
  env: dict[str, str]
379
451
  if bifrost is not None:
@@ -391,7 +463,7 @@ def serve(root: Path) -> None:
391
463
  )
392
464
  server = GatewayHTTPServer(("0.0.0.0", state["port"]), handler)
393
465
  server.daemon_threads = True
394
- if gateway_cli.read_state(root).get("desiredState") == "stopped":
466
+ if read_state(root).get("desiredState") == "stopped":
395
467
  server.server_close()
396
468
  return
397
469
  child: subprocess.Popen[bytes] | gateway_app_bifrost.Upstream
@@ -436,7 +508,7 @@ def serve(root: Path) -> None:
436
508
  if bifrost is not None:
437
509
  bifrost.stop()
438
510
  elif native_child is not None and native_child.poll() is None:
439
- runtime_process._terminate_tree(native_child)
511
+ runtime_process.terminate_tree(native_child)
440
512
  watcher.join()
441
513
 
442
514
 
@@ -17,6 +17,7 @@ bandwidths, where the old single 1000 GB/s class constant priced both alike.
17
17
  from __future__ import annotations
18
18
 
19
19
  import re
20
+ from dataclasses import dataclass
20
21
 
21
22
  # (fullmatch over the normalized name, GB/s). Normalized: lower case, vendor and product-line
22
23
  # words dropped, hyphens as spaces: "NVIDIA A100-SXM4-80GB" reads "a100 sxm4 80gb".
@@ -80,6 +81,7 @@ _BANDWIDTH_GB_S: tuple[tuple[str, float], ...] = (
80
81
  )
81
82
  _GIB = 1 << 30
82
83
  _DROPPED = re.compile(r"\b(nvidia|geforce|tesla|quadro)\b")
84
+ _APPLE_CHIP_RE = re.compile(r"(?:apple m([1-9]\d*)|m([1-9]))(?: (pro|max|ultra))?")
83
85
 
84
86
  # Compute capability major (and minor where one major spans two) → architecture.
85
87
  _ARCHITECTURES = {
@@ -95,12 +97,43 @@ _ARCHITECTURES = {
95
97
  }
96
98
 
97
99
 
100
+ @dataclass(frozen=True)
101
+ class AppleChip:
102
+ """Parsed Apple Silicon chip generation and tier from a Metal device or CPU name."""
103
+
104
+ generation: int
105
+ tier: str # "base" | "pro" | "max" | "ultra"
106
+
107
+ @property
108
+ def canonical(self) -> str:
109
+ """Normalized chip name matching ``normalized('Apple M...')``."""
110
+ if self.tier == "base":
111
+ return f"apple m{self.generation}"
112
+ return f"apple m{self.generation} {self.tier}"
113
+
114
+
115
+ def apple_chip_tier(name: str) -> AppleChip | None:
116
+ """Parse an Apple Silicon chip name (``'Apple M4 Pro'``, ``'M1'``); None for other names.
117
+
118
+ Inspects the lowercased name before dropping NVIDIA vendor words so names like ``'Tesla M4'``
119
+ never alias to Apple Silicon.
120
+ """
121
+ raw = " ".join(name.lower().replace("-", " ").split())
122
+ match = _APPLE_CHIP_RE.fullmatch(raw)
123
+ if match is None:
124
+ return None
125
+ generation = int(match.group(1) or match.group(2))
126
+ return AppleChip(generation=generation, tier=match.group(3) or "base")
127
+
128
+
98
129
  def normalized(name: str) -> str:
99
130
  return " ".join(_DROPPED.sub(" ", name.lower().replace("-", " ")).split())
100
131
 
101
132
 
102
133
  def device_class(name: str) -> str:
103
134
  """Canonical device model class for calibration and lower-bound joins; empty when unnamed."""
135
+ if (chip := apple_chip_tier(name)) is not None:
136
+ return chip.canonical
104
137
  key = normalized(name)
105
138
  if not key:
106
139
  return ""
@@ -113,7 +146,8 @@ def device_class(name: str) -> str:
113
146
 
114
147
  def bandwidth_gb_s(name: str, *, total_bytes: int | None = None) -> float | None:
115
148
  """The published memory bandwidth of the GPU or Apple Silicon SoC ``name``; None: not listed."""
116
- key = normalized(name)
149
+ chip = apple_chip_tier(name)
150
+ key = chip.canonical if chip is not None else normalized(name)
117
151
  if key == "apple m6" and total_bytes is not None and total_bytes > 0:
118
152
  # Base Apple M6 ships with 153 GB/s at 16 GB and 170 GB/s at 24/32 GB.
119
153
  return 153.0 if total_bytes <= 16 * _GIB else 170.0
@@ -48,10 +48,9 @@ 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 fetch_bifrost
52
51
  from localmodels.remote_ops import Archive, fetch
53
52
  from localmodels.remote_ops_download import npm_copies
54
- from localmodels.runtime_io import Event, error_cause, rename_with_retry
53
+ from localmodels.runtime_io import Event, error_cause, fetch_bifrost, rename_with_retry
55
54
  from localmodels.stack_events import CombinedEvents as _CombinedEvents
56
55
  from localmodels.stack_events import ToolEvents
57
56
  from localmodels.tool_archive import (
@@ -132,14 +132,22 @@ def _license(card: dict[str, object]) -> tuple[str, str]:
132
132
  return str(name or "unspecified"), str(card.get("license_link") or "")
133
133
 
134
134
 
135
+ _MMPROJ_RE = re.compile(r"(?:^|[-_])mmproj(?:$|[-_.])", re.IGNORECASE)
136
+ _AUX_GGUF_RE = re.compile(
137
+ r"(?:^|/)(?:imatrix|(?:mtp|dflash2?|eagle3|dspark)[-_])",
138
+ re.IGNORECASE,
139
+ )
140
+
141
+
135
142
  def _groups(files: list[OptionalTreeFile]) -> dict[str, list[OptionalTreeFile]]:
136
143
  """Model GGUFs grouped by stem with the split-part suffix stripped (one group per quant)."""
137
144
  groups: dict[str, list[OptionalTreeFile]] = {}
138
145
  for f in files:
139
- name = f["path"].rsplit("/", 1)[-1]
140
- stem = name.removesuffix(".gguf")
141
- if stem.lower().startswith("mmproj"):
146
+ path = f["path"]
147
+ name = path.rsplit("/", 1)[-1]
148
+ if _MMPROJ_RE.search(name) or _AUX_GGUF_RE.search(path):
142
149
  continue
150
+ stem = name.removesuffix(".gguf")
143
151
  if m := SPLIT_PART_RE.search(name):
144
152
  stem = stem[: m.start()]
145
153
  groups.setdefault(stem, []).append(f)
@@ -171,7 +179,7 @@ def _mmproj(files: list[OptionalTreeFile]) -> OptionalTreeFile | None:
171
179
  found = [
172
180
  f
173
181
  for f in files
174
- if f["path"].rsplit("/", 1)[-1].lower().startswith("mmproj") and f["path"].endswith(".gguf")
182
+ if f["path"].endswith(".gguf") and _MMPROJ_RE.search(f["path"].rsplit("/", 1)[-1])
175
183
  ]
176
184
  if not found:
177
185
  return None
@@ -22,7 +22,7 @@ from localmodels import console, harness, stack, stack_args, stack_picks, stack_
22
22
  from localmodels.plan_envelope import PlanError
23
23
  from localmodels.stack_console import Board
24
24
  from localmodels.stack_plan import StackError, command
25
- from localmodels.stack_summary import styled
25
+ from localmodels.stack_summary import styled, summary
26
26
 
27
27
  _REFUSED = (StackError, PlanError, harness.HarnessError, ValueError, KeyError)
28
28
 
@@ -47,7 +47,7 @@ def _fail(exc: Exception) -> int:
47
47
 
48
48
 
49
49
  def cli(args: argparse.Namespace) -> int:
50
- options = stack.options_from_args(args)
50
+ options = stack_args.options_from_args(args)
51
51
  explicit = getattr(args, "gateway", None) is not None
52
52
  selected = getattr(args, "component_selections", ())
53
53
  if (
@@ -78,7 +78,7 @@ def cli(args: argparse.Namespace) -> int:
78
78
  path = stack.save(plan)
79
79
  except _REFUSED as exc:
80
80
  return _fail(exc)
81
- print(styled(stack.summary(plan, path, apply_line=False)))
81
+ print(styled(summary(plan, path, apply_line=False)))
82
82
  seen = plan.get("hardware")
83
83
  offered = seen.get("picks", []) if seen else []
84
84
  other = (
@@ -99,7 +99,7 @@ def cli(args: argparse.Namespace) -> int:
99
99
  path = stack.save(plan)
100
100
  except _REFUSED as exc:
101
101
  return _fail(exc)
102
- print(styled(stack.summary(plan, path, apply_line=False)))
102
+ print(styled(summary(plan, path, apply_line=False)))
103
103
  answer = _confirm(None)
104
104
  if answer != "y":
105
105
  print(
@@ -181,6 +181,10 @@ def _code(message: str) -> str:
181
181
  return "CHECKSUM_MISMATCH"
182
182
  if "low disk space" in text or "no space left" in text:
183
183
  return "DISK_INSUFFICIENT"
184
+ if any(
185
+ phrase in text for phrase in ("redirect refused", "blocked redirect", "unsafe redirect")
186
+ ):
187
+ return "DOWNLOAD_FAILED"
184
188
  network = ("urlopen", "name or service", "timed out", "connection", "network", "resolve")
185
189
  if any(word in text for word in network):
186
190
  return "NETWORK_UNAVAILABLE"