@simplexai/localmodels-darwin-arm64 0.1.0-dev.50 → 0.1.0-dev.52

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 (40) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +38 -38
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/catalog.json +1988 -16
  5. package/modules/localmodels/catalog_recipes.py +47 -8
  6. package/modules/localmodels/contracts.py +96 -37
  7. package/modules/localmodels/deploy.py +29 -134
  8. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +132 -0
  9. package/modules/localmodels/engines.py +18 -2
  10. package/modules/localmodels/gateway_bifrost.py +9 -0
  11. package/modules/localmodels/harness_probe.py +38 -22
  12. package/modules/localmodels/library_gateway.py +132 -1
  13. package/modules/localmodels/library_model.py +5 -0
  14. package/modules/localmodels/library_poly.py +59 -0
  15. package/modules/localmodels/library_status.py +96 -31
  16. package/modules/localmodels/plan_envelope.py +234 -3
  17. package/modules/localmodels/process_identity.py +19 -9
  18. package/modules/localmodels/process_identity_darwin.py +155 -0
  19. package/modules/localmodels/remote_ops_service.py +11 -13
  20. package/modules/localmodels/runtime_cli.py +8 -8
  21. package/modules/localmodels/runtime_install.py +25 -1
  22. package/modules/localmodels/source_cli.py +9 -1
  23. package/modules/localmodels/stack.py +0 -5
  24. package/modules/localmodels/stack_binding.py +6 -2
  25. package/modules/localmodels/stack_cli.py +39 -0
  26. package/modules/localmodels/stack_compose.py +12 -43
  27. package/modules/localmodels/stack_plan.py +58 -5
  28. package/modules/localmodels/stack_suite.py +51 -12
  29. package/modules/localmodels/{strata-poly-serve-0.1.45-poly.9.txt → strata-poly-serve-0.2.20-poly.1.txt} +2 -2
  30. package/modules/localmodels/strata_poly_server.py +19 -0
  31. package/modules/localmodels/suite.py +45 -8
  32. package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/METADATA +1 -1
  33. package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/RECORD +35 -35
  34. package/package.json +1 -1
  35. package/tool.json +1 -1
  36. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +0 -75
  37. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/WHEEL +0 -0
  38. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/entry_points.txt +0 -0
  39. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/licenses/NOTICE +0 -0
  40. /package/modules/{simplex_localmodels-0.1.0.dev50.dist-info → simplex_localmodels-0.1.0.dev52.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -8,17 +8,34 @@ from __future__ import annotations
8
8
  import datetime as dt
9
9
  import functools
10
10
  import hashlib
11
+ import http.client
11
12
  import json
12
13
  import os
13
14
  import re
15
+ import sys
16
+ import time
17
+ import urllib.error
14
18
  import urllib.parse
15
- from collections.abc import Mapping
19
+ import urllib.request
20
+ from collections.abc import Callable, Mapping, Sequence
16
21
  from dataclasses import dataclass
17
22
  from pathlib import Path
23
+ from typing import TypedDict
18
24
 
25
+ from localmodels import catalog as cat
26
+ from localmodels import region
19
27
  from localmodels.budget import gib
28
+ from localmodels.contracts import decode
20
29
  from localmodels.probe import HostFacts
21
- from localmodels.records import Launch, ModelSpec, Plan, ReleaseEngine, ReusableFile, ServicePlan
30
+ from localmodels.records import (
31
+ Launch,
32
+ ModelSpec,
33
+ PinnedFile,
34
+ Plan,
35
+ ReleaseEngine,
36
+ ReusableFile,
37
+ ServicePlan,
38
+ )
22
39
  from localmodels.remote_ops import Source
23
40
 
24
41
  PLAN_SCHEMA = "localmodels.deployment-plan/v1"
@@ -27,6 +44,219 @@ PLAN_SCHEMA = "localmodels.deployment-plan/v1"
27
44
  class PlanError(ValueError):
28
45
  """The deployment cannot be planned as requested; the message says why."""
29
46
 
47
+ def __init__(self, message: str, *, cause_code: str | None = None) -> None:
48
+ super().__init__(message)
49
+ self.cause_code = cause_code
50
+
51
+
52
+ _COMMIT_SHA = re.compile(r"^[0-9a-f]{40}$")
53
+ _HF_GET_ATTEMPTS = 3
54
+ _HF_RETRY_DELAYS_S = (0.25, 0.75)
55
+
56
+
57
+ class HubUnreachableError(PlanError):
58
+ """The Hub API could not be reached over the network."""
59
+
60
+ def __init__(self, failures: Sequence[tuple[str, str]]) -> None:
61
+ self.failures = tuple(failures)
62
+ if len(self.failures) == 1:
63
+ host, reason = self.failures[0]
64
+ where = f"{host} to look up the model files ({reason})"
65
+ else:
66
+ where = (
67
+ " or ".join(f"{host} ({reason})" for host, reason in self.failures)
68
+ + " to look up the model files"
69
+ )
70
+ super().__init__(
71
+ f"cannot reach {where}; "
72
+ "name a reachable Hub with --hf-endpoint URL or HF_ENDPOINT (a mirror such as "
73
+ "https://hf-mirror.com), or plan from the catalog's pins with --offline",
74
+ cause_code="HUB_UNREACHABLE",
75
+ )
76
+
77
+
78
+ def _is_timeout(exc: BaseException) -> bool:
79
+ return isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError)
80
+
81
+
82
+ def hf_get(url: str) -> object:
83
+ """One Hub API document. Transient non-timeout disconnects retry briefly; timeouts fail over
84
+ immediately so a blackholed host does not stall."""
85
+ req = urllib.request.Request(url, headers={"User-Agent": "localmodels-plan"})
86
+ for attempt in range(_HF_GET_ATTEMPTS):
87
+ try:
88
+ with urllib.request.urlopen(req, timeout=20) as r:
89
+ return json.load(r)
90
+ except urllib.error.HTTPError:
91
+ raise # the Hub answered: a missing repo or revision is the caller's to report
92
+ except (OSError, http.client.HTTPException) as exc:
93
+ if _is_timeout(exc) or attempt + 1 >= _HF_GET_ATTEMPTS:
94
+ host = urllib.parse.urlsplit(url).netloc
95
+ raise HubUnreachableError([(host, str(getattr(exc, "reason", exc)))]) from exc
96
+ time.sleep(_HF_RETRY_DELAYS_S[attempt])
97
+ raise AssertionError("unreachable Hub retry loop")
98
+
99
+
100
+ def hub_get(
101
+ api: str,
102
+ path: str,
103
+ *,
104
+ mint: bool = False,
105
+ fetch: Callable[[str], object] = hf_get,
106
+ ) -> object:
107
+ """One Hub API document across region-ordered endpoints, preserving every failed host's reason."""
108
+ endpoints = [api.rstrip("/")] if mint else region.hub_endpoints(api)
109
+ failures: list[tuple[str, str]] = []
110
+ for index, endpoint in enumerate(endpoints):
111
+ try:
112
+ doc = fetch(endpoint + path)
113
+ except PlanError as exc:
114
+ if isinstance(exc, HubUnreachableError):
115
+ failures.extend(exc.failures)
116
+ else:
117
+ failures.append((urllib.parse.urlsplit(endpoint).netloc, str(exc)))
118
+ if index + 1 < len(endpoints):
119
+ continue
120
+ if mint and not region.explicit_hub(api):
121
+ what = path.split("/api/models/")[-1]
122
+ raise PlanError(
123
+ region.MINT_REFUSAL.format(what=what),
124
+ cause_code="HUB_UNREACHABLE",
125
+ ) from exc
126
+ if len(failures) > 1:
127
+ raise HubUnreachableError(failures) from exc
128
+ raise
129
+ if index:
130
+ region.fallback_to(region.side_of_endpoint(endpoint))
131
+ return doc
132
+ raise AssertionError("unreachable Hub loop")
133
+
134
+
135
+ class _Revision(TypedDict):
136
+ sha: str
137
+
138
+
139
+ class _LfsFile(TypedDict):
140
+ size: int
141
+ oid: str
142
+
143
+
144
+ class _TreeEntry(TypedDict):
145
+ path: str
146
+
147
+
148
+ class _OptionalTreeEntry(_TreeEntry, total=False):
149
+ lfs: _LfsFile
150
+
151
+
152
+ def _can_use_catalog_pin(asset: cat.AssetFile, api: str) -> bool:
153
+ return (
154
+ asset.sha256 is not None
155
+ and bool(_COMMIT_SHA.fullmatch(asset.revision))
156
+ and not region.explicit_hub(api)
157
+ )
158
+
159
+
160
+ def _pinned_from_catalog(repo: str, asset: cat.AssetFile) -> PinnedFile:
161
+ assert asset.sha256 is not None
162
+ return {
163
+ "repo": repo,
164
+ "path": asset.path,
165
+ "revision": asset.revision,
166
+ "size_bytes": asset.size_bytes,
167
+ "sha256": asset.sha256,
168
+ "local_name": asset.local_name,
169
+ }
170
+
171
+
172
+ def resolve_files(
173
+ assets: list[tuple[str, cat.AssetFile]],
174
+ api: str,
175
+ *,
176
+ fetch_hub: Callable[..., object] = hub_get,
177
+ ) -> list[PinnedFile]:
178
+ """Pin each asset via the Hub API, falling back to exact catalog pins when the default Hub is
179
+ unreachable over the network."""
180
+ revisions: dict[tuple[str, str, bool], str] = {}
181
+ trees: dict[tuple[str, str, str, bool], dict[str, _OptionalTreeEntry]] = {}
182
+ pinned: list[PinnedFile] = []
183
+ hub_offline = False
184
+ noticed_repos: set[str] = set()
185
+ for repo, asset in assets:
186
+ mint = asset.sha256 is None
187
+ fallback_ok = _can_use_catalog_pin(asset, api)
188
+ if hub_offline and fallback_ok:
189
+ pinned.append(_pinned_from_catalog(repo, asset))
190
+ continue
191
+ key = (repo, asset.revision, mint)
192
+ try:
193
+ if key not in revisions:
194
+ doc = decode(
195
+ fetch_hub(
196
+ api,
197
+ f"/api/models/{repo}/revision/{urllib.parse.quote(asset.revision)}",
198
+ mint=mint,
199
+ ),
200
+ _Revision,
201
+ )
202
+ revisions[key] = doc["sha"]
203
+ commit = revisions[key]
204
+ directory = asset.path.rsplit("/", 1)[0] if "/" in asset.path else ""
205
+ tkey = (repo, commit, directory, mint)
206
+ if tkey not in trees:
207
+ path = f"/api/models/{repo}/tree/{commit}" + (
208
+ f"/{urllib.parse.quote(directory)}" if directory else ""
209
+ )
210
+ entries = fetch_hub(api, path, mint=mint)
211
+ if not isinstance(entries, list):
212
+ raise PlanError("Hub tree must be an array")
213
+ parsed = [decode(e, _OptionalTreeEntry) for e in entries]
214
+ trees[tkey] = {e["path"]: e for e in parsed}
215
+ except HubUnreachableError:
216
+ if not fallback_ok:
217
+ raise
218
+ hub_offline = True
219
+ if repo not in noticed_repos:
220
+ noticed_repos.add(repo)
221
+ print(
222
+ f"localmodels: Hub unreachable; using catalog pins for {repo}",
223
+ file=sys.stderr,
224
+ )
225
+ pinned.append(_pinned_from_catalog(repo, asset))
226
+ continue
227
+ entry = trees[tkey].get(asset.path)
228
+ if entry is None or not entry.get("lfs"):
229
+ raise PlanError(f"{asset.path} not found in {repo}@{commit[:12]}")
230
+ if int(entry["lfs"]["size"]) != asset.size_bytes:
231
+ raise PlanError(
232
+ f"{asset.path} size {entry['lfs']['size']} != catalog size {asset.size_bytes}"
233
+ )
234
+ if asset.sha256 is not None and entry["lfs"]["oid"] != asset.sha256:
235
+ raise PlanError(f"{asset.path} on the Hub has a SHA256 the catalog does not pin")
236
+ pinned.append(
237
+ {
238
+ "repo": repo,
239
+ "path": asset.path,
240
+ "revision": commit,
241
+ "size_bytes": asset.size_bytes,
242
+ "sha256": entry["lfs"]["oid"],
243
+ "local_name": asset.local_name,
244
+ }
245
+ )
246
+ return pinned
247
+
248
+
249
+ def catalog_pins(assets: list[tuple[str, cat.AssetFile]], _api: str) -> list[PinnedFile]:
250
+ """Each asset at the commit and SHA256 the catalog pins, asking the Hub nothing."""
251
+ pinned: list[PinnedFile] = []
252
+ for repo, asset in assets:
253
+ if asset.sha256 is None:
254
+ raise PlanError(
255
+ f"catalog pins no commit and SHA256 for {repo}/{asset.path}; cannot plan it offline"
256
+ )
257
+ pinned.append(_pinned_from_catalog(repo, asset))
258
+ return pinned
259
+
30
260
 
