@simplexai/localmodels-darwin-arm64 0.1.0-dev.49 → 0.1.0-dev.51

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 (67) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +65 -59
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/catalog.json +2395 -9
  5. package/modules/localmodels/deploy.py +29 -134
  6. package/modules/localmodels/download-mirrors.json +47 -0
  7. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  8. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +132 -0
  9. package/modules/localmodels/gateway.py +23 -6
  10. package/modules/localmodels/gateway_bifrost.py +6 -2
  11. package/modules/localmodels/harness.py +8 -2
  12. package/modules/localmodels/harness_gateway.py +78 -17
  13. package/modules/localmodels/harness_probe.py +43 -23
  14. package/modules/localmodels/hosts.py +52 -5
  15. package/modules/localmodels/library_floor.py +76 -0
  16. package/modules/localmodels/library_gateway.py +17 -1
  17. package/modules/localmodels/library_jobs.py +38 -6
  18. package/modules/localmodels/library_model.py +5 -0
  19. package/modules/localmodels/library_poly.py +273 -0
  20. package/modules/localmodels/library_pricing.py +24 -35
  21. package/modules/localmodels/library_serve.py +7 -0
  22. package/modules/localmodels/library_state.py +16 -0
  23. package/modules/localmodels/library_status.py +114 -29
  24. package/modules/localmodels/llm_rank.py +14 -0
  25. package/modules/localmodels/magpie_windows.py +312 -0
  26. package/modules/localmodels/plan_envelope.py +234 -3
  27. package/modules/localmodels/probe.py +1 -1
  28. package/modules/localmodels/process_identity.py +19 -9
  29. package/modules/localmodels/process_identity_darwin.py +155 -0
  30. package/modules/localmodels/remote_ops.py +11 -0
  31. package/modules/localmodels/remote_ops_download.py +30 -5
  32. package/modules/localmodels/remote_ops_service.py +11 -13
  33. package/modules/localmodels/reuse.py +13 -6
  34. package/modules/localmodels/runtime_cli.py +8 -8
  35. package/modules/localmodels/runtime_install.py +25 -1
  36. package/modules/localmodels/runtime_io.py +32 -18
  37. package/modules/localmodels/setup_inspection.py +83 -79
  38. package/modules/localmodels/setup_inspection_harness.py +147 -0
  39. package/modules/localmodels/setup_text.py +12 -0
  40. package/modules/localmodels/setup_upgrade.py +11 -1
  41. package/modules/localmodels/stack.py +3 -1
  42. package/modules/localmodels/stack_auto.py +6 -2
  43. package/modules/localmodels/stack_cli.py +39 -0
  44. package/modules/localmodels/stack_clients.py +1 -1
  45. package/modules/localmodels/stack_compose.py +12 -43
  46. package/modules/localmodels/stack_down.py +25 -16
  47. package/modules/localmodels/stack_hardware.py +12 -1
  48. package/modules/localmodels/stack_picks.py +28 -13
  49. package/modules/localmodels/stack_plan.py +55 -3
  50. package/modules/localmodels/stack_remove.py +3 -1
  51. package/modules/localmodels/stack_suite.py +80 -20
  52. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  53. package/modules/localmodels/{strata-poly-serve-0.1.45-poly.9.txt → strata-poly-serve-0.2.20-poly.1.txt} +2 -2
  54. package/modules/localmodels/strata_poly_server.py +33 -2
  55. package/modules/localmodels/suite.py +45 -4
  56. package/modules/localmodels/tool_archive.py +4 -0
  57. package/modules/localmodels/vision.py +4 -2
  58. package/modules/localmodels/win_probe.py +24 -7
  59. package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/METADATA +1 -1
  60. package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/RECORD +62 -56
  61. package/package.json +1 -1
  62. package/tool.json +1 -1
  63. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +0 -75
  64. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/WHEEL +0 -0
  65. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/entry_points.txt +0 -0
  66. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/licenses/NOTICE +0 -0
  67. /package/modules/{simplex_localmodels-0.1.0.dev49.dist-info → simplex_localmodels-0.1.0.dev51.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -16,6 +16,7 @@ from localmodels import (
16
16
  harness,
17
17
  harness_probe,
18
18
  hosts,
19
+ magpie_windows,
19
20
  process_identity,
20
21
  remote_ops_service,
21
22
  runtime_io,
@@ -43,19 +44,34 @@ def address_port(addr: str) -> int:
43
44
  return port
44
45
 
45
46
 
47
+ def _tools_path(tools_dir: str | Path) -> Path:
48
+ return Path(hosts.tools_dir(tools_dir)).expanduser()
49
+
50
+
46
51
  def owned_address(addr: str, tools_dir: str, magpie: str | None) -> bool:
47
52
  """A socket is ours only with this private context's live process receipt."""
48
- if not magpie or hosts.load_owned(tools_dir)["gateway"]["started"] not in ("serve", "daemon"):
53
+ owned_gw = hosts.load_owned(tools_dir)["gateway"]
54
+ if not magpie or owned_gw["started"] not in ("serve", "daemon"):
49
55
  return False
50
- receipt = Path(tools_dir).expanduser() / SERVE_PID
56
+ receipt = _tools_path(tools_dir) / SERVE_PID
57
+ port = address_port(addr)
58
+ owned_magpie = owned_gw.get("magpie")
59
+ if owned_magpie is not None:
60
+ try:
61
+ if address_port(owned_magpie["addr"]) != port:
62
+ return False
63
+ except harness.HarnessError:
64
+ return False
51
65
  state, pid = process_identity.status(receipt)
52
- if state != "active" and process_identity.adopt_successor(receipt, magpie):
66
+ if state != "active" and magpie_windows.adopt_magpie_successor(
67
+ receipt, magpie, port=port, gateway_home=harness_probe.gateway_home(tools_dir)
68
+ ):
53
69
  state, pid = process_identity.status(receipt) # restarted into an updated binary
54
70
  if state != "active" or pid is None:
55
71
  return False
56
72
  if not remote_ops_service.command_matches(pid, [magpie, "serve"]):
57
73
  return False
58
- return remote_ops_service.listener_problem(address_port(addr), [pid]) is None
74
+ return remote_ops_service.listener_problem(port, [pid]) is None
59
75
 
60
76
 
61
77
  def address_listening(
@@ -100,9 +116,12 @@ def select_address(
100
116
  if requested:
101
117
  raise harness.HarnessError(
102
118
  f"Magpie gateway address {addr} is held by a program without proof of ownership;"
103
- " that program is kept"
119
+ " that program is kept",
120
+ code="gateway-port-in-use",
104
121
  )
105
- raise harness.HarnessError("Magpie default ports 3425..3456 are all in use")
122
+ raise harness.HarnessError(
123
+ "Magpie default ports 3425..3456 are all in use", code="gateway-port-in-use"
124
+ )
106
125
 
107
126
 
108
127
  def require_target(plan: harness.ToolPlan) -> None:
@@ -129,6 +148,7 @@ def plan_gateway(
129
148
  lock: harness.ToolLock | None = None,
130
149
  ) -> tuple[harness.ToolPlan, list[str]]:
131
150
  """The existing pinned Magpie installation without Agent clients or LLM routing."""
151
+ tools_dir = hosts.tools_dir(tools_dir)
132
152
  lock = lock or harness.load_lock()
133
153
  bin_dir = harness.BIN_DIR
134
154
  actions: list[harness.ToolAction] = []
@@ -159,7 +179,8 @@ def plan_gateway(
159
179
  f"Magpie gateway address {state['gateway_addr']} is held by another user's program;"
160
180
  " wiring into it would send your requests through someone else's gateway. Ask them to"
161
181
  " free the port, or set MAGPIE_ADDR=127.0.0.1:<free port> in the same terminal, then"
162
- " plan and apply again"
182
+ " plan and apply again",
183
+ code="gateway-port-in-use",
163
184
  )
164
185
  if state["gateway_up"]:
165
186
  actions.append(
@@ -202,9 +223,8 @@ def _standalone_target(tools_dir: str) -> harness.ToolPlan | None:
202
223
  try:
203
224
  saved = json.loads(path.read_text(encoding="utf-8"))
204
225
  tools = decode(saved["tools"], harness.ToolPlan)
205
- if (
206
- digest(saved) != saved["plan_id"]
207
- or Path(tools["tools_dir"]).expanduser() != Path(tools_dir).expanduser()
226
+ if digest(saved) != saved["plan_id"] or _tools_path(tools["tools_dir"]) != _tools_path(
227
+ tools_dir
208
228
  ):
209
229
  continue
210
230
  addr = next(t["path"] for t in tools["tools"] if t["tool"] == "gateway")
@@ -231,7 +251,7 @@ def _recorded_target(view: object, plan: object, tools_dir: str) -> harness.Tool
231
251
  and digest(plan) == plan.get("plan_id") == view.get("plan_id")
232
252
  and isinstance(plan.get("harness"), dict)
233
253
  and isinstance(plan["harness"].get("tools_dir"), str)
234
- and Path(plan["harness"]["tools_dir"]).expanduser() == Path(tools_dir).expanduser()
254
+ and _tools_path(plan["harness"]["tools_dir"]) == _tools_path(tools_dir)
235
255
  ):
236
256
  try:
237
257
  return decode(plan["harness"], harness.HarnessPlan)
@@ -280,7 +300,7 @@ def removal_target(
280
300
  or magpie is None
281
301
  or (binary := _magpie_tool(target)) is None
282
302
  or os.path.realpath(binary) != os.path.realpath(magpie)
283
- or Path(target["tools_dir"]).expanduser() != Path(tools_dir).expanduser()
303
+ or _tools_path(target["tools_dir"]) != _tools_path(tools_dir)
284
304
  ):
285
305
  return None
286
306
  try:
@@ -290,6 +310,40 @@ def removal_target(
290
310
  return target
291
311
 
292
312
 
313
+ def owned_magpie_target(record: hosts.OwnedMagpie) -> harness.ToolPlan:
314
+ """Reconstruct the approved ToolPlan for a private ``magpie serve`` recorded in owned.json."""
315
+ return {
316
+ "tools_dir": record["tools_dir"],
317
+ "tools": [
318
+ {
319
+ "tool": "magpie",
320
+ "action": "reuse",
321
+ "path": record["binary"],
322
+ "version": None,
323
+ "artifacts": [],
324
+ },
325
+ {
326
+ "tool": "gateway",
327
+ "action": "serve",
328
+ "path": record["addr"],
329
+ "version": None,
330
+ "artifacts": [],
331
+ },
332
+ ],
333
+ "download_bytes": 0,
334
+ "warnings": [],
335
+ }
336
+
337
+
338
+ def _recorded_magpie_target(tools_dir: str) -> harness.ToolPlan | None:
339
+ record = hosts.load_owned(tools_dir)["gateway"].get("magpie")
340
+ if record is None:
341
+ return None
342
+ if _tools_path(record["tools_dir"]) != _tools_path(tools_dir):
343
+ return None
344
+ return owned_magpie_target(record)
345
+
346
+
293
347
  def stop_gateway(
294
348
  magpie: str,
295
349
  started: str,
@@ -300,7 +354,7 @@ def stop_gateway(
300
354
  ) -> Check:
301
355
  """Signal only a process whose private receipt still proves the approved gateway.
302
356
  ``forget=False`` (``stack down``) keeps it recorded as started, so ``stack up`` starts it."""
303
- target = plan or accepted_plan(tools_dir)
357
+ target = plan or accepted_plan(tools_dir) or _recorded_magpie_target(tools_dir)
304
358
  failure: Check = {
305
359
  "check": "gateway",
306
360
  "ok": False,
@@ -312,15 +366,20 @@ def stop_gateway(
312
366
  if (
313
367
  target is None
314
368
  or started != "serve"
315
- or Path(target["tools_dir"]).expanduser() != Path(tools_dir).expanduser()
369
+ or _tools_path(target["tools_dir"]) != _tools_path(tools_dir)
316
370
  or (binary := _magpie_tool(target)) is None
317
371
  or os.path.realpath(binary) != os.path.realpath(magpie)
318
372
  ):
319
373
  return failure
320
- pid_file = Path(os.path.expanduser(tools_dir), "magpie-serve.pid")
374
+ gw_action = next((t for t in target["tools"] if t["tool"] == "gateway"), None)
375
+ gw_home = harness_probe.gateway_home(tools_dir)
376
+ pid_file = _tools_path(tools_dir) / SERVE_PID
321
377
  try:
378
+ port = address_port(gw_action["path"]) if gw_action is not None else None
322
379
  state, pid = process_identity.status(pid_file)
323
- if state != "active" and process_identity.adopt_successor(pid_file, magpie):
380
+ if state != "active" and magpie_windows.adopt_magpie_successor(
381
+ pid_file, magpie, port=port, gateway_home=gw_home
382
+ ):
324
383
  state, pid = process_identity.status(pid_file)
325
384
  if state == "active" and pid is not None:
326
385
  require_target(target)
@@ -342,6 +401,8 @@ def stop_gateway(
342
401
  }
343
402
  if forget:
344
403
  hosts.own_gateway(tools_dir, "started", None)
404
+ if hosts.load_owned(tools_dir)["gateway"].get("magpie") is not None:
405
+ hosts.own_magpie(tools_dir, None)
345
406
  return {"check": "gateway", "ok": True, "detail": SERVE_STOPPED[outcome]}
346
407
 
347
408
 
@@ -405,7 +466,7 @@ def purge_gateway_profile(plan: harness.ToolPlan | None, notes: list[str]) -> No
405
466
  )
406
467
  return
407
468
  else:
408
- pid_file = Path(plan["tools_dir"]).expanduser() / SERVE_PID
469
+ pid_file = _tools_path(plan["tools_dir"]) / SERVE_PID
409
470
  if process_identity.status(pid_file)[0] != "inactive":
410
471
  notes.append("- private gateway config kept: process still running or of unknown owner")
411
472
  return
@@ -13,7 +13,7 @@ import sys
13
13
  from pathlib import Path
14
14
  from typing import TYPE_CHECKING, TypedDict
15
15
 
16
- from localmodels import hosts, runtime_discovery
16
+ from localmodels import hosts, process_identity_darwin, runtime_discovery
17
17
 
18
18
  if TYPE_CHECKING:
19
19
  from localmodels import harness
@@ -64,16 +64,21 @@ def shown_pi_model(text: str) -> str | None:
64
64
 
65
65
 
66
66
  def listener_uids(addr: str, tables: tuple[str, ...] | None = None) -> set[int]:
67
- """The users whose sockets listen on ``addr``'s port: the given TCP tables (/proc's by default
68
- on Linux), lsof on macOS when no table is given."""
67
+ """The users whose sockets listen on ``addr`` (matching its host and port, plus wildcard
68
+ listeners): the given TCP tables (/proc's by default on Linux), lsof on macOS when no table
69
+ is given."""
69
70
  from localmodels.harness import HarnessError, run_tool
70
71
 
71
- port = int(addr.rpartition(":")[2])
72
+ host, port = process_identity_darwin.parse_host_port(addr)
72
73
  uids: set[int] = set()
73
74
  if tables is None and sys.platform == "win32":
74
75
  from localmodels import process_identity
75
76
 
76
- pids = process_identity.listener_pids(port)
77
+ pids = (
78
+ process_identity.listener_pids(port)
79
+ if host == "127.0.0.1"
80
+ else process_identity.listener_pids(port, host=host)
81
+ )
77
82
  if pids is None:
78
83
  raise HarnessError("cannot confirm who owns the Windows gateway listener")
79
84
  for pid in pids:
@@ -82,16 +87,17 @@ def listener_uids(addr: str, tables: tuple[str, ...] | None = None) -> set[int]:
82
87
  return uids
83
88
  if tables is None and sys.platform == "darwin":
84
89
  out = run_tool(
85
- ["/usr/sbin/lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpu"], timeout=10
90
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpun"], timeout=10
86
91
  )
87
- if out.returncode not in (0, 1):
92
+ parsed = process_identity_darwin.parse_lsof_listeners(out.stdout, port, host)
93
+ if out.returncode not in (0, 1) or parsed is None:
88
94
  raise HarnessError("cannot confirm who owns the macOS gateway listener")
89
- uids = {int(line[1:]) for line in out.stdout.splitlines() if re.fullmatch(r"u\d+", line)}
90
- if out.returncode == 0 and not uids:
95
+ _, uids, _, saw_uid = parsed
96
+ if out.returncode == 0 and not saw_uid:
91
97
  raise HarnessError("cannot confirm who owns the macOS gateway listener")
92
98
  if not uids:
93
99
  try:
94
- with socket.create_connection((addr.rpartition(":")[0], port), timeout=1):
100
+ with socket.create_connection((host, port), timeout=1):
95
101
  raise HarnessError(
96
102
  "the macOS gateway port is listening, but its owner cannot be confirmed"
97
103
  )
@@ -106,7 +112,9 @@ def listener_uids(addr: str, tables: tuple[str, ...] | None = None) -> set[int]:
106
112
  for row in rows: # sl local rem st tx:rx tr:when retrnsmt uid ...
107
113
  f = row.split()
108
114
  if len(f) > 7 and f[3] == "0A" and int(f[1].rpartition(":")[2], 16) == port:
109
- uids.add(int(f[7]))
115
+ bound = process_identity_darwin.parse_proc_net_addr(f[1].rpartition(":")[0])
116
+ if bound is None or process_identity_darwin.address_conflicts(bound, host):
117
+ uids.add(int(f[7]))
110
118
  return uids
111
119
 
112
120
 
@@ -145,12 +153,12 @@ def loopback_listener_pids(port: int, proc: str = _PROC) -> set[int] | None:
145
153
  from localmodels.harness import run_tool
146
154
 
147
155
  out = run_tool(
148
- ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"], timeout=10
156
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpn"], timeout=10
149
157
  )
150
- lines = out.stdout.splitlines()
151
- if out.returncode not in (0, 1) or any(not ln[1:].isdecimal() for ln in lines):
158
+ parsed = process_identity_darwin.parse_lsof_listeners(out.stdout, port, "127.0.0.1")
159
+ if out.returncode not in (0, 1) or parsed is None:
152
160
  return None
153
- return {int(ln[1:]) for ln in lines if ln[:1] == "p"}
161
+ return parsed[0]
154
162
  if not sys.platform.startswith("linux"):
155
163
  return None
156
164
  from localmodels import remote_ops_service
@@ -163,10 +171,11 @@ def loopback_listener_pids(port: int, proc: str = _PROC) -> set[int] | None:
163
171
  return _linux_socket_owner_pids(inodes, proc, uid=os.getuid())
164
172
 
165
173
 
166
- def port_holder(port: int, proc: str = _PROC) -> str | None:
167
- """Who listens on ``port``, for a refusal the operator can act on: "name (pid N)" for this
168
- user's own process, "a process of user uid N" for another user's, None when /proc shows no
169
- listener or cannot be read (Linux only; the caller then says nothing more)."""
174
+ def port_holder(port: int, proc: str = _PROC, *, host: str = "127.0.0.1") -> str | None:
175
+ """Who listens on ``port`` conflicting with ``host``, for a refusal the operator can act on:
176
+ "name (pid N)" for this user's own process, "a process of user uid N" for another user's, None
177
+ when /proc shows no matching listener or cannot be read (Linux only; the caller then says
178
+ nothing more)."""
170
179
  inodes: dict[str, int] = {}
171
180
  for table in ("net/tcp", "net/tcp6"):
172
181
  try:
@@ -176,7 +185,9 @@ def port_holder(port: int, proc: str = _PROC) -> str | None:
176
185
  for row in rows: # sl local rem st tx:rx tr:when retrnsmt uid timeout inode
177
186
  f = row.split()
178
187
  if len(f) > 9 and f[3] == "0A" and int(f[1].rpartition(":")[2], 16) == port:
179
- inodes[f[9]] = int(f[7])
188
+ bound = process_identity_darwin.parse_proc_net_addr(f[1].rpartition(":")[0])
189
+ if bound is None or process_identity_darwin.address_conflicts(bound, host):
190
+ inodes[f[9]] = int(f[7])
180
191
  if not inodes:
181
192
  return None
182
193
  for pid in sorted(_linux_socket_owner_pids(set(inodes), proc)):
@@ -242,6 +253,8 @@ def gateway_environment(
242
253
  MAGPIE_CONFIG_DIR=str(private / ".config/magpie"),
243
254
  XDG_DATA_HOME=str(private / ".local/share"),
244
255
  XDG_CACHE_HOME=str(private / ".cache"),
256
+ APPDATA=str(private / "AppData/Roaming"),
257
+ LOCALAPPDATA=str(private / "AppData/Local"),
245
258
  )
246
259
  env.setdefault("PI_CODING_AGENT_DIR", str(home / ".pi/agent"))
247
260
  env.setdefault("CODEX_HOME", str(home / ".codex"))
@@ -269,7 +282,9 @@ def inspect(
269
282
  from localmodels import harness_gateway, stack_clients
270
283
 
271
284
  env = dict(os.environ if env is None else env)
272
- tools_dir = os.path.expanduser(approved["tools_dir"] if approved else tools_dir)
285
+ tools_dir = os.path.expanduser(
286
+ hosts.tools_dir(approved["tools_dir"] if approved else tools_dir, env=env)
287
+ )
273
288
  path = env.get("PATH", "")
274
289
  home = env.get("HOME") or os.path.expanduser("~")
275
290
  bin_dir = os.path.join(home, harness.BIN_DIR.removeprefix("~/"))
@@ -387,8 +402,13 @@ def loopback_listening(port: int) -> bool:
387
402
  def bifrost_held(addr: str) -> str:
388
403
  """The refusal for a listener of this user's that the manifest does not own, naming it: a
389
404
  bifrost-http is most often another HOME's or state directory's localmodels gateway."""
390
- port = addr.rpartition(":")[2]
391
- held = port_holder(int(port)) if port.isdigit() else None
405
+ host, _, port = addr.rpartition(":")
406
+ target = host.strip("[]") or "127.0.0.1"
407
+ held = (
408
+ (port_holder(int(port)) if target == "127.0.0.1" else port_holder(int(port), host=target))
409
+ if port.isdigit()
410
+ else None
411
+ )
392
412
  other = (
393
413
  "; it is not in this tool's owned manifest, so it is most likely the localmodels "
394
414
  "gateway of another HOME or state directory"
@@ -12,7 +12,7 @@ import os
12
12
  import re
13
13
  import threading
14
14
  import time
15
- from collections.abc import Callable, Iterator
15
+ from collections.abc import Callable, Iterator, Mapping
16
16
  from contextlib import contextmanager
17
17
  from pathlib import Path
18
18
  from typing import Any, Literal, TypedDict, TypeVar
@@ -346,6 +346,15 @@ class OwnedBifrost(_OwnedBifrostSince20261110):
346
346
  binary: str
347
347
 
348
348
 
349
+ class OwnedMagpie(TypedDict):
350
+ """A private ``magpie serve`` instance this tool launched for its own gateway-home."""
351
+
352
+ addr: str
353
+ binary: str
354
+ gateway_home: str
355
+ tools_dir: str
356
+
357
+
349
358
  class _OwnedGatewaySince20261031(TypedDict, total=False):
350
359
  caller_keys: list[str] # ids of the Magpie gateway keys (callers' keys) this tool added
351
360
  # The Magpie search APIs this tool added for the web search service the stack used to run:
@@ -353,6 +362,7 @@ class _OwnedGatewaySince20261031(TypedDict, total=False):
353
362
  search: str # the searxng search API URL
354
363
  search_you: bool # Magpie's You.com search API, the free fallback after it
355
364
  bifrost: OwnedBifrost # since 2026-11-02: the Bifrost gateway this tool runs
365
+ magpie: OwnedMagpie # since 2026-11-20: private magpie serve launched for this gateway-home
356
366
 
357
367
 
358
368
  class OwnedGateway(_OwnedGatewaySince20261031):
@@ -424,12 +434,37 @@ def empty_owned() -> Owned:
424
434
  }
425
435
 
426
436
 
427
- def tools_dir(given: str | Path = TOOLS_DIR) -> str:
437
+ def _strip_trailing_sep(path: str) -> str:
438
+ cleaned = path.rstrip("/\\")
439
+ return cleaned if cleaned and not cleaned.endswith(":") else path
440
+
441
+
442
+ def _is_default_tools_dir(given: str | Path, env: Mapping[str, str] | None = None) -> bool:
443
+ raw = str(given)
444
+ if raw.replace("\\", "/").rstrip("/") == TOOLS_DIR:
445
+ return True
446
+ norm_given = os.path.normcase(os.path.normpath(os.path.expanduser(raw)))
447
+ norm_default = os.path.normcase(os.path.normpath(os.path.expanduser(TOOLS_DIR)))
448
+ if norm_given == norm_default:
449
+ return True
450
+ if env is not None:
451
+ home = env.get("HOME") or env.get("USERPROFILE")
452
+ if home:
453
+ env_default = os.path.normcase(
454
+ os.path.normpath(os.path.join(home, TOOLS_DIR.removeprefix("~/")))
455
+ )
456
+ if norm_given == env_default:
457
+ return True
458
+ return False
459
+
460
+
461
+ def tools_dir(given: str | Path = TOOLS_DIR, *, env: Mapping[str, str] | None = None) -> str:
428
462
  """The tools root: ``LOCALMODELS_TOOLS_DIR`` overrides the default ``TOOLS_DIR``."""
429
- if str(given) == TOOLS_DIR and (
430
- override := os.environ.get("LOCALMODELS_TOOLS_DIR", "").strip()
463
+ environ = os.environ if env is None else env
464
+ if (override := environ.get("LOCALMODELS_TOOLS_DIR", "").strip()) and _is_default_tools_dir(
465
+ given, env=env
431
466
  ):
432
- return override
467
+ return _strip_trailing_sep(override)
433
468
  return str(given)
434
469
 
435
470
 
@@ -520,6 +555,18 @@ def own_gateway(
520
555
  update_owned(change, tools_dir)
521
556
 
522
557
 
558
+ def own_magpie(tools_dir: str | Path, record: OwnedMagpie | None) -> None:
559
+ """Record or clear the private ``magpie serve`` instance launched by this tool."""
560
+
561
+ def change(doc: Owned) -> None:
562
+ if record is None:
563
+ doc["gateway"].pop("magpie", None)
564
+ else:
565
+ doc["gateway"]["magpie"] = record
566
+
567
+ update_owned(change, tools_dir)
568
+
569
+
523
570
  def forget_search(tools_dir: str | Path, field: Literal["search", "search_you"]) -> None:
524
571
  """Forget a Magpie search API this tool added for the web search service it used to run."""
525
572
 
@@ -0,0 +1,76 @@
1
+ """Floor metadata for library models that do not fit this computer's pools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from localmodels import budget, context_policy, library_pricing, metal, suite, vision
6
+ from localmodels.estimator import agent_footprint_bytes, eager
7
+ from localmodels.library_pricing import Model
8
+ from localmodels.probe import HostFacts
9
+
10
+
11
+ def floor_metadata(
12
+ facts: HostFacts,
13
+ model: Model,
14
+ shortfall_bytes: int = 0,
15
+ *,
16
+ memory_kind: str = "",
17
+ ) -> tuple[int, int, bool, int]:
18
+ """Estimated floor memory, context window, vision flag and download bytes when a model does
19
+ not fit this computer's pools (``plan is None``), using the same agent posture.
20
+
21
+ Honors per-entry posture overrides (such as ``ubatch``), accounts for Metal and CUDA UMA
22
+ unified memory, and avoids mixing host RAM shortfalls (``memory_kind == "ram"``) into VRAM
23
+ floor bytes.
24
+ """
25
+ if model.entry.runtime == "strata-poly":
26
+ recipe = suite.recipe(model.entry.id)
27
+ window = int(recipe.get("context") or model.entry.n_ctx_train)
28
+ active = model.entry.agent_posture(
29
+ context_policy.posture_for(library_pricing.posture(), "cuda")
30
+ )
31
+ vision_on = bool(recipe.get("vision")) and active.vision != "off"
32
+ download = sum(
33
+ int(f["size_bytes"]) for f in recipe["files"] if vision_on or not f.get("vision")
34
+ )
35
+ floor_bytes = int(recipe.get("min_vram_free_bytes") or recipe.get("vram_bytes") or 0)
36
+ effective_shortfall = 0 if memory_kind == "ram" else shortfall_bytes
37
+ return max(effective_shortfall, floor_bytes), window, vision_on, download
38
+ metal_unified = metal.supported(facts)
39
+ cuda_uma = not metal_unified and budget.unified_pool_bytes(facts) is not None
40
+ active = model.entry.agent_posture(
41
+ context_policy.posture_for(library_pricing.posture(), "metal" if metal_unified else "cuda")
42
+ )
43
+ profile = eager(model.entry.profile(model.variant))
44
+ window = profile.n_ctx_train if 0 < profile.n_ctx_train < active.floor else active.floor
45
+ vision_on = vision.llama_reader_enabled(model.entry.mmproj, active.vision)
46
+ mtp = bool(model.entry.mtp_capable and model.entry.agent_mtp and active.mtp_draft_depth > 0)
47
+ core = agent_footprint_bytes(
48
+ profile,
49
+ window,
50
+ slots=active.slots,
51
+ kv_types=active.kv_types[-1],
52
+ ubatch=active.ubatch,
53
+ mtp=mtp,
54
+ )
55
+ if metal_unified or cuda_uma:
56
+ vision_extra = (
57
+ vision.llama_device_bytes(model.entry.mmproj, "gpu")
58
+ if vision_on and model.entry.mmproj is not None
59
+ else 0
60
+ )
61
+ host_side = (
62
+ context_policy.cache_floor_bytes(active, profile)
63
+ + context_policy.metal_host_bytes(profile, active)
64
+ if metal_unified
65
+ else 0
66
+ )
67
+ floor_bytes = core + vision_extra + host_side
68
+ else:
69
+ floor_bytes = core
70
+ download = sum(f.size_bytes for f in model.variant.files)
71
+ if vision_on and model.entry.mmproj is not None:
72
+ download += model.entry.mmproj.size_bytes
73
+ if model.entry.mtp_head is not None:
74
+ download += model.entry.mtp_head.size_bytes
75
+ effective_shortfall = 0 if memory_kind == "ram" else shortfall_bytes
76
+ return max(effective_shortfall, floor_bytes), window, vision_on, download
@@ -257,6 +257,21 @@ def _pi_add(provider: str, entry: dict[str, Any], base: str) -> None:
257
257
  _write(path, models)
258
258
 
259
259
 
260
+ def _marker_for_other_file(marker: Path, path: Path) -> bool:
261
+ """Whether ``marker`` records ownership of a different existing ``models.json``."""
262
+ try:
263
+ recorded = marker.read_text(encoding="utf-8").strip()
264
+ except OSError:
265
+ return False
266
+ if not recorded:
267
+ return False
268
+ other = Path(recorded)
269
+ try:
270
+ return other.resolve() != path.resolve() and other.is_file()
271
+ except OSError:
272
+ return False
273
+
274
+
260
275
  def _pi_drop(provider: str, model_id: str) -> None:
261
276
  marker = _ours_marker(provider)
262
277
  if not marker.is_file():
@@ -266,7 +281,8 @@ def _pi_drop(provider: str, model_id: str) -> None:
266
281
  providers = models.get("providers")
267
282
  current = providers.get(provider) if isinstance(providers, dict) else None
268
283
  if not isinstance(providers, dict) or not isinstance(current, dict):
269
- marker.unlink(missing_ok=True)
284
+ if not _marker_for_other_file(marker, path):
285
+ marker.unlink(missing_ok=True)
270
286
  return
271
287
  kept = [m for m in current.get("models", []) if m.get("id") != model_id]
272
288
  if kept:
@@ -21,6 +21,7 @@ from pathlib import Path
21
21
  from localmodels import (
22
22
  app,
23
23
  deploy_steps,
24
+ frontend,
24
25
  hosts,
25
26
  library_gateway,
26
27
  library_pricing,
@@ -147,6 +148,11 @@ def delete_weights(files: list[str], keep: set[str]) -> list[str]:
147
148
  return deleted
148
149
 
149
150
 
151
+ KEEP_FAILED_DOWNLOAD_CODES = frozenset(
152
+ ("DOWNLOAD_FAILED", "NETWORK_UNAVAILABLE", "DISK_INSUFFICIENT")
153
+ )
154
+
155
+
150
156
  def _code(message: str) -> str:
151
157
  text = message.lower()
152
158
  if "sha256 mismatch" in text:
@@ -173,16 +179,24 @@ def _download_telemetry(phase: str, event: dict[str, object]) -> tuple[str | Non
173
179
 
174
180
 
175
181
  class _Counter:
176
- """Bytes of the whole model: the files already verified count as done; each progress event
177
- moves its file's counter for the phase it reports."""
182
+ """Bytes of the whole model: the files already verified (or partially downloaded on disk)
183
+ count as done; each progress event moves its file's counter for the phase it reports."""
178
184
 
179
185
  def __init__(self, model: str, plan: Plan, handle: JobHandle) -> None:
180
186
  self.model, self.handle = model, handle
181
187
  self.sizes = {os.path.basename(f["dest"]): f["size_bytes"] for f in plan["files"]}
182
188
  self.done = {
183
- os.path.basename(f["dest"]): f["size_bytes"]
189
+ os.path.basename(f["dest"]): (
190
+ f["size_bytes"]
191
+ if plan_envelope.verified_in_place(f)
192
+ else min(
193
+ f["size_bytes"],
194
+ remote_ops_download.kept_bytes(
195
+ os.path.expanduser(f["dest"]) + ".part", f["size_bytes"]
196
+ ),
197
+ )
198
+ )
184
199
  for f in plan["files"]
185
- if plan_envelope.verified_in_place(f)
186
200
  }
187
201
 
188
202
  @property
@@ -250,7 +264,9 @@ def fetch(
250
264
  """The plan's engine (when it is a pinned release) and weights, as stack apply fetches them;
251
265
  ``only`` limits the weights to the files this job claims. Progress counts the whole model."""
252
266
  counter = _Counter(model, plan, handle)
253
- progress(model, "download", sum(counter.done.values()), counter.total)
267
+ initial_done = sum(counter.done.values())
268
+ handle.update("download", initial_done, counter.total)
269
+ progress(model, "download", initial_done, counter.total)
254
270
  files = [f for f in plan["files"] if only is None or os.path.expanduser(f["dest"]) in only]
255
271
  steps: tuple[Action, ...] = ("download",) if files else ()
256
272
  if engine and plan["engine"]["source"] == "release":
@@ -264,6 +280,11 @@ def fetch(
264
280
  if result.returncode != 0 or outcome.get("event") != "result":
265
281
  message = str(outcome.get("message") or result.stderr.strip()[-500:] or "failed")
266
282
  raise LibraryError(_code(message), message, failed=True)
283
+ if engine and (reqs := plan["launch"].get("frontend_requirements")):
284
+ try:
285
+ frontend.install(str(plan["launch"]["frontend_base_dir"]), str(reqs))
286
+ except frontend.FrontendError as exc:
287
+ raise LibraryError("DOWNLOAD_FAILED", str(exc), failed=True) from None
267
288
  progress(model, "verify", counter.total, counter.total)
268
289
 
269
290
 
@@ -426,7 +447,8 @@ def download(
426
447
  others = claimed_elsewhere(model.id)
427
448
  mine = [f for f in files if os.path.realpath(f) not in others]
428
449
  job = library_state.acquire("download", model.id, priced.pool, memory, mine, files)
429
- with library_state.held([job]):
450
+ claims = [job]
451
+ with library_state.held(claims):
430
452
  handle = library_state.JobHandle(job)
431
453
  try:
432
454
  _fetch_and_commit(model, plan, handle, priced.pool, memory, base_dir, mine, files)
@@ -437,6 +459,16 @@ def download(
437
459
  if library_state.load(model.id) is None:
438
460
  _give_up(model.id, job, handle)
439
461
  raise LibraryError("CANCELLED", "the download was cancelled") from None
462
+ except LibraryError as exc:
463
+ if exc.code in KEEP_FAILED_DOWNLOAD_CODES:
464
+ with library_state.locked():
465
+ if library_state.load(model.id) is None and library_state.current(job):
466
+ if library_state.cancelled(job):
467
+ _give_up(model.id, job, handle)
468
+ raise LibraryError("CANCELLED", "the download was cancelled") from None
469
+ library_state.fail_job(handle.job, {"code": exc.code, "detail": exc.detail})
470
+ claims.clear()
471
+ raise
440
472
  if not autoload:
441
473
  return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
442
474
  try:
@@ -15,6 +15,7 @@ STATUS_SCHEMA = "localmodels.library-status/v1"
15
15
  EVENT_SCHEMA = "localmodels.library-event/v1"
16
16
 
17
17
  ModelState = Literal["absent", "downloading", "idle", "loading", "loaded", "failed"]
18
+ Engine = Literal["llama.cpp", "polystrata", "strata"]
18
19
  Fit = Literal["gpu", "unified", "system", "none"]
19
20
  Phase = Literal["download", "verify", "load", "warm"]
20
21
  MemoryPressure = Literal["normal", "warn", "critical"]
@@ -229,6 +230,10 @@ class Row(_Row, total=False):
229
230
  license: str
230
231
  source_url: str
231
232
  prompt_tokens_per_second: float # the last load's measured prefill speed
233
+ engine: Engine # inference engine family serving this row
234
+ engine_label: str # engine, pinned build and backend for display
235
+ concurrency: int # maximum simultaneous requests served (slots / parallel)
236
+ host_ram_bytes: int # system RAM held beside VRAM by a hybrid discrete-GPU engine
232
237
  fits_now: bool # live pool currently has enough free memory to load
233
238
  load_need_bytes: int # pool-aligned memory needed to load when fits_now is False
234
239
  load_free_bytes: int # pool-aligned free memory when fits_now is False