@simplexai/localmodels-linux-arm64 0.1.0-dev.61 → 0.1.0-dev.63

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 +66 -63
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_checks.py +19 -13
  5. package/modules/localmodels/bifrost_clients.py +38 -36
  6. package/modules/localmodels/bifrost_config.py +19 -6
  7. package/modules/localmodels/bifrost_log.py +3 -3
  8. package/modules/localmodels/bifrost_models.py +9 -8
  9. package/modules/localmodels/bifrost_pi.py +27 -72
  10. package/modules/localmodels/catalog.json +51 -58
  11. package/modules/localmodels/custom_hub.py +10 -1
  12. package/modules/localmodels/custom_hub_http.py +41 -107
  13. package/modules/localmodels/debug_mode.py +3 -3
  14. package/modules/localmodels/gateway.py +56 -55
  15. package/modules/localmodels/gateway_bifrost.py +70 -83
  16. package/modules/localmodels/gateway_clients.py +33 -116
  17. package/modules/localmodels/gateway_home.py +5 -5
  18. package/modules/localmodels/gateway_keys.py +8 -6
  19. package/modules/localmodels/gateway_probe.py +4 -4
  20. package/modules/localmodels/gateway_server.py +4 -4
  21. package/modules/localmodels/gateway_speed.py +2 -2
  22. package/modules/localmodels/harness.py +185 -401
  23. package/modules/localmodels/harness_core.py +409 -0
  24. package/modules/localmodels/harness_gateway.py +75 -73
  25. package/modules/localmodels/harness_probe.py +19 -216
  26. package/modules/localmodels/library_custom.py +51 -16
  27. package/modules/localmodels/library_elastic.py +1 -1
  28. package/modules/localmodels/library_gateway.py +59 -176
  29. package/modules/localmodels/library_jobs.py +4 -0
  30. package/modules/localmodels/library_model.py +23 -0
  31. package/modules/localmodels/library_pricing.py +2 -2
  32. package/modules/localmodels/library_serve.py +5 -3
  33. package/modules/localmodels/library_smoke.py +33 -21
  34. package/modules/localmodels/library_status.py +330 -2
  35. package/modules/localmodels/llm_rank.py +14 -5
  36. package/modules/localmodels/magpie_setup.py +5 -4
  37. package/modules/localmodels/magpie_windows.py +1 -1
  38. package/modules/localmodels/memcalc_load.py +9 -4
  39. package/modules/localmodels/pi_profile.py +384 -0
  40. package/modules/localmodels/process_identity.py +3 -3
  41. package/modules/localmodels/remote_ops_common.py +31 -90
  42. package/modules/localmodels/remote_ops_download.py +2 -0
  43. package/modules/localmodels/remote_ops_mirrors.py +1 -1
  44. package/modules/localmodels/remote_ops_ranges.py +4 -1
  45. package/modules/localmodels/remote_ops_redirect.py +393 -0
  46. package/modules/localmodels/runtime_cli.py +32 -46
  47. package/modules/localmodels/runtime_pi.py +1 -1
  48. package/modules/localmodels/source_byok.py +9 -16
  49. package/modules/localmodels/source_cli.py +136 -23
  50. package/modules/localmodels/speech_jobs.py +4 -0
  51. package/modules/localmodels/stack_binding.py +9 -7
  52. package/modules/localmodels/stack_clients.py +137 -21
  53. package/modules/localmodels/stack_doctor.py +6 -3
  54. package/modules/localmodels/stack_hardware.py +18 -0
  55. package/modules/localmodels/stack_lifecycle.py +3 -2
  56. package/modules/localmodels/stack_remove.py +2 -1
  57. package/modules/localmodels/stack_verify.py +2 -2
  58. package/modules/localmodels/stack_view_events.py +2 -2
  59. package/modules/localmodels/transport.py +1 -0
  60. package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/METADATA +1 -1
  61. package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/RECORD +63 -60
  62. package/package.json +1 -1
  63. package/tool.json +1 -1
  64. /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/WHEEL +0 -0
  65. /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/entry_points.txt +0 -0
  66. /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/NOTICE +0 -0
  67. /package/modules/{simplex_localmodels-0.1.0.dev61.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -8,51 +8,84 @@ artifacts, with ownership recorded for safe removal. The controller must be the
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
- import contextlib
12
11
  import hashlib
13
- import json
14
12
  import os
15
- import re
16
13
  import shutil
17
- import subprocess
14
+ import sys
18
15
  import tempfile
19
16
  from collections.abc import Callable
20
- from concurrent.futures import ThreadPoolExecutor, as_completed
21
17
  from pathlib import Path
22
- from typing import Any, Literal, TypedDict, cast
23
-
24
- from localmodels import harness_probe, hosts, region, runtime_discovery
25
- from localmodels.contracts import decode
26
- from localmodels.harness_cleanup import (
27
- changed as changed,
28
- )
29
- from localmodels.harness_cleanup import (
30
- digest as digest,
31
- )
32
- from localmodels.harness_cleanup import (
33
- keep_reason as keep_reason,
34
- )
35
- from localmodels.harness_cleanup import (
36
- remove_tools as remove_tools,
18
+ from typing import Any, cast
19
+
20
+ from localmodels import (
21
+ gateway_bifrost,
22
+ harness_core,
23
+ harness_gateway,
24
+ harness_probe,
25
+ hosts,
26
+ pi_profile,
27
+ runtime_discovery,
28
+ stack_clients,
37
29
  )
38
- from localmodels.harness_cleanup import (
39
- unit_users as unit_users,
40
- )
41
- from localmodels.harness_probe import (
42
- ClientConfig,
43
- ClientState,
44
- )
45
- from localmodels.harness_probe import client_environment as client_environment
46
- from localmodels.harness_probe import gateway_environment as gateway_environment
30
+ from localmodels.harness_cleanup import changed as changed
31
+ from localmodels.harness_cleanup import digest as digest
32
+ from localmodels.harness_cleanup import keep_reason as keep_reason
33
+ from localmodels.harness_cleanup import remove_tools as remove_tools
34
+ from localmodels.harness_cleanup import unit_users as unit_users
35
+ from localmodels.harness_core import BIFROST_ADDR as BIFROST_ADDR
36
+ from localmodels.harness_core import BIN_DIR as BIN_DIR
37
+ from localmodels.harness_core import DECISION_PROVIDER as DECISION_PROVIDER
38
+ from localmodels.harness_core import DEFAULT_GATEWAY as DEFAULT_GATEWAY
39
+ from localmodels.harness_core import DEFAULT_TOOLS_DIR as DEFAULT_TOOLS_DIR
40
+ from localmodels.harness_core import GATEWAY_ADDR as GATEWAY_ADDR
41
+ from localmodels.harness_core import GATEWAYS as GATEWAYS
42
+ from localmodels.harness_core import GROUP as GROUP
43
+ from localmodels.harness_core import HARD_INTENT as HARD_INTENT
44
+ from localmodels.harness_core import LLM_PROVIDER as LLM_PROVIDER
45
+ from localmodels.harness_core import OWNED_WRAPPER as OWNED_WRAPPER
46
+ from localmodels.harness_core import PI_DOWNLOADS as PI_DOWNLOADS
47
+ from localmodels.harness_core import TOOL_LOCK as TOOL_LOCK
48
+ from localmodels.harness_core import UNIT_DIR as UNIT_DIR
49
+ from localmodels.harness_core import Artifact as Artifact
50
+ from localmodels.harness_core import BifrostLock as BifrostLock
51
+ from localmodels.harness_core import ClientConfig as ClientConfig
52
+ from localmodels.harness_core import ClientState as ClientState
53
+ from localmodels.harness_core import Endpoint as Endpoint
54
+ from localmodels.harness_core import GatewayPlan as GatewayPlan
55
+ from localmodels.harness_core import HarnessError as HarnessError
56
+ from localmodels.harness_core import HarnessPlan as HarnessPlan
57
+ from localmodels.harness_core import MagpieLock as MagpieLock
58
+ from localmodels.harness_core import NodeLock as NodeLock
59
+ from localmodels.harness_core import NpmArtifact as NpmArtifact
60
+ from localmodels.harness_core import PiLock as PiLock
61
+ from localmodels.harness_core import PiModule as PiModule
62
+ from localmodels.harness_core import ToolAction as ToolAction
63
+ from localmodels.harness_core import ToolBuild as ToolBuild
64
+ from localmodels.harness_core import ToolLock as ToolLock
65
+ from localmodels.harness_core import ToolPlan as ToolPlan
66
+ from localmodels.harness_core import ToolState as ToolState
67
+ from localmodels.harness_core import archive_files as archive_files
68
+ from localmodels.harness_core import bifrost_addr as bifrost_addr
69
+ from localmodels.harness_core import download_artifact as download_artifact
70
+ from localmodels.harness_core import fetch_artifact as fetch_artifact
71
+ from localmodels.harness_core import fetch_many as fetch_many
72
+ from localmodels.harness_core import gateway_addr as gateway_addr
73
+ from localmodels.harness_core import gateway_environment as gateway_environment
74
+ from localmodels.harness_core import gateway_kind as gateway_kind
75
+ from localmodels.harness_core import load_lock as load_lock
76
+ from localmodels.harness_core import own_downloads as own_downloads
77
+ from localmodels.harness_core import reuse_tool as reuse_tool
78
+ from localmodels.harness_core import run_tool as run_tool
79
+ from localmodels.harness_core import search_path as search_path
80
+ from localmodels.harness_core import tool_artifact as tool_artifact
81
+ from localmodels.harness_core import tool_build as tool_build
82
+ from localmodels.harness_core import tool_path as tool_path
83
+ from localmodels.harness_core import version_tuple as _version_tuple
84
+ from localmodels.harness_gateway import checked_gateway_environment as checked_gateway_environment
47
85
  from localmodels.harness_probe import listener_uids as listener_uids
48
86
  from localmodels.harness_probe import shown_pi_model as shown_pi_model
49
- from localmodels.npm_transport import Artifact as Artifact
50
- from localmodels.npm_transport import ToolBuild as ToolBuild
51
- from localmodels.remote_ops import Archive, fetch
52
- from localmodels.remote_ops_download import npm_copies
53
- from localmodels.runtime_io import Event, error_cause, fetch_bifrost, rename_with_retry
54
- from localmodels.stack_events import CombinedEvents as _CombinedEvents
55
- from localmodels.stack_events import ToolEvents
87
+ from localmodels.pi_profile import client_environment as client_environment
88
+ from localmodels.runtime_io import error_cause, rename_with_retry
56
89
  from localmodels.tool_archive import (
57
90
  ArchiveError,
58
91
  launcher_name,
@@ -61,256 +94,6 @@ from localmodels.tool_archive import (
61
94
  write_launcher,
62
95
  )
63
96
 
64
- _Events = ToolEvents
65
-
66
- TOOL_LOCK = Path(__file__).with_name("tools.json")
67
- DEFAULT_TOOLS_DIR = hosts.TOOLS_DIR
68
- BIN_DIR = "~/.local/bin"
69
- UNIT_DIR = "~/.config/systemd/user"
70
- GATEWAY_ADDR = "127.0.0.1:3425" # Magpie's default; MAGPIE_ADDR overrides it
71
- BIFROST_ADDR = "127.0.0.1:18480" # this tool's Bifrost; LOCALMODELS_BIFROST_ADDR overrides it
72
- GATEWAYS = ("bifrost", "magpie")
73
- DEFAULT_GATEWAY = "bifrost"
74
- LLM_PROVIDER = "localmodels-llm"
75
- DECISION_PROVIDER = "localmodels-jev"
76
- GROUP = "localmodels-agent"
77
- # The rule Magpie asks the decision model about at the start of every new turn.
78
- HARD_INTENT = "a hard multi-step coding, debugging or design task"
79
- OWNED_WRAPPER = "# localmodels: pi wrapper"
80
-
81
-
82
- class HarnessError(RuntimeError):
83
- """A tool could not be planned, installed or wired; the message says why."""
84
-
85
- def __init__(self, message: str, *, code: str | None = None) -> None:
86
- super().__init__(message)
87
- self.code = code
88
-
89
-
90
- class NodeLock(TypedDict):
91
- version: str
92
- min_version: str
93
- builds: list[ToolBuild]
94
-
95
-
96
- class NpmArtifact(TypedDict):
97
- package: str
98
- version: str
99
- license: str
100
- name: str
101
- url: str
102
- sha256: str
103
- size_bytes: int
104
- integrity: str
105
-
106
-
107
- class _PiModuleOptional(NpmArtifact, total=False):
108
- install_script: str # "skipped": npm would run one; scripts/pin_pi.py says why it is not
109
-
110
-
111
- class PiModule(_PiModuleOptional):
112
- path: (
113
- str # its place under the package root, npm's lockfile key: node_modules/a[/node_modules/b]
114
- )
115
-
116
-
117
- class PiLock(NpmArtifact):
118
- """pi and its whole production dependency tree, written by scripts/pin_pi.py."""
119
-
120
- entry: str
121
- modules: list[PiModule]
122
- longest_path: int # characters of the deepest file below the package root
123
-
124
-
125
- class MagpieLock(TypedDict):
126
- version: str
127
- builds: list[ToolBuild]
128
-
129
-
130
- class BifrostLock(TypedDict):
131
- version: str
132
- source: str
133
- license: str
134
- note: str
135
- builds: list[ToolBuild]
136
-
137
-
138
- class _ToolLockSince20261102(TypedDict, total=False):
139
- bifrost: BifrostLock
140
-
141
-
142
- class ToolLock(_ToolLockSince20261102):
143
- schema: str
144
- node: NodeLock
145
- pi: PiLock
146
- magpie: MagpieLock
147
-
148
-
149
- class _ToolStateSince20261026(TypedDict, total=False):
150
- gateway_other_user: bool # another user's program listens at gateway_addr
151
- clients: dict[str, ClientState]
152
- tools_dir: str
153
- bifrost_addr: str # where this tool's Bifrost listens (since 2026-11-02)
154
- bifrost_listeners: list[int] # uids of the programs listening at bifrost_addr
155
-
156
-
157
- class ToolState(_ToolStateSince20261026):
158
- """What this computer has now; read-only."""
159
-
160
- inspection: Literal["complete", "unknown"]
161
- node: str | None
162
- node_version: str | None
163
- pi: str | None
164
- pi_version: str | None
165
- magpie: str | None
166
- magpie_version: str | None
167
- gateway_addr: str
168
- gateway_up: bool
169
- pi_model: str | None
170
- bin_on_path: bool
171
-
172
-
173
- class ToolAction(TypedDict):
174
- tool: str # node | pi | magpie | bifrost | gateway
175
- action: str # reuse | install | skip | daemon | serve | unit (Bifrost's systemd --user unit)
176
- path: str
177
- version: str | None
178
- artifacts: list[Artifact]
179
-
180
-
181
- class Endpoint(TypedDict):
182
- url: str
183
- model: str
184
-
185
-
186
- class _GatewayOptional(TypedDict, total=False):
187
- efforts: list[str] # reasoning_effort levels the template accepts, low to high; none: all
188
- caller_key: str # name of the gateway key gateway_keys.CALLER_KEY goes by; older plans add none
189
- clients: dict[str, ClientConfig]
190
- # Since 2026-11-02: which gateway carries the stack. Absent: Magpie, as every plan before.
191
- kind: str # one of GATEWAYS
192
- llm_fast: Endpoint # optional fastest provider, only on a two-LLM Bifrost plan
193
- llm_fast_key_file: str # private deployment credential, never its content
194
- llm_key_file: str # direct readiness credential path, only present on two-LLM plans
195
- context: int # the LLM's context window per request, for the clients' model entries
196
- vision: bool # True when the served LLM reads images (vision.reads_pictures), for clients
197
-
198
-
199
- class GatewayPlan(_GatewayOptional):
200
- addr: str
201
- group: str
202
- llm_provider: str
203
- decision_provider: str
204
- llm: Endpoint
205
- decision: Endpoint | None
206
- intent: str
207
- pi_model_before: str | None
208
- pi_model: str
209
-
210
-
211
- class _NativeTools(TypedDict, total=False):
212
- native: dict[str, dict[str, Any]]
213
- environment: dict[str, str]
214
-
215
-
216
- class ToolPlan(_NativeTools):
217
- """Node.js, pi, the gateway program and the gateway: what installing the tools needs,
218
- without models."""
219
-
220
- tools_dir: str
221
- tools: list[ToolAction]
222
- download_bytes: int
223
- warnings: list[str]
224
-
225
-
226
- class HarnessPlan(ToolPlan):
227
- gateway: GatewayPlan
228
-
229
-
230
- def load_lock() -> ToolLock:
231
- return decode(json.loads(TOOL_LOCK.read_text(encoding="utf-8")), ToolLock)
232
-
233
-
234
- def _version_tuple(text: str | None) -> tuple[int, ...]:
235
- return tuple(int(x) for x in re.findall(r"\d+", text or "")[:3]) or (0,)
236
-
237
-
238
- def run_tool(
239
- argv: list[str],
240
- *,
241
- timeout: float = 60,
242
- cwd: str | None = None,
243
- env: dict[str, str] | None = None,
244
- stdin_text: str | None = None,
245
- ) -> subprocess.CompletedProcess[str]:
246
- try:
247
- return subprocess.run(
248
- argv,
249
- capture_output=True,
250
- text=True,
251
- encoding="utf-8",
252
- errors="replace",
253
- timeout=timeout,
254
- check=False,
255
- input=stdin_text,
256
- stdin=subprocess.DEVNULL if stdin_text is None else None,
257
- cwd=cwd,
258
- env=env,
259
- )
260
- except (OSError, subprocess.TimeoutExpired) as exc:
261
- return subprocess.CompletedProcess(argv, 127, "", f"{type(exc).__name__}")
262
-
263
-
264
- def gateway_addr(env: dict[str, str] | None = None) -> str:
265
- return (env if env is not None else os.environ).get("MAGPIE_ADDR") or GATEWAY_ADDR
266
-
267
-
268
- def checked_gateway_environment(plan: ToolPlan) -> dict[str, str]:
269
- """Prove the target before any command can send data to it."""
270
- from localmodels import harness_gateway
271
-
272
- harness_gateway.require_target(plan)
273
- return gateway_environment(plan)
274
-
275
-
276
- def bifrost_addr(env: dict[str, str] | None = None) -> str:
277
- return (env if env is not None else os.environ).get("LOCALMODELS_BIFROST_ADDR") or BIFROST_ADDR
278
-
279
-
280
- def gateway_kind(gw: GatewayPlan | dict[str, Any] | None) -> str:
281
- """The gateway a stack plan's ``harness.gateway`` names; a plan without one used Magpie."""
282
- return str((gw or {}).get("kind") or "magpie")
283
-
284
-
285
- def search_path(env: dict[str, str]) -> str:
286
- """PATH plus ~/.local/bin, where installers put commands and non-login shells miss it."""
287
- home = env.get("HOME") or os.path.expanduser("~")
288
- return os.pathsep.join([env.get("PATH", ""), os.path.join(home, BIN_DIR.removeprefix("~/"))])
289
-
290
-
291
- def tool_build(builds: list[ToolBuild], platform: str, arch: str, tool: str) -> ToolBuild:
292
- names = {platform, "windows"} if platform == "win32" else {platform} # the lock: windows
293
- match = next((b for b in builds if b["platform"] in names and b["arch"] == arch), None)
294
- if match is None:
295
- raise HarnessError(f"{tool} has no pinned version for {platform}/{arch}")
296
- return match
297
-
298
-
299
- def tool_artifact(item: ToolBuild | NpmArtifact | PiModule) -> Artifact:
300
- artifact: Artifact = {
301
- "name": item["name"],
302
- "url": item["url"],
303
- "sha256": item["sha256"],
304
- "size_bytes": item["size_bytes"],
305
- }
306
- if "npm" in item:
307
- artifact["npm"] = cast(ToolBuild, item)["npm"]
308
- if "npm_copy" in item:
309
- artifact["npm_copy"] = cast(ToolBuild, item)["npm_copy"]
310
- if "path" in item:
311
- artifact["path"] = cast(PiModule, item)["path"]
312
- return artifact
313
-
314
97
 
315
98
  def plan_tools(
316
99
  state: ToolState,
@@ -374,15 +157,11 @@ def plan_tools(
374
157
  f"{bin_dir} is not on PATH; add it to PATH in a new terminal to run pi directly"
375
158
  )
376
159
  if gateway == "bifrost":
377
- from localmodels import gateway_bifrost
378
-
379
160
  bifrost_actions, gateway_warnings = gateway_bifrost.plan_tools(
380
161
  state, platform, arch, systemd_user, tools_dir, lock
381
162
  )
382
163
  actions += bifrost_actions
383
164
  else:
384
- from localmodels import harness_gateway
385
-
386
165
  gateway_plan, gateway_warnings = harness_gateway.plan_gateway(
387
166
  state, platform, arch, systemd_user, tools_dir, lock
388
167
  )
@@ -418,10 +197,8 @@ def plan_harness(
418
197
  tools = plan_tools(state, platform, arch, systemd_user, tools_dir, lock, gateway_kind)
419
198
  native: dict[str, dict[str, Any]] = {}
420
199
  if clients:
421
- from localmodels import stack_clients
422
-
423
200
  if not state.get("clients"):
424
- env = {**os.environ, **client_environment(tools["tools_dir"])}
201
+ env = {**os.environ, **pi_profile.client_environment(tools["tools_dir"])}
425
202
  state = {
426
203
  **state,
427
204
  "clients": {
@@ -460,8 +237,6 @@ def plan_harness(
460
237
  "efforts": list(efforts),
461
238
  }
462
239
  if clients:
463
- from localmodels import stack_clients
464
-
465
240
  gateway["clients"] = {
466
241
  name: {"model": seen["model"], "files": seen["files"]}
467
242
  for name, seen in stack_clients.planned_clients(state).items()
@@ -475,8 +250,6 @@ def plan_harness(
475
250
  )
476
251
  plan = cast(HarnessPlan, {**tools, "gateway": gateway})
477
252
  if gateway_kind == "bifrost":
478
- from localmodels import gateway_bifrost
479
-
480
253
  gateway_bifrost.adopt(plan, state, decision is not None, context, vision=vision)
481
254
  return plan
482
255
 
@@ -488,18 +261,6 @@ def _safe_extract(archive: Path, dest: Path) -> None:
488
261
  raise HarnessError(str(exc)) from exc
489
262
 
490
263
 
491
- def reuse_tool(
492
- tool: str, path: str | None, version: str | None, *, needed: bool = True
493
- ) -> ToolAction:
494
- return {
495
- "tool": tool,
496
- "action": "reuse" if needed else "skip",
497
- "path": path or "",
498
- "version": version,
499
- "artifacts": [],
500
- }
501
-
502
-
503
264
  def _owned_wrapper(path: str) -> bool:
504
265
  try:
505
266
  return OWNED_WRAPPER in Path(path).expanduser().read_text(encoding="utf-8")[:400]
@@ -507,92 +268,9 @@ def _owned_wrapper(path: str) -> bool:
507
268
  return False
508
269
 
509
270
 
510
- def tool_path(plan: ToolPlan, tool: str) -> str:
511
- return os.path.expanduser(next(t["path"] for t in plan["tools"] if t["tool"] == tool))
512
-
513
-
514
271
  # ---------------------------------------------------------------------------- installation
515
272
 
516
273
 
517
- def archive_files(tools_dir: Path, artifact: Artifact) -> list[str]:
518
- """The files ``_fetch`` may leave in ``.archives`` for ``artifact``: the archive, fetch's
519
- verification marker and, for an npm build, its lock and the tarball with its partial
520
- download (gone after a successful fetch). The owned manifest lists them for ``--purge``."""
521
- path = str(tools_dir / ".archives" / artifact["name"])
522
- suffixes = ("", ".sha256", *((".lock", ".tgz", ".tgz.part") if "npm" in artifact else ()))
523
- return [path + suffix for suffix in suffixes]
524
-
525
-
526
- def own_downloads(tools_dir: Path, artifacts: list[Artifact]) -> None:
527
- """List ``artifacts``' archive files in the owned manifest before fetching them, so
528
- ``--purge`` also finds the partial download of an install that failed or was killed."""
529
- files = {f for a in artifacts for f in archive_files(tools_dir, a)}
530
- hosts.update_owned(
531
- lambda doc: doc.__setitem__("archives", sorted(set(doc["archives"]) | files)), tools_dir
532
- )
533
-
534
-
535
- def _fetch(
536
- tools_dir: Path,
537
- artifact: Artifact,
538
- log: Callable[[str], None],
539
- event: Event = lambda _: None,
540
- ) -> Path:
541
- path = tools_dir / ".archives" / artifact["name"]
542
- if "npm" in artifact:
543
- path.parent.mkdir(parents=True, exist_ok=True)
544
- # stack apply and source apply may fetch it at once: one writes the tarball, the other
545
- # waits and then reuses the binary it published.
546
- with hosts.file_lock(path.with_name(path.name + ".lock")):
547
- if not path.is_file() or digest(str(path)) != artifact["sha256"]:
548
- with tempfile.TemporaryDirectory(dir=path.parent) as temporary:
549
- staged = Path(temporary) / "bifrost-http"
550
- fetch_bifrost(artifact, staged, path.with_name(path.name + ".tgz"), event)
551
- staged.replace(path)
552
- return path
553
- with contextlib.redirect_stdout(_Events(log)):
554
- _download(path, artifact)
555
- return path
556
-
557
-
558
- def _download(path: Path, artifact: Artifact) -> None:
559
- fetch(
560
- artifact["url"],
561
- str(path),
562
- artifact["sha256"],
563
- artifact["size_bytes"],
564
- artifact["name"],
565
- npm_copies(cast(Archive, artifact)),
566
- region.current_region(),
567
- )
568
-
569
-
570
- PI_DOWNLOADS = 8 # pi's tree is ~120 small tarballs; one at a time takes minutes
571
-
572
-
573
- def _fetch_many(
574
- tools_dir: Path, artifacts: list[Artifact], log: Callable[[str], None]
575
- ) -> list[Path]:
576
- """Download ``artifacts`` eight at a time, reported as one download of their total bytes;
577
- the first failure cancels the ones still queued. A tarball two of them share downloads
578
- once."""
579
- unique = {a["name"]: a for a in artifacts}
580
- events = _CombinedEvents(log, {name: a["size_bytes"] for name, a in unique.items()})
581
- pool = ThreadPoolExecutor(PI_DOWNLOADS)
582
- try:
583
- with contextlib.redirect_stdout(events):
584
- futures = {
585
- pool.submit(_download, tools_dir / ".archives" / name, a): name
586
- for name, a in unique.items()
587
- }
588
- for future in as_completed(futures):
589
- future.result()
590
- events.finished(futures[future])
591
- finally:
592
- pool.shutdown(wait=True, cancel_futures=True)
593
- return [tools_dir / ".archives" / a["name"] for a in artifacts]
594
-
595
-
596
274
  def _install_tree(tools_dir: Path, name: str, unpack: Callable[[Path], None], marker: str) -> Path:
597
275
  """Unpack into tools_dir/name once; a matching .complete marker means it is already there."""
598
276
  final = tools_dir / name
@@ -625,7 +303,7 @@ def _install_pi(
625
303
  modules = action["artifacts"][1:]
626
304
  if any("path" not in m for m in modules): # plans saved before 2026-11-18
627
305
  raise HarnessError("this plan installs pi without its dependency tree; plan again")
628
- archives = _fetch_many(tools_dir, action["artifacts"], log)
306
+ archives = harness_core.fetch_many(tools_dir, action["artifacts"], log)
629
307
 
630
308
  def unpack_pi(dest: Path) -> None:
631
309
  _safe_extract(archives[0], dest)
@@ -659,7 +337,7 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
659
337
  actions = {t["tool"]: t for t in plan["tools"]}
660
338
  node = os.path.expanduser(actions["node"]["path"])
661
339
  if actions["node"]["action"] == "install":
662
- archive = _fetch(tools_dir, actions["node"]["artifacts"][0], log)
340
+ archive = harness_core.fetch_artifact(tools_dir, actions["node"]["artifacts"][0], log)
663
341
  tree = _install_tree(
664
342
  tools_dir,
665
343
  f"node-v{lock['node']['version']}",
@@ -672,8 +350,6 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
672
350
  if actions["pi"]["action"] == "install":
673
351
  owned += _install_pi(tools_dir, bin_dir, actions["pi"], lock["pi"], node, log)
674
352
  if "bifrost" in actions and actions["bifrost"]["action"] == "install":
675
- from localmodels import gateway_bifrost
676
-
677
353
  own_downloads(tools_dir, actions["bifrost"]["artifacts"])
678
354
  if made := gateway_bifrost.install_binary(tools_dir, actions["bifrost"], log):
679
355
  owned.append(made)
@@ -687,7 +363,7 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
687
363
  elif target.exists():
688
364
  raise HarnessError(f"{target} exists; not overwritten")
689
365
  else:
690
- archive = _fetch(tools_dir, artifact, log)
366
+ archive = harness_core.fetch_artifact(tools_dir, artifact, log)
691
367
  bin_dir.mkdir(parents=True, exist_ok=True)
692
368
  shutil.copyfile(archive, target)
693
369
  target.chmod(0o755)
@@ -710,8 +386,6 @@ def install_tools(plan: ToolPlan, log: Callable[[str], None] = lambda message: N
710
386
 
711
387
  hosts.update_owned(add, tools_dir)
712
388
  if plan.get("native"):
713
- from localmodels import stack_clients
714
-
715
389
  try:
716
390
  owned += stack_clients.install_tools(plan, log)
717
391
  except ValueError as exc:
@@ -730,6 +404,116 @@ def inspect(
730
404
  approved: ToolPlan | None = None,
731
405
  private_clients: bool = False,
732
406
  ) -> ToolState:
733
- return harness_probe.inspect(
734
- env, tools_dir=tools_dir, approved=approved, private_clients=private_clients
407
+ """Read-only facts about the tools on this computer, found on ``harness_core.search_path``."""
408
+ if not (sys.platform.startswith("linux") or sys.platform in ("darwin", "win32")):
409
+ raise HarnessError(
410
+ "the local stack tool check supports Linux, macOS and Windows; cannot confirm"
411
+ " gateway ownership on this platform."
412
+ )
413
+ env = dict(os.environ if env is None else env)
414
+ tools_dir = os.path.expanduser(
415
+ hosts.tools_dir(approved["tools_dir"] if approved else tools_dir, env=env)
416
+ )
417
+ path = env.get("PATH", "")
418
+ home = env.get("HOME") or os.path.expanduser("~")
419
+ bin_dir = os.path.join(home, BIN_DIR.removeprefix("~/"))
420
+ search = search_path(env)
421
+ node, pi, magpie = (shutil.which(name, path=search) for name in ("node", "pi", "magpie"))
422
+ magpie = harness_probe.windows_program(magpie)
423
+ bifrost = bool(approved and gateway_kind(approved.get("gateway")) == "bifrost")
424
+ bifrost_address = (
425
+ str(approved["gateway"]["addr"]) if bifrost and approved else bifrost_addr(env)
426
+ )
427
+ requested = (
428
+ next(t["path"] for t in approved["tools"] if t["tool"] == "gateway")
429
+ if approved and not bifrost
430
+ else env.get("MAGPIE_ADDR") or None
431
+ )
432
+ addr = (
433
+ GATEWAY_ADDR
434
+ if bifrost
435
+ else harness_gateway.select_address(
436
+ requested,
437
+ tools_dir,
438
+ owned=lambda candidate: harness_gateway.owned_address(candidate, tools_dir, magpie),
439
+ )
440
+ )
441
+ context: ToolPlan = {
442
+ "tools_dir": tools_dir,
443
+ "tools": [
444
+ {"tool": "gateway", "action": "serve", "path": addr, "version": None, "artifacts": []}
445
+ ],
446
+ "download_bytes": 0,
447
+ "warnings": [],
448
+ }
449
+ gateway_env = harness_core.gateway_environment(approved or context, base=env)
450
+ if private_clients:
451
+ gateway_env.update(pi_profile.client_environment(tools_dir))
452
+ node_version = (
453
+ harness_probe.first_line(harness_core.run_tool([node, "--version"], timeout=10, env=env))
454
+ if node
455
+ else None
735
456
  )
457
+ pi_version = (
458
+ harness_probe.first_line(harness_core.run_tool([pi, "--version"], timeout=30, env=env))
459
+ if pi
460
+ else None
461
+ )
462
+ if pi and pi_version and not runtime_discovery.pi_loads_extensions([pi], env):
463
+ # localmodels before 0.1.0.dev39 installed pi without jiti, so it cannot load the
464
+ # extension Linger starts it with: plan_tools installs the pinned tree over an owned one.
465
+ pi_version = None
466
+ magpie_version = pi_model = None
467
+ gateway_up = False
468
+ if magpie and not bifrost:
469
+ version = harness_probe.first_line(
470
+ harness_core.run_tool([magpie, "--version"], timeout=20, env=env)
471
+ )
472
+ magpie_version = version.split()[-1] if version else None
473
+ if harness_gateway.owned_address(addr, tools_dir, magpie):
474
+ gateway_up = (
475
+ harness_core.run_tool(
476
+ [magpie, "healthcheck"], timeout=20, env=gateway_env
477
+ ).returncode
478
+ == 0
479
+ )
480
+ if not private_clients:
481
+ pi_model = shown_pi_model(
482
+ harness_core.run_tool([magpie, "pi"], timeout=20, env=gateway_env).stdout
483
+ )
484
+ clients = (
485
+ stack_clients.inspect(search, env, None)
486
+ if private_clients
487
+ else stack_clients.inspect(
488
+ search, gateway_env if gateway_up else env, magpie if gateway_up else None
489
+ )
490
+ )
491
+ if private_clients:
492
+ pi_model = harness_probe.pi_settings_model(str(pi_profile.gateway_home(tools_dir)))
493
+ for client, seen in clients.items():
494
+ seen["files"] = stack_clients.config_files(client, gateway_env)
495
+ if gateway_up and magpie and next(iter(seen["files"].values()), None) is not None:
496
+ out = harness_core.run_tool([magpie, client], timeout=20, env=gateway_env)
497
+ seen["model"] = (
498
+ stack_clients.shown_model(client, out.stdout) if out.returncode == 0 else None
499
+ )
500
+ return {
501
+ "inspection": "complete",
502
+ "gateway_other_user": False,
503
+ "tools_dir": tools_dir,
504
+ "bifrost_addr": bifrost_address,
505
+ "bifrost_listeners": sorted(harness_probe.listener_uids(bifrost_address)),
506
+ "node": node,
507
+ "node_version": node_version,
508
+ "pi": pi if pi_version else None,
509
+ "pi_version": pi_version,
510
+ "magpie": magpie if magpie_version else None,
511
+ "magpie_version": magpie_version,
512
+ "gateway_addr": addr,
513
+ "gateway_up": gateway_up,
514
+ "pi_model": pi_model
515
+ if private_clients
516
+ else pi_model or harness_probe.pi_settings_model(home),
517
+ "bin_on_path": bin_dir in path.split(os.pathsep),
518
+ "clients": clients,
519
+ }