31
261
  def deployment_name(model_id: str, port: int) -> str:
32
262
  return re.sub(r"[^a-z0-9.-]+", "-", f"{model_id}-{port}".lower())
@@ -154,7 +384,8 @@ def require_disk(facts: HostFacts, files: list[ReusableFile], *, local: bool = F
154
384
  if free is not None and total > free:
155
385
  raise PlanError(
156
386
  f"not enough disk space: needs {gib(total)}, {facts['disk']['path']} has only "
157
- f"{gib(free)} free"
387
+ f"{gib(free)} free",
388
+ cause_code="DISK_INSUFFICIENT",
158
389
  )
159
390
 
160
391
 
@@ -264,13 +264,17 @@ def image_path(pid: int) -> str | None:
264
264
  return found[1] or None if found else None
265
265
 
266
266
 
267
- def listener_pids(port: int) -> set[int] | None:
268
- """Windows: PIDs listening on TCP ``port`` (IPv4/IPv6 iphlpapi tables), or None on failure."""
267
+ def listener_pids(port: int, *, host: str = "127.0.0.1") -> set[int] | None:
268
+ """Windows: PIDs listening on TCP ``port`` conflicting with ``host``, or None on failure."""
269
+ import ipaddress
269
270
  import struct
270
271
 
271
272
  iphlpapi = ctypes.WinDLL("iphlpapi") # type: ignore[attr-defined]
272
273
  owners: set[int] = set()
273
- for family, row_size, port_at, pid_at in ((2, 24, 8, 20), (23, 56, 20, 52)):
274
+ for family, row_size, addr_at, addr_len, port_at, pid_at in (
275
+ (2, 24, 4, 4, 8, 20),
276
+ (23, 56, 0, 16, 20, 52),
277
+ ):
274
278
  size = ctypes.c_ulong(0)
275
279
  # TCP_TABLE_OWNER_PID_LISTENER = 3; first call sizes the buffer.
276
280
  iphlpapi.GetExtendedTcpTable(None, ctypes.byref(size), False, family, 3, 0)
@@ -286,7 +290,15 @@ def listener_pids(port: int) -> set[int] | None:
286
290
  for index in range(count):
287
291
  row = 4 + index * row_size
288
292
  local_port = struct.unpack_from(">H", raw, row + port_at)[0]
289
- if local_port == port:
293
+ if local_port != port:
294
+ continue
295
+ addr_bytes = raw[row + addr_at : row + addr_at + addr_len]
296
+ bound = (
297
+ ipaddress.IPv4Address(addr_bytes)
298
+ if addr_len == 4
299
+ else ipaddress.IPv6Address(addr_bytes)
300
+ )
301
+ if process_identity_darwin.address_conflicts(bound, host):
290
302
  owners.add(struct.unpack_from("<I", raw, row + pid_at)[0])
291
303
  return owners
292
304
 
@@ -681,7 +693,7 @@ def listener_owned(port: int, pid: int | None) -> bool:
681
693
  return False
682
694
  try:
683
695
  res = subprocess.run(
684
- ["/usr/sbin/lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"],
696
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpn"],
685
697
  capture_output=True,
686
698
  text=True,
687
699
  timeout=5,
@@ -689,10 +701,8 @@ def listener_owned(port: int, pid: int | None) -> bool:
689
701
  )
690
702
  except (OSError, subprocess.TimeoutExpired):
691
703
  return False
692
- owners = {
693
- int(ln[1:]) for ln in res.stdout.splitlines() if ln.startswith("p") and ln[1:].isdigit()
694
- }
695
- return res.returncode == 0 and owners == {pid}
704
+ parsed = process_identity_darwin.parse_lsof_listeners(res.stdout, port, "127.0.0.1")
705
+ return res.returncode == 0 and parsed is not None and parsed[0] == {pid}
696
706
 
697
707
 
698
708
  def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
@@ -9,8 +9,10 @@ from __future__ import annotations
9
9
 
10
10
  import ctypes
11
11
  import errno
12
+ import ipaddress
12
13
  import os
13
14
  import struct
15
+ import sys
14
16
  from pathlib import Path
15
17
  from typing import Any
16
18
 
@@ -187,3 +189,156 @@ def command_info(pid: int) -> tuple[list[str], Path] | None:
187
189
  return None
188
190
  exec_path, argv = parsed
189
191
  return argv, Path(exec_path)
192
+
193
+
194
+ def parse_host_port(addr: str) -> tuple[str, int]:
195
+ """Split ``host:port`` (including bracketed IPv6 ``[::1]:port``)."""
196
+ host, sep, port_text = addr.strip().rpartition(":")
197
+ if not sep or not port_text.isdecimal():
198
+ raise ValueError(f"invalid address: {addr!r}")
199
+ if host.startswith("[") and host.endswith("]"):
200
+ host = host[1:-1]
201
+ return host, int(port_text)
202
+
203
+
204
+ def _parse_ip(raw: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
205
+ text = raw.strip()
206
+ if text.startswith("[") and text.endswith("]"):
207
+ text = text[1:-1]
208
+ text = text.partition("%")[0]
209
+ try:
210
+ parsed = ipaddress.ip_address(text)
211
+ except ValueError:
212
+ return None
213
+ if isinstance(parsed, ipaddress.IPv6Address):
214
+ return parsed.ipv4_mapped or parsed
215
+ return parsed
216
+
217
+
218
+ def address_conflicts(
219
+ bound: str | ipaddress.IPv4Address | ipaddress.IPv6Address, target: str
220
+ ) -> bool:
221
+ """Whether a listener bound to ``bound`` can receive or block traffic for ``target``.
222
+
223
+ Wildcard/unspecified bindings (``*``, ``0.0.0.0``, ``::``) conflict with every target.
224
+ Unparseable addresses fail closed (return True) so unknown listeners are never ignored.
225
+ """
226
+ target_text = target.strip()
227
+ if target_text in ("", "*", "0.0.0.0", "::", "[::]"):
228
+ return True
229
+ if isinstance(bound, str):
230
+ bound_text = bound.strip()
231
+ if bound_text in ("", "*"):
232
+ return True
233
+ bound_ip = _parse_ip(bound_text)
234
+ if bound_ip is None:
235
+ return True
236
+ elif isinstance(bound, ipaddress.IPv6Address):
237
+ bound_ip = bound.ipv4_mapped or bound
238
+ else:
239
+ bound_ip = bound
240
+ if bound_ip.is_unspecified:
241
+ return True
242
+ if target_text.lower() == "localhost":
243
+ return bound_ip in (ipaddress.IPv4Address("127.0.0.1"), ipaddress.IPv6Address("::1"))
244
+ target_ip = _parse_ip(target_text)
245
+ if target_ip is None or target_ip.is_unspecified:
246
+ return True
247
+ return bound_ip == target_ip
248
+
249
+
250
+ def parse_proc_net_addr(hex_addr: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
251
+ """Decode Linux ``/proc/net/tcp`` or ``/proc/net/tcp6`` local hex address."""
252
+ if len(hex_addr) not in (8, 32):
253
+ return None
254
+ try:
255
+ packed = b"".join(
256
+ int(hex_addr[i : i + 8], 16).to_bytes(4, sys.byteorder)
257
+ for i in range(0, len(hex_addr), 8)
258
+ )
259
+ bound = ipaddress.ip_address(packed)
260
+ except ValueError:
261
+ return None
262
+ if isinstance(bound, ipaddress.IPv6Address):
263
+ return bound.ipv4_mapped or bound
264
+ return bound
265
+
266
+
267
+ def _lsof_name_conflicts(name: str, port: int, target_host: str) -> bool:
268
+ host, sep, port_text = name.rpartition(":")
269
+ if not sep or not port_text.isdecimal():
270
+ return True
271
+ return int(port_text) == port and address_conflicts(host, target_host)
272
+
273
+
274
+ class _LsofCursor:
275
+ """Mutable cursor for parsing one ``lsof -Fpn`` / ``-Fpun`` stream."""
276
+
277
+ def __init__(self, port: int, target_host: str) -> None:
278
+ self.port = port
279
+ self.target_host = target_host
280
+ self.pids: set[int] = set()
281
+ self.uids: set[int] = set()
282
+ self.cur_pid: int | None = None
283
+ self.cur_uid: int | None = None
284
+ self.saw_proc = self.saw_uid = self.saw_name = self.fd_unlabeled = False
285
+
286
+ def _record(self) -> None:
287
+ if self.cur_pid is not None:
288
+ self.pids.add(self.cur_pid)
289
+ if self.cur_uid is not None:
290
+ self.uids.add(self.cur_uid)
291
+
292
+ def flush(self) -> None:
293
+ if self.cur_pid is not None and (not self.saw_name or self.fd_unlabeled):
294
+ self._record()
295
+
296
+ def feed(self, line: str) -> bool:
297
+ if not line:
298
+ return False
299
+ tag, value = line[0], line[1:]
300
+ if tag == "p":
301
+ if not value.isdecimal() or value == "0":
302
+ return False
303
+ self.flush()
304
+ self.cur_pid, self.cur_uid = int(value), None
305
+ self.saw_name = self.fd_unlabeled = False
306
+ self.saw_proc = True
307
+ return True
308
+ if self.cur_pid is None:
309
+ return False
310
+ if tag == "u":
311
+ if not value.isdecimal():
312
+ return False
313
+ self.cur_uid, self.saw_uid = int(value), True
314
+ return True
315
+ if tag == "f":
316
+ if not value.isdecimal():
317
+ return False
318
+ if self.fd_unlabeled:
319
+ self._record()
320
+ self.fd_unlabeled = True
321
+ return True
322
+ if tag == "n" and value:
323
+ self.saw_name, self.fd_unlabeled = True, False
324
+ if _lsof_name_conflicts(value, self.port, self.target_host):
325
+ self._record()
326
+ return True
327
+ return False
328
+
329
+
330
+ def parse_lsof_listeners(
331
+ output: str, port: int, target_host: str = "127.0.0.1"
332
+ ) -> tuple[set[int], set[int], bool, bool] | None:
333
+ """Parse ``lsof -Fpn`` / ``-Fpun`` output into ``(pids, uids, saw_proc, saw_uid)``.
334
+
335
+ Only sockets whose bound address conflicts with ``target_host`` on ``port`` are included;
336
+ records without an ``n`` socket name fail closed and are included. Returns None when any
337
+ line is malformed or attributes a listener to PID 0.
338
+ """
339
+ cursor = _LsofCursor(port, target_host)
340
+ for line in output.splitlines():
341
+ if not cursor.feed(line):
342
+ return None
343
+ cursor.flush()
344
+ return cursor.pids, cursor.uids, cursor.saw_proc, cursor.saw_uid
@@ -140,16 +140,16 @@ def _previous_install(
140
140
 
141
141
 
142
142
  def _darwin_listener_pids(port: int) -> set[int] | None:
143
- """Processes listening on TCP ``port`` (lsof; its warnings about unrelated mounts aside)."""
144
- argv = ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"]
143
+ """Processes listening on loopback TCP ``port`` (lsof; its warnings about unrelated mounts aside)."""
144
+ argv = ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpn"]
145
145
  try:
146
146
  done = subprocess.run(argv, capture_output=True, text=True, timeout=10, check=False)
147
147
  except (OSError, subprocess.SubprocessError):
148
148
  return None
149
- lines = done.stdout.splitlines()
150
- if done.returncode not in (0, 1) or any(not ln[1:].isdecimal() for ln in lines):
149
+ parsed = process_identity_darwin.parse_lsof_listeners(done.stdout, port, "127.0.0.1")
150
+ if done.returncode not in (0, 1) or parsed is None:
151
151
  return None
152
- return {int(ln[1:]) for ln in lines if ln[:1] == "p"}
152
+ return parsed[0]
153
153
 
154
154
 
155
155
  def _process_state(pid: int) -> str | None:
@@ -576,7 +576,7 @@ def _darwin_listener_problem(port: int, pids: list[int]) -> str | None:
576
576
  unknown = "who holds the port is unknown, not probed"
577
577
  try:
578
578
  result = subprocess.run(
579
- ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fp"],
579
+ ["/usr/sbin/lsof", "-wnP", f"-iTCP:{port}", "-sTCP:LISTEN", "-Fpn"],
580
580
  capture_output=True,
581
581
  text=True,
582
582
  timeout=10,
@@ -584,14 +584,12 @@ def _darwin_listener_problem(port: int, pids: list[int]) -> str | None:
584
584
  )
585
585
  except (OSError, subprocess.SubprocessError):
586
586
  return unknown
587
- lines = result.stdout.splitlines()
588
- if result.returncode or result.stderr or not lines:
589
- return unknown
590
- if any(line[:1] not in ("p", "f") or not line[1:].isdecimal() for line in lines):
591
- return unknown # -Fp: a p line per process, an f line per listening descriptor
592
- owners = {int(line[1:]) for line in lines if line[:1] == "p"}
593
- if 0 in owners:
587
+ parsed = process_identity_darwin.parse_lsof_listeners(result.stdout, port, "127.0.0.1")
588
+ if result.returncode or result.stderr or parsed is None or not parsed[2]:
594
589
  return unknown
590
+ owners = parsed[0]
591
+ if not owners:
592
+ return "the port is not listening"
595
593
  return None if owners <= set(pids) else "another process holds the port, not probed"
596
594
 
597
595
 
@@ -9,7 +9,6 @@ import os
9
9
  import re
10
10
  import subprocess
11
11
  import sys
12
- import tempfile
13
12
  import time
14
13
  from pathlib import Path
15
14
  from typing import Any
@@ -60,9 +59,11 @@ def _active_profile(runtime: str, env: dict[str, str]) -> Path:
60
59
  return Path(env.get(PROFILE_KEYS[runtime], str(Path.home() / PROFILE_DIRS[runtime])))
61
60
 
62
61
 
63
- def _probe(argv: list[str], env: dict[str, str] | None = None) -> tuple[int, str]:
64
- """Bound execution and output; raw native messages never enter public reports."""
65
- return runtime_process.probe(argv, env, retry_timeout=bool(argv and argv[-1] == "--version"))
62
+ def _probe(
63
+ argv: list[str], env: dict[str, str] | None = None, *, timeout: float = 5
64
+ ) -> tuple[int, str]:
65
+ retry_timeout = argv[-1:] == ["--version"]
66
+ return runtime_process.probe(argv, env, timeout=timeout, retry_timeout=retry_timeout)
66
67
 
67
68
 
68
69
  class RuntimeVersionVerificationError(ValueError):
@@ -566,9 +567,7 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
566
567
  replace = True
567
568
  private_directory(target.parent)
568
569
  event({"kind": "stage", "stage": "install", "state": "running"})
569
- # Short names: Windows allows 260 characters, and Pi's tree has files 138 below its root
570
- with tempfile.TemporaryDirectory(prefix=".s", dir=target.parent) as temporary:
571
- stage = Path(temporary)
570
+ with runtime_install.install_stage(target.parent) as stage:
572
571
  private_permissions(stage, created=True)
573
572
  tree = _install_tree(plan, stage, event)
574
573
  command = (
@@ -577,7 +576,8 @@ def apply_plan(plan: dict[str, Any], approve: str, event: Event = lambda _: None
577
576
  else [str(tree / ("pi.exe" if os.name == "nt" else "pi"))]
578
577
  )
579
578
  event({"kind": "stage", "stage": "verify", "state": "running"})
580
- code, version = _probe(command + ["--version"])
579
+ timeout = 10 if runtime == "pi" and plan["platform"].startswith("win32-") else 5
580
+ code, version = _probe(command + ["--version"], timeout=timeout)
581
581
  try:
582
582
  _require_installed_version(code, version, plan["version"])
583
583
  if runtime == "pi" and not pi_loads_extensions(command):
@@ -5,8 +5,10 @@ from __future__ import annotations
5
5
  import contextlib
6
6
  import os
7
7
  import shutil
8
+ import sys
9
+ import tempfile
8
10
  import threading
9
- from collections.abc import Callable
11
+ from collections.abc import Callable, Iterator
10
12
  from concurrent.futures import ThreadPoolExecutor, as_completed
11
13
  from functools import partial
12
14
  from pathlib import Path
@@ -25,6 +27,28 @@ from localmodels.runtime_io import (
25
27
  )
26
28
 
27
29
 
30
+ @contextlib.contextmanager
31
+ def install_stage(parent: Path) -> Iterator[Path]:
32
+ """Remove the stage while preserving an install failure if its files are still busy."""
33
+ # Keep the stage name short for the Windows Pi dependency tree.
34
+ temporary = tempfile.TemporaryDirectory(prefix=".s", dir=parent)
35
+ try:
36
+ yield Path(temporary.name)
37
+ except BaseException:
38
+ try:
39
+ temporary.cleanup()
40
+ except OSError as error:
41
+ print(
42
+ "localmodels harness: stage cleanup failed"
43
+ f" errno={error.errno} winerror={getattr(error, 'winerror', None)}",
44
+ file=sys.stderr,
45
+ flush=True,
46
+ )
47
+ raise
48
+ else:
49
+ temporary.cleanup()
50
+
51
+
28
52
  def bootstrap(path: Path, destination: str) -> dict[str, str]:
29
53
  if path.is_symlink():
30
54
  raise ValueError("Unsafe bootstrap executable")
@@ -18,6 +18,7 @@ from localmodels import (
18
18
  library_jobs,
19
19
  library_serve,
20
20
  library_state,
21
+ library_status,
21
22
  runtime_cli,
22
23
  source_byok,
23
24
  source_byok_probe,
@@ -318,10 +319,17 @@ def _apply_local(args: argparse.Namespace) -> SourceState:
318
319
  if r.get("state") == "loaded" and str(r["id"]) != args.model
319
320
  ]
320
321
  current = next((r for r in library_state.records() if str(r["id"]) == args.model), None)
321
- if current is None or current.get("state") != "loaded":
322
+ answering = bool(
323
+ current is not None
324
+ and current.get("state") == "loaded"
325
+ and library_status.answering(str(current["plan"]["endpoint"]["base_url"]))
326
+ )
327
+ if not answering or _gateway_url() is None:
322
328
  library_serve.load(args.model, args.base_dir, others)
323
329
  loaded = _loaded_local_record()
324
330
  reg = (loaded or {}).get("registration") or {}
331
+ if reg and _gateway_url() is not None:
332
+ library_gateway.reconcile_pi_default(cast(library_state.Registration, reg))
325
333
  return source_byok.save_source_state(
326
334
  {
327
335
  "schema": source_byok.SOURCE_SCHEMA,
@@ -96,11 +96,6 @@ def build(
96
96
  raise StackError(error)
97
97
  # The preflight checks the Mac as it is, before --unified-memory prices a smaller one.
98
98
  raw = copy.deepcopy(seen)
99
- if seen["platform"] == "win32" and options.get("gateway") == "bifrost":
100
- raise StackError( # the default follows the computer planning; --facts may be another's
101
- "the stack runs Magpie on Windows (decision 48); plan Windows facts with --gateway"
102
- " magpie, the gateway stack plan picks on Windows itself"
103
- )
104
99
  seen = hardware.assumed(seen, options.get("unified_memory"))
105
100
  resolver = deploy.catalog_pins if options.get("offline") else deploy.resolve_files
106
101
  context = approved