@simplexai/localmodels-linux-x64 0.1.0-dev.37 → 0.1.0-dev.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +85 -78
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/bifrost_checks.py +9 -6
  6. package/modules/localmodels/bifrost_config.py +35 -1
  7. package/modules/localmodels/bifrost_datasheet.py +12 -2
  8. package/modules/localmodels/catalog.json +155 -8
  9. package/modules/localmodels/catalog.py +19 -1
  10. package/modules/localmodels/catalog_recipes.py +33 -2
  11. package/modules/localmodels/cli_parser.py +26 -3
  12. package/modules/localmodels/deploy.py +37 -9
  13. package/modules/localmodels/deploy_steps.py +6 -3
  14. package/modules/localmodels/download-mirrors.json +52 -4
  15. package/modules/localmodels/engines-b11583.json +20 -4
  16. package/modules/localmodels/engines-b12167.json +5 -1
  17. package/modules/localmodels/engines-strata-0.1.47.json +5 -1
  18. package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
  19. package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
  20. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
  21. package/modules/localmodels/engines-whisper-b5454.json +5 -1
  22. package/modules/localmodels/engines.json +55 -11
  23. package/modules/localmodels/frontend.py +5 -2
  24. package/modules/localmodels/gateway_bifrost.py +11 -9
  25. package/modules/localmodels/gateway_cli.py +4 -2
  26. package/modules/localmodels/guard.py +15 -6
  27. package/modules/localmodels/harness.py +65 -33
  28. package/modules/localmodels/harness_gateway.py +9 -3
  29. package/modules/localmodels/hf_repo.py +15 -8
  30. package/modules/localmodels/library_gateway.py +26 -13
  31. package/modules/localmodels/library_jobs.py +51 -3
  32. package/modules/localmodels/library_model.py +10 -0
  33. package/modules/localmodels/library_pricing.py +29 -22
  34. package/modules/localmodels/library_serve.py +5 -0
  35. package/modules/localmodels/library_state.py +9 -1
  36. package/modules/localmodels/library_status.py +30 -0
  37. package/modules/localmodels/llm_rank.py +83 -30
  38. package/modules/localmodels/metal_probe.py +16 -6
  39. package/modules/localmodels/npm_signatures.py +131 -0
  40. package/modules/localmodels/npm_transport.py +26 -10
  41. package/modules/localmodels/process_identity.py +32 -5
  42. package/modules/localmodels/recommend.py +5 -2
  43. package/modules/localmodels/region.py +244 -0
  44. package/modules/localmodels/remote_ops.py +69 -13
  45. package/modules/localmodels/remote_ops_download.py +210 -10
  46. package/modules/localmodels/remote_ops_prepare.py +61 -8
  47. package/modules/localmodels/runtime-lock.json +13 -13
  48. package/modules/localmodels/runtime_args.py +4 -2
  49. package/modules/localmodels/runtime_cli.py +19 -37
  50. package/modules/localmodels/runtime_discovery.py +30 -0
  51. package/modules/localmodels/runtime_install.py +81 -6
  52. package/modules/localmodels/runtime_io.py +61 -5
  53. package/modules/localmodels/runtime_pi.py +79 -0
  54. package/modules/localmodels/runtime_process.py +99 -15
  55. package/modules/localmodels/runtime_releases.py +51 -71
  56. package/modules/localmodels/search_server.py +5 -1
  57. package/modules/localmodels/service_probe.py +62 -4
  58. package/modules/localmodels/setup_inspection.py +21 -4
  59. package/modules/localmodels/setup_text.py +6 -0
  60. package/modules/localmodels/source_byok.py +484 -0
  61. package/modules/localmodels/source_byok_probe.py +275 -0
  62. package/modules/localmodels/source_cli.py +426 -0
  63. package/modules/localmodels/stack.py +31 -14
  64. package/modules/localmodels/stack_args.py +8 -4
  65. package/modules/localmodels/stack_binding.py +47 -4
  66. package/modules/localmodels/stack_cli.py +2 -0
  67. package/modules/localmodels/stack_compose.py +5 -5
  68. package/modules/localmodels/stack_events.py +3 -0
  69. package/modules/localmodels/stack_hardware.py +21 -6
  70. package/modules/localmodels/stack_llm_ram.py +16 -6
  71. package/modules/localmodels/stack_picks.py +4 -4
  72. package/modules/localmodels/stack_progress.py +9 -1
  73. package/modules/localmodels/stack_run.py +29 -0
  74. package/modules/localmodels/stack_suite.py +10 -3
  75. package/modules/localmodels/stack_warm.py +45 -4
  76. package/modules/localmodels/tools.json +1396 -32
  77. package/modules/localmodels/transport.py +40 -13
  78. package/modules/localmodels/windows_job.py +69 -0
  79. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/METADATA +1 -1
  80. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/RECORD +82 -75
  81. package/package.json +1 -1
  82. package/tool.json +1 -1
  83. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/WHEEL +0 -0
  84. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/entry_points.txt +0 -0
  85. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/NOTICE +0 -0
  86. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -6,6 +6,7 @@ import os
6
6
  import platform
7
7
  import re
8
8
  import shutil
9
+ import tempfile
9
10
  from pathlib import Path
10
11
 
11
12
  from localmodels import runtime_process
@@ -82,3 +83,32 @@ def compatible_version(
82
83
  if version is None or not runtime_process.version_ok(version, MINIMUM[runtime]):
83
84
  return False
84
85
  return before_version is None or version_key(version) < version_key(before_version)
86
+
87
+
88
+ PI_EXTENSION_MARKER = "localmodels-pi-extension-probe"
89
+ # TypeScript, so loading it needs the jiti transform Pi loads every extension with (Linger passes
90
+ # --extension <computer-tools>/extensions/pi-mcp.mjs on every run).
91
+ PI_EXTENSION_PROBE = f"""const marker: string = "{PI_EXTENSION_MARKER}";
92
+ export default function (_pi: unknown): void {{
93
+ process.stderr.write(marker + "\\n");
94
+ }}
95
+ """
96
+
97
+
98
+ def pi_loads_extensions(argv: list[str]) -> bool:
99
+ """Whether this Pi can load an extension. A Pi missing its dependencies (localmodels before
100
+ 0.1.0.dev39 installed only the bundled CLI and its image module) prints "Cannot find module
101
+ 'jiti'" and still exits 0, so the probe extension's own output is the evidence. The probe
102
+ runs with an empty private profile and without extension discovery: no user extension runs
103
+ and no user setting is read or written."""
104
+ with tempfile.TemporaryDirectory(prefix="localmodels-pi-probe-") as temporary:
105
+ directory = Path(temporary)
106
+ extension = directory / "probe.ts"
107
+ extension.write_text(PI_EXTENSION_PROBE, encoding="utf-8")
108
+ env = {**os.environ, "PI_CODING_AGENT_DIR": str(directory / "agent")}
109
+ code, output = runtime_process.probe(
110
+ [*argv, "--no-extensions", "--extension", str(extension), "--list-models"],
111
+ env,
112
+ timeout=30,
113
+ )
114
+ return code == 0 and PI_EXTENSION_MARKER in output
@@ -2,15 +2,20 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import contextlib
5
6
  import os
6
7
  import shutil
8
+ import threading
7
9
  from collections.abc import Callable
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from functools import partial
8
12
  from pathlib import Path
9
13
  from typing import Any
10
14
 
11
15
  from localmodels import http_local
12
16
  from localmodels.runtime_io import (
13
17
  Event,
18
+ Rate,
14
19
  cached_download,
15
20
  download,
16
21
  extract_archive,
@@ -32,17 +37,86 @@ def downloads_dir(root: Path, runtime: str) -> Path:
32
37
  return root / "tools" / ".downloads" / runtime
33
38
 
34
39
 
40
+ MODULE_DOWNLOADS = 8 # Pi's dependency tree is ~120 small tarballs; one at a time takes minutes
41
+
42
+
35
43
  def fetch_all(
36
44
  plan: dict[str, Any], event: Event, *, download_fn: Callable[..., Any] = download
37
45
  ) -> list[Path]:
38
- """Download every artifact first: one that failed leaves the others ready for the retry."""
46
+ """Download every artifact first: one that failed leaves the others ready for the retry.
47
+ Pi's dependency modules download together and report one byte count."""
48
+ cache = downloads_dir(Path(plan["root"]), plan["runtime"])
49
+ if plan.get("artifactSource") == "codex-stable-npm":
50
+ download_fn = partial(download_fn, retry_missing=True)
51
+ wanted = _wanted(plan)
52
+ found = {
53
+ a["digest"]: cached_download(cache, a, event, download_fn)
54
+ for a in wanted
55
+ if a and not a.get("destination")
56
+ }
57
+ modules = {a["digest"]: a for a in wanted if a and a.get("destination")}
58
+ found.update(_fetch_modules(cache, list(modules.values()), event, download_fn))
59
+ return [found[a["digest"]] if a else Path() for a in wanted]
60
+
61
+
62
+ def _fetch_modules(
63
+ cache: Path, artifacts: list[dict[str, Any]], event: Event, download_fn: Callable[..., Any]
64
+ ) -> dict[str, Path]:
65
+ if not artifacts:
66
+ return {}
67
+ total = sum(int(a["maxBytes"]) for a in artifacts) # the pinned sizes are exact
68
+ done: dict[str, int] = {}
69
+ lock = threading.Lock()
70
+ rate = Rate(0)
71
+ private_directory(cache) # once, before the downloads race to create it
72
+
73
+ def fetch(artifact: dict[str, Any]) -> Path:
74
+ def report(update: dict[str, Any]) -> None:
75
+ with lock:
76
+ if update.get("kind") != "progress":
77
+ if update.get("state") != "reused":
78
+ event(update)
79
+ return
80
+ done[artifact["digest"]] = int(update["completed"])
81
+ completed = min(total, sum(done.values()))
82
+ event(
83
+ {
84
+ "kind": "progress",
85
+ "stage": "download",
86
+ "completed": completed,
87
+ "total": total,
88
+ "unit": "bytes",
89
+ **rate.fields(completed, total),
90
+ }
91
+ )
92
+
93
+ path = cached_download(cache, artifact, report, download_fn)
94
+ with lock:
95
+ done[artifact["digest"]] = int(artifact["maxBytes"])
96
+ return path
97
+
98
+ with ThreadPoolExecutor(MODULE_DOWNLOADS) as pool:
99
+ futures = {a["digest"]: pool.submit(fetch, a) for a in artifacts}
100
+ return {digest: future.result() for digest, future in futures.items()} # first failure raises
101
+
102
+
103
+ def _wanted(plan: dict[str, Any]) -> list[dict[str, Any] | None]:
104
+ return [*plan["artifacts"], plan.get("nodeArtifact"), plan.get("launcherArtifact")]
105
+
106
+
107
+ def release_downloads(plan: dict[str, Any]) -> None:
108
+ """Delete the cached artifacts once the install is published. A file left behind is harmless:
109
+ the next apply verifies its digest and reuses it."""
39
110
  cache = downloads_dir(Path(plan["root"]), plan["runtime"])
40
- wanted = [*plan["artifacts"], plan.get("nodeArtifact"), plan.get("launcherArtifact")]
41
- return [cached_download(cache, a, event, download_fn) if a else Path() for a in wanted]
111
+ for artifact in _wanted(plan):
112
+ if artifact:
113
+ with contextlib.suppress(OSError):
114
+ (cache / artifact["digest"]).unlink(missing_ok=True)
42
115
 
43
116
 
44
117
  def take(kept: Path, file: Path) -> None:
45
- kept.rename(file)
118
+ # Copy, not move: the cache must survive a failed verification or interruption of this stage.
119
+ shutil.copyfile(kept, file)
46
120
  private_permissions(file, created=True)
47
121
 
48
122
 
@@ -67,10 +141,11 @@ def install_tree(
67
141
  else:
68
142
  unpack = stage / f"unpack-{index}"
69
143
  extract_archive(file, unpack)
70
- if plan["runtime"] == "pi" and index == 1:
144
+ if artifact.get("destination"): # a module of Pi's dependency tree
145
+ (top,) = unpack.iterdir() # npm drops the archive's one top directory
71
146
  target = tree / artifact["destination"]
72
147
  private_directory(target.parent)
73
- (unpack / "package").rename(target)
148
+ top.rename(target)
74
149
  else:
75
150
  for entry in unpack.iterdir():
76
151
  entry.rename(tree / entry.name)
@@ -23,6 +23,9 @@ from collections.abc import Callable
23
23
  from pathlib import Path
24
24
  from typing import Any, cast
25
25
 
26
+ # remote_ops before remote_ops_download: the bundle's entry module loads its siblings
27
+ from localmodels import region, remote_ops, remote_ops_download
28
+
26
29
  Event = Callable[[dict[str, Any]], None]
27
30
 
28
31
 
@@ -329,7 +332,9 @@ def _extract_archive(archive: Path, target: Path) -> None:
329
332
  private_permissions(destination, created=True)
330
333
  return
331
334
  with tarfile.open(archive) as tar:
332
- entries = tar.getmembers()
335
+ # npm tarballs may repeat a/b as a/./b; the last wins, as with tar (scripts/pin_pi.py
336
+ # refuses a pinned Pi archive whose repeats differ).
337
+ entries = list({_safe_member(e.name): e for e in tar.getmembers()}.values())
333
338
  for entry in entries:
334
339
  _safe_member(entry.name)
335
340
  if not (entry.isfile() or entry.isdir()):
@@ -432,7 +437,7 @@ class Rate:
432
437
  return found
433
438
 
434
439
 
435
- def _transfer(url: str, part: Path, limit: int, event: Event) -> None:
440
+ def _transfer(url: str, part: Path, limit: int, event: Event, *, retry_missing: bool) -> None:
436
441
  """One request for the rest of ``part``; network failures raise _TransferError."""
437
442
  have = part.stat().st_size
438
443
  request = urllib.request.Request(url, headers={"User-Agent": "localmodels-runtime"})
@@ -441,6 +446,8 @@ def _transfer(url: str, part: Path, limit: int, event: Event) -> None:
441
446
  try:
442
447
  source = urllib.request.urlopen(request, timeout=30)
443
448
  except urllib.error.HTTPError as exc:
449
+ if exc.code == 404 and retry_missing:
450
+ raise _TransferError("HTTP 404") from None
444
451
  if exc.code == 416 and have:
445
452
  part.write_bytes(b"") # the kept part no longer matches; start over
446
453
  raise _TransferError("the server could not resume the download") from None
@@ -489,6 +496,18 @@ def _interrupted(exc: BaseException) -> _TransferError:
489
496
  return _TransferError(reason, retryable=retryable)
490
497
 
491
498
 
499
+ def download_urls(url: str) -> list[str]:
500
+ """``url`` and the other hosts serving the same file (the npm mirror for the npm registry
501
+ and nodejs.org), in the download region's order. A URL with no other host does not resolve
502
+ the region."""
503
+ source: remote_ops.Source = {"source": "", "url": url}
504
+ every = [url, *(s["url"] for s in remote_ops_download.alternates(source))]
505
+ if len(every) == 1:
506
+ return every
507
+ cn = [u for u in every if remote_ops_download.side(u) == "cn"]
508
+ return region.prefer(region.current_region(), [u for u in every if u not in cn], cn)
509
+
510
+
492
511
  def download(
493
512
  artifact: dict[str, Any],
494
513
  destination: Path,
@@ -496,11 +515,48 @@ def download(
496
515
  *,
497
516
  attempts: int = DOWNLOAD_ATTEMPTS,
498
517
  pause: Callable[[float], None] = time.sleep,
518
+ retry_missing: bool = False,
499
519
  ) -> None:
500
520
  """Fetch a pinned artifact into ``destination``, which must not exist. Network failures are
501
521
  retried with backoff and each retry resumes ``destination.part``; a part left by an earlier
502
- call is resumed too. Only content matching the pinned digest is published."""
503
- url = artifact["url"]
522
+ call is resumed too. Only content matching the pinned digest is published. When every
523
+ retry against one host fails, the next host serving the same file (``download_urls``) is
524
+ tried, and a success on the other region's side switches the region."""
525
+ urls = download_urls(artifact["url"])
526
+ preferred = remote_ops_download.side(urls[0])
527
+ failed_preferred = False
528
+ for index, url in enumerate(urls):
529
+ try:
530
+ _download_from(
531
+ url,
532
+ artifact,
533
+ destination,
534
+ event,
535
+ attempts=attempts,
536
+ pause=pause,
537
+ retry_missing=retry_missing,
538
+ )
539
+ except RuntimeDownloadError:
540
+ if index + 1 == len(urls):
541
+ raise
542
+ failed_preferred = failed_preferred or remote_ops_download.side(url) == preferred
543
+ continue
544
+ used = remote_ops_download.side(url)
545
+ if failed_preferred and used and used != preferred:
546
+ region.fallback_to(used)
547
+ return
548
+
549
+
550
+ def _download_from(
551
+ url: str,
552
+ artifact: dict[str, Any],
553
+ destination: Path,
554
+ event: Event,
555
+ *,
556
+ attempts: int,
557
+ pause: Callable[[float], None],
558
+ retry_missing: bool,
559
+ ) -> None:
504
560
  part = destination.with_name(destination.name + ".part")
505
561
  if destination.exists() or destination.is_symlink():
506
562
  raise ValueError("Runtime download destination exists")
@@ -516,7 +572,7 @@ def download(
516
572
  while True:
517
573
  attempt += 1
518
574
  try:
519
- _transfer(url, part, artifact["maxBytes"], event)
575
+ _transfer(url, part, artifact["maxBytes"], event, retry_missing=retry_missing)
520
576
  break
521
577
  except _TransferError as exc:
522
578
  kept = part.stat().st_size
@@ -0,0 +1,79 @@
1
+ """Pi's native install plan and the replacement of an owned Pi that cannot load extensions.
2
+
3
+ Pi is one pinned release with its whole production dependency tree (``tools.json``, written by
4
+ ``scripts/pin_pi.py``); it never resolves the registry's newest release.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import shutil
12
+ import tempfile
13
+ from collections.abc import Callable
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from localmodels import runtime_process
18
+ from localmodels.harness import load_lock
19
+ from localmodels.runtime_discovery import private_file
20
+ from localmodels.runtime_install import bootstrap
21
+ from localmodels.runtime_releases import STABLE, version_key
22
+
23
+
24
+ def plan_install(
25
+ plan: dict[str, Any],
26
+ lock: dict[str, Any],
27
+ node: str | None,
28
+ launcher: str | None,
29
+ before_version: str | None,
30
+ *,
31
+ platform: str,
32
+ probe: Callable[[list[str]], tuple[int, str]],
33
+ ) -> None:
34
+ """Add the Node.js and, on Windows, the launcher the pinned Pi tree runs with."""
35
+ node_version = lock["node"]["version"]
36
+ if node:
37
+ if not Path(node).is_absolute() or not Path(node).is_file():
38
+ raise ValueError("Pi requires an absolute regular private Node path")
39
+ plan["bootstrap"].append(bootstrap(Path(node), "node.exe" if os.name == "nt" else "node"))
40
+ code, version = probe([node, "--version"])
41
+ match = STABLE.fullmatch(version.strip().removeprefix("v"))
42
+ if code != 0 or not match:
43
+ raise ValueError("The private Node executable could not report its version")
44
+ node_version = match.group()
45
+ else:
46
+ plan["nodeArtifact"] = lock["node"]["artifacts"][platform]
47
+ if platform.startswith("win32-"):
48
+ if launcher:
49
+ if not Path(launcher).is_absolute() or not Path(launcher).is_file():
50
+ raise ValueError("Windows Pi requires an absolute native launcher path")
51
+ plan["bootstrap"].append(bootstrap(Path(launcher), "pi.exe"))
52
+ else:
53
+ plan["launcherArtifact"] = lock["launchers"].get(platform)
54
+ if not plan["launcherArtifact"]:
55
+ raise ValueError("Windows Pi launcher artifact is unpublished; supply --launcher")
56
+ minimum = load_lock()["node"]["min_version"] # pi's engines.node, checked by pin_pi.py
57
+ if not runtime_process.version_ok(node_version, minimum):
58
+ raise ValueError(f"Pi {plan['version']} needs Node.js {minimum} or newer")
59
+ if before_version is not None and version_key(plan["version"]) >= version_key(before_version):
60
+ raise ValueError("Pi has no pinned release older than the --before-version bound")
61
+
62
+
63
+ def replace_broken(
64
+ target: Path, plan: dict[str, Any], loads_extensions: Callable[[list[str]], bool]
65
+ ) -> None:
66
+ """Retire an owned Pi of another plan at ``target`` that cannot load extensions:
67
+ 0.1.0.dev38 installed Pi 1.5.2 there without its dependencies. Anything else stays."""
68
+ marker = target / "localmodels-runtime.json"
69
+ if plan["runtime"] != "pi" or not private_file(marker):
70
+ return
71
+ if json.loads(marker.read_text()).get("planId") == plan["id"]:
72
+ return
73
+ if loads_extensions([str(target / ("pi.exe" if os.name == "nt" else "pi"))]):
74
+ return
75
+ # Move it aside, then delete it; a file still in use on Windows only leaves the hidden copy
76
+ # behind, under the runtime root that uninstall removes.
77
+ aside = Path(tempfile.mkdtemp(prefix=f".retired-{target.name}-", dir=target.parent))
78
+ target.rename(aside / target.name)
79
+ shutil.rmtree(aside, ignore_errors=True)
@@ -7,9 +7,11 @@ import os
7
7
  import re
8
8
  import signal
9
9
  import subprocess
10
+ import sys
10
11
  import tempfile
11
12
  import time
12
13
  from pathlib import Path
14
+ from typing import IO
13
15
 
14
16
  # Windows: a console child of the detached gateway worker gets its own visible console window
15
17
  # (closing it kills the gateway) unless CREATE_NO_WINDOW is set; CREATE_NEW_PROCESS_GROUP keeps
@@ -93,6 +95,83 @@ def await_group_exit(pgid: int, timeout: float = GROUP_EXIT_S) -> bool:
93
95
  # This sentinel cannot be a normal child exit code or a POSIX signal.
94
96
  PROBE_TIMEOUT = -1000
95
97
 
98
+ # A just-unpacked executable can be briefly unavailable to CreateProcess on Windows (for
99
+ # example while antivirus or indexing scans or locks it), so these spawn errors are retried.
100
+ SPAWN_RETRY_DELAYS = (0.25, 0.5, 1.0, 2.0, 4.0, 4.0)
101
+ _RETRYABLE_WINERRORS = (2, 5, 32, 225)
102
+
103
+
104
+ # taskkill's exit code when the PID no longer exists: the child exited before cleanup reached it.
105
+ TASKKILL_NOT_FOUND = 128
106
+
107
+
108
+ def _windows() -> bool:
109
+ return os.name == "nt"
110
+
111
+
112
+ def _diagnose(event: str, **fields: object) -> None:
113
+ """One stderr line of fixed categories; callers never pass paths, argv, env or native output."""
114
+ parts = [
115
+ f"{key}={'true' if value is True else 'false' if value is False else 'none' if value is None else value}"
116
+ for key, value in fields.items()
117
+ ]
118
+ print(" ".join([f"localmodels probe: {event}", *parts]), file=sys.stderr, flush=True)
119
+
120
+
121
+ def _spawn(
122
+ argv: list[str], env: dict[str, str] | None, output: IO[bytes]
123
+ ) -> subprocess.Popen[bytes]:
124
+ """Start the probe, retrying transient Windows spawn errors; one stderr line per failure
125
+ of an absolute executable records which error it was, without the path, environment or
126
+ exception text."""
127
+ attempt = 0
128
+ while True:
129
+ attempt += 1
130
+ try:
131
+ return subprocess.Popen(
132
+ argv,
133
+ stdin=subprocess.DEVNULL,
134
+ stdout=output,
135
+ stderr=subprocess.STDOUT,
136
+ env=env,
137
+ shell=False,
138
+ start_new_session=os.name != "nt",
139
+ creationflags=child_flags(),
140
+ )
141
+ except OSError as error:
142
+ winerror = getattr(error, "winerror", None)
143
+ retrying = (
144
+ _windows()
145
+ and winerror in _RETRYABLE_WINERRORS
146
+ and attempt <= len(SPAWN_RETRY_DELAYS)
147
+ )
148
+ # A bare PATH name that fails to spawn is an ordinary "not installed" result.
149
+ if argv and Path(argv[0]).is_absolute():
150
+ exists = "unknown"
151
+ with contextlib.suppress(OSError, ValueError):
152
+ exists = "true" if Path(argv[0]).exists() else "false"
153
+ _diagnose(
154
+ "spawn failed",
155
+ attempt=attempt,
156
+ winerror=winerror if isinstance(winerror, int) else None,
157
+ errno=error.errno if isinstance(error.errno, int) else None,
158
+ executable_exists=exists,
159
+ path_length=len(argv[0]),
160
+ retrying=bool(retrying),
161
+ )
162
+ if not retrying:
163
+ raise
164
+ time.sleep(SPAWN_RETRY_DELAYS[attempt - 1])
165
+
166
+
167
+ def _cleanup_failed(attempt: int, taskkill: int | None, process: subprocess.Popen[bytes]) -> None:
168
+ _diagnose(
169
+ "cleanup failed",
170
+ attempt=attempt,
171
+ taskkill=taskkill,
172
+ child_running=process.poll() is None,
173
+ )
174
+
96
175
 
97
176
  def probe(
98
177
  argv: list[str],
@@ -101,28 +180,33 @@ def probe(
101
180
  timeout: float = 5,
102
181
  retry_timeout: bool = False,
103
182
  ) -> tuple[int, str]:
104
- """Capture bounded public-read output; a timeout returns no native text."""
183
+ """Capture bounded public-read output; a timeout returns no native text. A child that exits
184
+ on its own while timeout cleanup runs (taskkill finds no PID) reports its real exit code."""
105
185
  for attempt in range(2 if retry_timeout else 1):
106
186
  process: subprocess.Popen[bytes] | None = None
107
187
  try:
108
188
  with tempfile.TemporaryFile() as output:
109
- process = subprocess.Popen(
110
- argv,
111
- stdin=subprocess.DEVNULL,
112
- stdout=output,
113
- stderr=subprocess.STDOUT,
114
- env=env,
115
- shell=False,
116
- start_new_session=os.name != "nt",
117
- creationflags=child_flags(),
118
- )
189
+ process = _spawn(argv, env, output)
119
190
  try:
120
191
  code = process.wait(timeout=timeout)
121
192
  except subprocess.TimeoutExpired:
122
- terminate_tree(process)
123
- if retry_timeout and attempt == 0:
124
- continue
125
- return PROBE_TIMEOUT, ""
193
+ retrying = retry_timeout and attempt == 0
194
+ try:
195
+ terminate_tree(process)
196
+ except subprocess.CalledProcessError as error:
197
+ if error.returncode != TASKKILL_NOT_FOUND or process.poll() is None:
198
+ _cleanup_failed(attempt + 1, error.returncode, process)
199
+ raise
200
+ code = process.returncode
201
+ _diagnose("exited during timeout cleanup", attempt=attempt + 1, code=code)
202
+ except Exception:
203
+ _cleanup_failed(attempt + 1, None, process)
204
+ raise
205
+ else:
206
+ _diagnose("timed out", attempt=attempt + 1, retrying=retrying)
207
+ if retrying:
208
+ continue
209
+ return PROBE_TIMEOUT, ""
126
210
  output.seek(0)
127
211
  return code, output.read(65536).decode("utf-8", errors="replace")
128
212
  except (OSError, subprocess.SubprocessError):