@simplexai/localmodels-linux-arm64 0.1.0-dev.64 → 0.1.0-dev.66

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 (127) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +125 -121
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +2 -2
  5. package/modules/localmodels/approval.py +5 -3
  6. package/modules/localmodels/auth_proxy.py +34 -2
  7. package/modules/localmodels/bifrost_checks.py +2 -1
  8. package/modules/localmodels/catalog.json +504 -18
  9. package/modules/localmodels/catalog.py +2 -1
  10. package/modules/localmodels/catalog_recipes.py +3 -0
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/context_policy.py +1 -1
  13. package/modules/localmodels/custom_hub.py +54 -6
  14. package/modules/localmodels/custom_probe.py +33 -5
  15. package/modules/localmodels/debug_stub_server.py +34 -1
  16. package/modules/localmodels/deploy.py +45 -285
  17. package/modules/localmodels/deployment_lifecycle.py +167 -0
  18. package/modules/localmodels/download-mirrors.json +43 -3
  19. package/modules/localmodels/draft_spec.py +43 -1
  20. package/modules/localmodels/engine_adapters/__init__.py +4 -2
  21. package/modules/localmodels/engine_adapters/auxiliary.py +4 -1
  22. package/modules/localmodels/engine_adapters/llama_cpp.py +539 -0
  23. package/modules/localmodels/engines-b11583.json +9 -5
  24. package/modules/localmodels/engines-b12757-mix-ef2df21.json +85 -1
  25. package/modules/localmodels/engines.json +9 -5
  26. package/modules/localmodels/gateway.py +124 -13
  27. package/modules/localmodels/gateway_accept.py +1 -6
  28. package/modules/localmodels/gateway_cli.py +13 -24
  29. package/modules/localmodels/gateway_ops.py +185 -0
  30. package/modules/localmodels/gateway_server.py +3 -2
  31. package/modules/localmodels/harness.py +13 -16
  32. package/modules/localmodels/harness_core.py +4 -9
  33. package/modules/localmodels/harness_gateway.py +18 -6
  34. package/modules/localmodels/harness_probe.py +64 -3
  35. package/modules/localmodels/hosts.py +22 -34
  36. package/modules/localmodels/library_convert.py +3 -3
  37. package/modules/localmodels/library_custom.py +15 -13
  38. package/modules/localmodels/library_elastic.py +27 -13
  39. package/modules/localmodels/library_jobs.py +151 -28
  40. package/modules/localmodels/library_model.py +22 -2
  41. package/modules/localmodels/library_order.py +5 -4
  42. package/modules/localmodels/library_poly.py +2 -2
  43. package/modules/localmodels/library_pricing.py +34 -318
  44. package/modules/localmodels/library_serve.py +20 -12
  45. package/modules/localmodels/library_smoke.py +8 -1
  46. package/modules/localmodels/library_state.py +12 -0
  47. package/modules/localmodels/library_status.py +26 -16
  48. package/modules/localmodels/llm_rank.py +1 -1
  49. package/modules/localmodels/magpie_legacy.py +160 -0
  50. package/modules/localmodels/magpie_setup.py +6 -1
  51. package/modules/localmodels/pi_profile.py +3 -7
  52. package/modules/localmodels/plan_envelope.py +1 -1
  53. package/modules/localmodels/{budget.py → planning/budget.py} +56 -33
  54. package/modules/localmodels/{stack_llm_ram.py → planning/llm_ram.py} +11 -1
  55. package/modules/localmodels/planning/memory_pools.py +403 -0
  56. package/modules/localmodels/recommend.py +1 -1
  57. package/modules/localmodels/recommend_cli.py +3 -4
  58. package/modules/localmodels/remote_ops_mirrors.py +55 -19
  59. package/modules/localmodels/residency_host.py +1 -1
  60. package/modules/localmodels/service_control.py +4 -4
  61. package/modules/localmodels/service_deployment.py +4 -4
  62. package/modules/localmodels/service_wiring.py +17 -19
  63. package/modules/localmodels/setup_inspection.py +29 -2
  64. package/modules/localmodels/setup_inspection_harness.py +5 -2
  65. package/modules/localmodels/setup_text.py +6 -0
  66. package/modules/localmodels/setup_upgrade.py +3 -12
  67. package/modules/localmodels/slot_cache.py +1 -3
  68. package/modules/localmodels/speech_admission.py +17 -5
  69. package/modules/localmodels/speech_catalog.py +5 -1
  70. package/modules/localmodels/speech_cli.py +5 -5
  71. package/modules/localmodels/speech_jobs.py +103 -20
  72. package/modules/localmodels/speech_model.py +2 -0
  73. package/modules/localmodels/speech_server.py +132 -9
  74. package/modules/localmodels/speech_state.py +11 -0
  75. package/modules/localmodels/speech_worker_sensevoice.py +215 -19
  76. package/modules/localmodels/speech_workers.py +79 -7
  77. package/modules/localmodels/stack.py +15 -6
  78. package/modules/localmodels/stack_auto.py +10 -4
  79. package/modules/localmodels/stack_aux_gpu.py +1 -1
  80. package/modules/localmodels/stack_binding.py +24 -143
  81. package/modules/localmodels/stack_capacity.py +4 -4
  82. package/modules/localmodels/stack_card.py +1 -1
  83. package/modules/localmodels/stack_cleanup.py +3 -3
  84. package/modules/localmodels/stack_cli.py +3 -0
  85. package/modules/localmodels/stack_client_settings.py +9 -2
  86. package/modules/localmodels/stack_compose.py +42 -9
  87. package/modules/localmodels/stack_console.py +2 -2
  88. package/modules/localmodels/stack_debug.py +1 -1
  89. package/modules/localmodels/stack_decision.py +1 -1
  90. package/modules/localmodels/stack_doctor.py +10 -7
  91. package/modules/localmodels/stack_down.py +3 -3
  92. package/modules/localmodels/stack_gpu_memory.py +1 -1
  93. package/modules/localmodels/stack_hardware.py +3 -3
  94. package/modules/localmodels/stack_hardware_text.py +1 -1
  95. package/modules/localmodels/stack_lifecycle.py +7 -7
  96. package/modules/localmodels/stack_memory.py +1 -1
  97. package/modules/localmodels/stack_mlx.py +1 -1
  98. package/modules/localmodels/stack_plan.py +18 -13
  99. package/modules/localmodels/stack_ports.py +60 -29
  100. package/modules/localmodels/stack_preflight.py +4 -3
  101. package/modules/localmodels/stack_remove.py +13 -6
  102. package/modules/localmodels/stack_review.py +3 -5
  103. package/modules/localmodels/stack_rollback.py +1 -1
  104. package/modules/localmodels/stack_route.py +5 -4
  105. package/modules/localmodels/stack_suite.py +17 -4
  106. package/modules/localmodels/stack_summary.py +1 -1
  107. package/modules/localmodels/stack_try.py +8 -13
  108. package/modules/localmodels/stack_up.py +10 -9
  109. package/modules/localmodels/stack_update.py +2 -1
  110. package/modules/localmodels/stack_verify.py +4 -30
  111. package/modules/localmodels/stack_view.py +6 -4
  112. package/modules/localmodels/stack_view_apply.py +2 -2
  113. package/modules/localmodels/stack_view_text.py +2 -6
  114. package/modules/localmodels/stack_view_tick.py +2 -2
  115. package/modules/localmodels/stack_view_words.py +5 -2
  116. package/modules/localmodels/stack_warm.py +1 -1
  117. package/modules/localmodels/suite.py +1 -1
  118. package/modules/localmodels/tui_views.py +11 -5
  119. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/METADATA +1 -1
  120. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/RECORD +122 -118
  121. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/NOTICE +3 -0
  122. package/package.json +1 -1
  123. package/tool.json +1 -1
  124. package/modules/localmodels/library_vram.py +0 -123
  125. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/WHEEL +0 -0
  126. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/entry_points.txt +0 -0
  127. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,185 @@
1
+ """What each gateway does for a stack once it is installed: the implementation side of
2
+ ``magpie_legacy``'s adapter.
3
+
4
+ ``of`` is the one place that picks Bifrost's or legacy Magpie's code for a plan's gateway
5
+ (architecture_gateway_kind counts it); callers in the stack layer (``stack_binding``) ask
6
+ the operations here and never which gateway a plan names. Removing Magpie
7
+ removes ``MagpieOps``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from collections.abc import Mapping
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from localmodels import (
18
+ bifrost_pi,
19
+ gateway_bifrost,
20
+ harness,
21
+ harness_core,
22
+ hosts,
23
+ magpie_legacy,
24
+ )
25
+
26
+ # A refusal: the setup_text reason code, and the detail key that names its cause (or None).
27
+ Refusal = tuple[str, str | None]
28
+
29
+
30
+ def same_path(left: str | Path, right: str | Path) -> bool:
31
+ return os.path.normcase(os.path.normpath(os.path.expanduser(str(left)))) == os.path.normcase(
32
+ os.path.normpath(os.path.expanduser(str(right)))
33
+ )
34
+
35
+
36
+ def same_real_path(left: str | Path, right: str | Path) -> bool:
37
+ return os.path.normcase(os.path.realpath(left)) == os.path.normcase(os.path.realpath(right))
38
+
39
+
40
+ def with_path(env: dict[str, str], prefixes: list[str]) -> dict[str, str]:
41
+ """``env`` with ``prefixes`` ahead of this process's PATH."""
42
+ merged = {key: value for key, value in env.items() if key.upper() != "PATH"}
43
+ merged["PATH"] = os.pathsep.join([*prefixes, os.environ.get("PATH", "")])
44
+ return merged
45
+
46
+
47
+ class BifrostOps:
48
+ """This tool's Bifrost: the instance its manifest records (``gateway.bifrost``)."""
49
+
50
+ def pi_profile(self, plan: harness.HarnessPlan) -> Path:
51
+ """The pi profile the stack's own binding reads."""
52
+ return bifrost_pi.pi_profile(harness_core.gateway_environment(plan))
53
+
54
+ def pi_owner(self, plan: harness.HarnessPlan, owned: hosts.Owned) -> Refusal | None:
55
+ """Why the plan's gateway and pi are not the ones this tool installed, or None."""
56
+ gateway = plan["gateway"]
57
+ record = owned["gateway"].get("bifrost")
58
+ if (
59
+ not record
60
+ or record["addr"] != gateway["addr"]
61
+ # an instance still on an earlier pinned binary is not the approved plan until
62
+ # apply restarts it
63
+ or not same_path(record["binary"], harness.tool_path(plan, "bifrost"))
64
+ or not owned["pi"]
65
+ or owned["pi"]["model"] != gateway["pi_model"]
66
+ ):
67
+ return ("gateway-ownership", None)
68
+ try:
69
+ if gateway_bifrost.require_target(plan) != record:
70
+ raise harness.HarnessError("Bifrost record changed")
71
+ except harness.HarnessError:
72
+ return ("gateway-ownership", "gateway-record")
73
+ return None
74
+
75
+ def pi_env(
76
+ self, plan: harness.HarnessPlan, owned: hosts.Owned, executable: Path, profile: Path
77
+ ) -> dict[str, str] | None:
78
+ """The environment pi lists its models in, once the gateway answers and pi selects the
79
+ plan's model; None when either is not so."""
80
+ record = owned["gateway"].get("bifrost")
81
+ if (
82
+ not record
83
+ or not gateway_bifrost.owned_listener(record)
84
+ or not gateway_bifrost.healthy(plan["gateway"]["addr"])
85
+ or bifrost_pi.pi_model(profile) != (plan["gateway"]["pi_model"])
86
+ ):
87
+ return None
88
+ return {**harness_core.gateway_environment(plan), "PI_CODING_AGENT_DIR": str(profile)}
89
+
90
+ def pi_on_previous(self, profile: Path) -> bool:
91
+ """pi still selects this gateway's earlier model, which a library binding must check."""
92
+ return False
93
+
94
+ def library_refusal(
95
+ self, plan: harness.HarnessPlan, owned: hosts.Owned, unadopted: bool
96
+ ) -> str | None:
97
+ """Why a library binding cannot route through the plan's gateway, or None."""
98
+ gateway = plan["gateway"]
99
+ record = owned["gateway"].get("bifrost")
100
+ if not record or record["addr"] != gateway["addr"]:
101
+ return "gateway-ownership"
102
+ if not gateway_bifrost.owned_listener(record) or not gateway_bifrost.healthy(
103
+ gateway["addr"]
104
+ ):
105
+ return "gateway-unavailable"
106
+ return None
107
+
108
+
109
+ class MagpieOps(BifrostOps):
110
+ """Legacy Magpie: the gateway this tool's manifest records (``gateway.group``) and the
111
+ ``magpie`` CLI that reaches it."""
112
+
113
+ def pi_profile(self, plan: harness.HarnessPlan) -> Path:
114
+ # A Magpie plan on a shared daemon has none (KeyError, unavailable), never the user's
115
+ # ~/.pi/agent.
116
+ return Path(harness_core.gateway_environment(plan)["PI_CODING_AGENT_DIR"]).expanduser()
117
+
118
+ def pi_owner(self, plan: harness.HarnessPlan, owned: hosts.Owned) -> Refusal | None:
119
+ gateway = plan["gateway"]
120
+ if (
121
+ owned["gateway"]["group"] != gateway["group"]
122
+ or not owned["pi"]
123
+ or owned["pi"]["model"] != gateway["pi_model"]
124
+ ):
125
+ return ("gateway-ownership", None)
126
+ return None
127
+
128
+ def _inspect(self, plan: harness.HarnessPlan, prefixes: list[str]) -> harness.ToolState:
129
+ env = {
130
+ **with_path(harness.checked_gateway_environment(plan), prefixes),
131
+ "MAGPIE_ADDR": plan["gateway"]["addr"],
132
+ }
133
+ return harness.inspect(
134
+ env=env, tools_dir=plan["tools_dir"], approved=plan, private_clients=True
135
+ )
136
+
137
+ def pi_env(
138
+ self, plan: harness.HarnessPlan, owned: hosts.Owned, executable: Path, profile: Path
139
+ ) -> dict[str, str] | None:
140
+ magpie = harness.tool_path(plan, "magpie")
141
+ env = {
142
+ **with_path(
143
+ harness.checked_gateway_environment(plan),
144
+ [str(executable.parent), str(Path(magpie).parent)],
145
+ ),
146
+ "MAGPIE_ADDR": plan["gateway"]["addr"],
147
+ "PI_CODING_AGENT_DIR": str(profile),
148
+ }
149
+ state = harness.inspect(
150
+ env=env, tools_dir=plan["tools_dir"], approved=plan, private_clients=True
151
+ )
152
+ if (
153
+ not state["gateway_up"]
154
+ or state.get("gateway_other_user")
155
+ or not state["pi"]
156
+ or not state["magpie"]
157
+ or not same_real_path(state["magpie"], magpie)
158
+ or not same_real_path(state["pi"], executable)
159
+ or state["pi_model"] != plan["gateway"]["pi_model"]
160
+ ):
161
+ return None
162
+ return env
163
+
164
+ def pi_on_previous(self, profile: Path) -> bool:
165
+ return magpie_legacy.MAGPIE_LEGACY.selected_in_pi(None, bifrost_pi.pi_model(profile))
166
+
167
+ def library_refusal(
168
+ self, plan: harness.HarnessPlan, owned: hosts.Owned, unadopted: bool
169
+ ) -> str | None:
170
+ if unadopted and owned["gateway"]["group"] != plan["gateway"]["group"]:
171
+ return "gateway-ownership"
172
+ magpie = harness.tool_path(plan, "magpie")
173
+ state = self._inspect(plan, [str(Path(magpie).parent)])
174
+ if not state["gateway_up"] or state.get("gateway_other_user"):
175
+ return "gateway-unavailable"
176
+ return None
177
+
178
+
179
+ BIFROST: BifrostOps = BifrostOps()
180
+ MAGPIE: BifrostOps = MagpieOps()
181
+
182
+
183
+ def of(gateway: Mapping[str, Any] | None) -> BifrostOps:
184
+ """The operations of the gateway a plan's ``harness.gateway`` names."""
185
+ return MAGPIE if magpie_legacy.of(gateway).legacy else BIFROST
@@ -26,6 +26,7 @@ from localmodels import (
26
26
  gateway_foundations,
27
27
  harness,
28
28
  http_local,
29
+ magpie_legacy,
29
30
  runtime_auth,
30
31
  runtime_cli,
31
32
  runtime_io,
@@ -42,7 +43,7 @@ def read_state(root: Path) -> dict[str, Any]:
42
43
  value: dict[str, Any] = json.loads(path.read_text())
43
44
  if value.get("schema") != SCHEMA or value.get("runtime") not in runtime_cli.RUNTIMES:
44
45
  raise ValueError("Invalid gateway ownership")
45
- if value.get("kind", "magpie") not in ("magpie", "bifrost"):
46
+ if not magpie_legacy.known(value.get("kind", magpie_legacy.MAGPIE)):
46
47
  raise ValueError("Invalid gateway kind")
47
48
  for field in ("port", "upstreamPort"):
48
49
  if type(value.get(field)) is not int or not 1 <= value[field] <= 65535:
@@ -444,7 +445,7 @@ def serve(root: Path) -> None:
444
445
  return
445
446
  bifrost = (
446
447
  gateway_app_bifrost.Upstream(root, state, lambda: resolve_provider(root, state))
447
- if state.get("kind") == "bifrost"
448
+ if not magpie_legacy.of(state).legacy
448
449
  else None
449
450
  )
450
451
  env: dict[str, str]
@@ -23,6 +23,7 @@ from localmodels import (
23
23
  harness_gateway,
24
24
  harness_probe,
25
25
  hosts,
26
+ magpie_legacy,
26
27
  pi_profile,
27
28
  runtime_discovery,
28
29
  stack_clients,
@@ -71,7 +72,6 @@ from localmodels.harness_core import fetch_artifact as fetch_artifact
71
72
  from localmodels.harness_core import fetch_many as fetch_many
72
73
  from localmodels.harness_core import gateway_addr as gateway_addr
73
74
  from localmodels.harness_core import gateway_environment as gateway_environment
74
- from localmodels.harness_core import gateway_kind as gateway_kind
75
75
  from localmodels.harness_core import load_lock as load_lock
76
76
  from localmodels.harness_core import own_downloads as own_downloads
77
77
  from localmodels.harness_core import reuse_tool as reuse_tool
@@ -102,7 +102,7 @@ def plan_tools(
102
102
  systemd_user: bool,
103
103
  tools_dir: str = DEFAULT_TOOLS_DIR,
104
104
  lock: ToolLock | None = None,
105
- gateway: str = "magpie",
105
+ gateway: str = magpie_legacy.MAGPIE,
106
106
  ) -> ToolPlan:
107
107
  """Reuse what works, install the pinned version of what is missing, never replace: Node.js,
108
108
  pi, the gateway's program (Magpie, or this tool's Bifrost) and the gateway, with no model
@@ -156,16 +156,16 @@ def plan_tools(
156
156
  warnings.append(
157
157
  f"{bin_dir} is not on PATH; add it to PATH in a new terminal to run pi directly"
158
158
  )
159
- if gateway == "bifrost":
160
- bifrost_actions, gateway_warnings = gateway_bifrost.plan_tools(
159
+ if magpie_legacy.for_kind(gateway).legacy:
160
+ gateway_plan, gateway_warnings = harness_gateway.plan_gateway(
161
161
  state, platform, arch, systemd_user, tools_dir, lock
162
162
  )
163
- actions += bifrost_actions
163
+ actions += gateway_plan["tools"]
164
164
  else:
165
- gateway_plan, gateway_warnings = harness_gateway.plan_gateway(
165
+ bifrost_actions, gateway_warnings = gateway_bifrost.plan_tools(
166
166
  state, platform, arch, systemd_user, tools_dir, lock
167
167
  )
168
- actions += gateway_plan["tools"]
168
+ actions += bifrost_actions
169
169
  warnings += gateway_warnings
170
170
 
171
171
  return {
@@ -187,7 +187,7 @@ def plan_harness(
187
187
  lock: ToolLock | None = None,
188
188
  efforts: tuple[str, ...] = ("low", "medium", "high"),
189
189
  clients: bool = False,
190
- gateway_kind: str = "magpie",
190
+ gateway_kind: str = magpie_legacy.MAGPIE,
191
191
  context: int | None = None,
192
192
  vision: bool = False,
193
193
  ) -> HarnessPlan:
@@ -218,12 +218,9 @@ def plan_harness(
218
218
  f"{BIN_DIR} is not on PATH; add it to PATH before running the three clients"
219
219
  " directly"
220
220
  )
221
- if gateway_kind == "magpie":
222
- tools["warnings"].append(
223
- "to register the local service keys, the control side uses Magpie's local"
224
- " authenticated admin API; keys stay out of command-line arguments, diagnostic output"
225
- " and temporary files, and are then kept in Magpie's providers.json (0600)"
226
- )
221
+ adapter = magpie_legacy.for_kind(gateway_kind)
222
+ if adapter.plan_warning:
223
+ tools["warnings"].append(adapter.plan_warning)
227
224
  gateway: GatewayPlan = {
228
225
  "addr": state["gateway_addr"],
229
226
  "group": GROUP,
@@ -249,7 +246,7 @@ def plan_harness(
249
246
  for a in p["artifacts"]
250
247
  )
251
248
  plan = cast(HarnessPlan, {**tools, "gateway": gateway})
252
- if gateway_kind == "bifrost":
249
+ if not adapter.legacy:
253
250
  gateway_bifrost.adopt(plan, state, decision is not None, context, vision=vision)
254
251
  return plan
255
252
 
@@ -420,7 +417,7 @@ def inspect(
420
417
  search = search_path(env)
421
418
  node, pi, magpie = (shutil.which(name, path=search) for name in ("node", "pi", "magpie"))
422
419
  magpie = harness_probe.windows_program(magpie)
423
- bifrost = bool(approved and gateway_kind(approved.get("gateway")) == "bifrost")
420
+ bifrost = bool(approved and not magpie_legacy.of(approved.get("gateway")).legacy)
424
421
  bifrost_address = (
425
422
  str(approved["gateway"]["addr"]) if bifrost and approved else bifrost_addr(env)
426
423
  )
@@ -17,7 +17,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
17
17
  from pathlib import Path
18
18
  from typing import Any, Literal, TypedDict, cast
19
19
 
20
- from localmodels import harness_cleanup, hosts, pi_profile, region
20
+ from localmodels import harness_cleanup, hosts, magpie_legacy, pi_profile, region
21
21
  from localmodels.contracts import decode
22
22
  from localmodels.npm_transport import Artifact as Artifact
23
23
  from localmodels.npm_transport import ToolBuild as ToolBuild
@@ -32,8 +32,8 @@ BIN_DIR = "~/.local/bin"
32
32
  UNIT_DIR = "~/.config/systemd/user"
33
33
  GATEWAY_ADDR = "127.0.0.1:3425" # Magpie's default; MAGPIE_ADDR overrides it
34
34
  BIFROST_ADDR = "127.0.0.1:18480" # this tool's Bifrost; LOCALMODELS_BIFROST_ADDR overrides it
35
- GATEWAYS = ("bifrost", "magpie")
36
- DEFAULT_GATEWAY = "bifrost"
35
+ GATEWAYS = magpie_legacy.KINDS
36
+ DEFAULT_GATEWAY = magpie_legacy.BIFROST
37
37
  LLM_PROVIDER = "localmodels-llm"
38
38
  DECISION_PROVIDER = "localmodels-jev"
39
39
  GROUP = "localmodels-agent"
@@ -245,11 +245,6 @@ def bifrost_addr(env: dict[str, str] | None = None) -> str:
245
245
  return (env if env is not None else os.environ).get("LOCALMODELS_BIFROST_ADDR") or BIFROST_ADDR
246
246
 
247
247
 
248
- def gateway_kind(gw: GatewayPlan | dict[str, Any] | None) -> str:
249
- """The gateway a stack plan's ``harness.gateway`` names; a plan without one used Magpie."""
250
- return str((gw or {}).get("kind") or "magpie")
251
-
252
-
253
248
  def search_path(env: dict[str, str]) -> str:
254
249
  """PATH plus ~/.local/bin, where installers put commands and non-login shells miss it."""
255
250
  home = env.get("HOME") or os.path.expanduser("~")
@@ -307,7 +302,7 @@ def gateway_environment(plan: ToolPlan, *, base: dict[str, str] | None = None) -
307
302
  gateway = plan.get("gateway")
308
303
  if isinstance(gateway, dict) and gateway.get("addr") != action["path"]:
309
304
  raise HarnessError("the gateway address in the approved plan does not match")
310
- if isinstance(gateway, dict) and gateway_kind(gateway) == "bifrost":
305
+ if isinstance(gateway, dict) and not magpie_legacy.of(gateway).legacy:
311
306
  if "environment" not in plan:
312
307
  env.update(pi_profile.client_environment(plan["tools_dir"]))
313
308
  return env
@@ -19,6 +19,7 @@ from localmodels import (
19
19
  harness_core,
20
20
  harness_probe,
21
21
  hosts,
22
+ magpie_legacy,
22
23
  magpie_windows,
23
24
  pi_profile,
24
25
  process_identity,
@@ -108,13 +109,19 @@ def select_address(
108
109
  ) -> str:
109
110
  """Resolve an automatic address before querying any gateway; fixed addresses never move."""
110
111
  candidates = [requested] if requested else [f"127.0.0.1:{p}" for p in range(3425, 3457)]
112
+ unknown = False
111
113
  for addr in candidates:
112
114
  try:
113
115
  busy = address_listening(addr, listening)
114
116
  except (OSError, RuntimeError) as exc:
115
- raise harness_core.HarnessError(
116
- "cannot confirm whether the Magpie gateway port is free"
117
- ) from exc
117
+ # An automatic address the probe cannot tell about is skipped like a busy one.
118
+ if requested:
119
+ raise harness_core.HarnessError(
120
+ "cannot confirm whether the Magpie gateway port is free; check again",
121
+ code="port-check-failed",
122
+ ) from exc
123
+ unknown = True
124
+ continue
118
125
  if not busy or owned(addr):
119
126
  return addr
120
127
  if requested:
@@ -123,6 +130,11 @@ def select_address(
123
130
  " that program is kept",
124
131
  code="gateway-port-in-use",
125
132
  )
133
+ if unknown:
134
+ raise harness_core.HarnessError(
135
+ "cannot confirm whether any Magpie default port 3425..3456 is free; check again",
136
+ code="port-check-failed",
137
+ )
126
138
  raise harness_core.HarnessError(
127
139
  "Magpie default ports 3425..3456 are all in use", code="gateway-port-in-use"
128
140
  )
@@ -290,7 +302,7 @@ def magpie_target(tools_dir: str) -> harness_core.ToolPlan | None:
290
302
  return None
291
303
  if _magpie_tool(target) is not None:
292
304
  return target
293
- if harness_core.gateway_kind(target.get("gateway")) != "bifrost": # type: ignore[arg-type]
305
+ if magpie_legacy.of(target.get("gateway")).legacy: # type: ignore[arg-type]
294
306
  return None
295
307
  return None
296
308
 
@@ -438,7 +450,7 @@ def gateway_profile(plan: harness_core.ToolPlan | None) -> Path | None:
438
450
  profile = pi_profile.gateway_home(plan["tools_dir"])
439
451
  environment = harness_core.gateway_environment(plan)
440
452
  gateway = plan.get("gateway")
441
- if isinstance(gateway, dict) and harness_core.gateway_kind(gateway) == "bifrost":
453
+ if isinstance(gateway, dict) and not magpie_legacy.of(gateway).legacy:
442
454
  if any(
443
455
  environment.get(key) != value
444
456
  for key, value in pi_profile.client_environment(plan["tools_dir"]).items()
@@ -456,7 +468,7 @@ def purge_gateway_profile(plan: harness_core.ToolPlan | None, notes: list[str])
456
468
  if profile is None or not profile.exists() or plan is None:
457
469
  return
458
470
  gateway = plan.get("gateway")
459
- if isinstance(gateway, dict) and harness_core.gateway_kind(gateway) == "bifrost":
471
+ if isinstance(gateway, dict) and not magpie_legacy.of(gateway).legacy:
460
472
  record = hosts.load_owned(plan["tools_dir"])["gateway"].get("bifrost")
461
473
  if (
462
474
  record is not None
@@ -2,12 +2,15 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import contextlib
6
+ import contextvars
5
7
  import errno
6
8
  import os
7
9
  import re
8
10
  import socket
9
11
  import subprocess
10
12
  import sys
13
+ from collections.abc import Iterator
11
14
  from pathlib import Path
12
15
 
13
16
  from localmodels import (
@@ -185,9 +188,53 @@ def _listdir(path: str) -> list[str]:
185
188
  return []
186
189
 
187
190
 
191
+ # A connect that times out met a listener whose accept backlog is full (or, on macOS, a bound
192
+ # socket that does not listen): the port is in use, not unknown.
193
+ _IN_USE_RESULTS = frozenset({errno.EAGAIN, errno.EWOULDBLOCK, errno.ETIMEDOUT})
194
+ _SNAPSHOT: contextvars.ContextVar[dict[int, bool | str] | None] = contextvars.ContextVar(
195
+ "loopback_snapshot", default=None
196
+ )
197
+
198
+
199
+ @contextlib.contextmanager
200
+ def loopback_snapshot() -> Iterator[None]:
201
+ """Within one plan each loopback port is probed once and every later question gets the same
202
+ answer, so a port chosen as free is not found taken a moment later by a slower probe (which
203
+ made ``--llm auto`` pass over a candidate). Nested uses share the outer snapshot."""
204
+ if _SNAPSHOT.get() is not None:
205
+ yield
206
+ return
207
+ token = _SNAPSHOT.set({})
208
+ try:
209
+ yield
210
+ finally:
211
+ _SNAPSHOT.reset(token)
212
+
213
+
188
214
  def loopback_listening(port: int) -> bool:
189
- """Only connection refusal proves that a loopback port has no TCP listener. Windows reads
190
- its listener table instead: a refused loopback connect retries there for about two seconds."""
215
+ """Only connection refusal proves that a loopback port has no TCP listener; a connect that
216
+ times out counts as in use. Raises OSError when neither can be told. Inside
217
+ ``loopback_snapshot`` the first answer for a port, or its error, is the answer for the plan."""
218
+ seen = _SNAPSHOT.get()
219
+ if seen is not None and port in seen:
220
+ known = seen[port]
221
+ if isinstance(known, str):
222
+ raise OSError(known)
223
+ return known
224
+ try:
225
+ answer = _probe_loopback(port)
226
+ except OSError as exc:
227
+ if seen is not None:
228
+ seen[port] = str(exc)
229
+ raise
230
+ if seen is not None:
231
+ seen[port] = answer
232
+ return answer
233
+
234
+
235
+ def _probe_loopback(port: int) -> bool:
236
+ """Windows reads its listener table instead: a refused loopback connect retries there for
237
+ about two seconds."""
191
238
  if sys.platform == "win32":
192
239
  if (pids := process_identity.listener_pids(port)) is None:
193
240
  raise OSError(f"cannot confirm whether port {port} is free")
@@ -195,13 +242,27 @@ def loopback_listening(port: int) -> bool:
195
242
  with socket.socket() as sock:
196
243
  sock.settimeout(1)
197
244
  result = sock.connect_ex(("127.0.0.1", port))
198
- if result == 0:
245
+ if result == 0 or result in _IN_USE_RESULTS:
199
246
  return True
200
247
  if result == errno.ECONNREFUSED:
201
248
  return False
202
249
  raise OSError(f"cannot confirm whether port {port} is free (connect result {result})")
203
250
 
204
251
 
252
+ def loopback_bindable(port: int) -> bool:
253
+ """Whether a server could bind ``127.0.0.1:port`` now, as http.server binds it (reusing
254
+ TIME_WAIT on POSIX). A port without a listener can still be held: where the ephemeral range
255
+ covers it, an outgoing connection's local port refuses bind() though connect() is refused."""
256
+ with socket.socket() as sock:
257
+ if os.name != "nt":
258
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
259
+ try:
260
+ sock.bind(("127.0.0.1", port))
261
+ except OSError:
262
+ return False
263
+ return True
264
+
265
+
205
266
  def bifrost_held(addr: str) -> str:
206
267
  """The refusal for a listener of this user's that the manifest does not own, naming it: a
207
268
  bifrost-http is most often another HOME's or state directory's localmodels gateway."""
@@ -17,6 +17,7 @@ from contextlib import contextmanager
17
17
  from pathlib import Path
18
18
  from typing import Any, Literal, TypedDict, TypeVar
19
19
 
20
+ from localmodels import deployment_lifecycle as lifecycle
20
21
  from localmodels.contracts import decode
21
22
  from localmodels.probe import HostFacts
22
23
  from localmodels.records import Device, FinishedRecord, Plan
@@ -249,13 +250,6 @@ def load_facts(dev_id: str) -> HostFacts | None:
249
250
  return _read(state_dir() / "facts" / f"{dev_id}.json", None, lambda v: decode(v, HostFacts))
250
251
 
251
252
 
252
- def _same_place(a: str, b: str) -> bool:
253
- def norm(path: str) -> str:
254
- return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
255
-
256
- return norm(a) == norm(b)
257
-
258
-
259
253
  def _record_touched_service(record: FinishedRecord) -> bool:
260
254
  """True when a deployment succeeded or got far enough that it may have installed or started
261
255
  service files on this computer. A deploy that failed before ``install`` succeeded (for
@@ -298,9 +292,9 @@ def deployment_dirs(dev_id: str) -> dict[str, str]:
298
292
  if dev_id == LOCAL_ID and owned_path().is_file():
299
293
  try:
300
294
  for name, entry in load_owned()["deployments"].items():
301
- if entry["removed"] or entry.get("failed"):
295
+ if not lifecycle.is_live(entry):
302
296
  continue
303
- if name not in taken or not _same_place(taken[name], entry["deploy_dir"]):
297
+ if name not in taken or not lifecycle.same_dir(taken[name], entry["deploy_dir"]):
304
298
  taken[name] = entry["deploy_dir"]
305
299
  except (OSError, ValueError):
306
300
  pass
@@ -321,9 +315,10 @@ def record(dev_id: str, name: str) -> FinishedRecord:
321
315
  def delete_record(
322
316
  dev_id: str, name: str, *, purged: bool = False, deploy_dir: str | None = None
323
317
  ) -> None:
324
- """Forget a removed deployment. On this computer the owned manifest keeps it as removed, its
325
- files and log left for a purge, or drops it when ``purged`` — only when the manifest entry
326
- belongs to this deployment's directory, never another controller's."""
318
+ """Forget a removed deployment. On this computer the owned manifest entry moves to
319
+ ``Phase.REMOVED``, its files and log left for a purge, or to ``Phase.ABSENT`` when ``purged``
320
+ (``deployment_lifecycle``) — only when the entry belongs to this deployment's directory, never
321
+ another controller's."""
327
322
  path = state_dir() / "deployments" / dev_id / f"{name}.json"
328
323
  recorded_dir = deploy_dir
329
324
  if recorded_dir is None and path.is_file():
@@ -339,12 +334,10 @@ def delete_record(
339
334
  entry = doc["deployments"].get(name)
340
335
  if entry is None:
341
336
  return
342
- if recorded_dir is not None and not _same_place(entry["deploy_dir"], recorded_dir):
337
+ if recorded_dir is not None and not lifecycle.same_dir(entry["deploy_dir"], recorded_dir):
343
338
  return
344
- if purged:
345
- del doc["deployments"][name]
346
- else:
347
- entry["removed"] = True
339
+ event = lifecycle.Event.PURGE if purged else lifecycle.Event.REMOVE
340
+ lifecycle.advance(doc["deployments"], name, event)
348
341
 
349
342
  if owned_path().is_file():
350
343
  update_owned(change)
@@ -358,9 +351,7 @@ OWNED_SCHEMA = "localmodels.owned/v1"
358
351
 
359
352
  class _OwnedPreparation(TypedDict, total=False):
360
353
  preparation_dir: str
361
- failed: (
362
- bool # True when recorded from a failed/interrupted deploy; never blocks a verified owner
363
- )
354
+ failed: bool # deployment_lifecycle.Phase.FAILED: a failed/interrupted deploy
364
355
 
365
356
 
366
357
  class OwnedDeployment(_OwnedPreparation):
@@ -371,7 +362,7 @@ class OwnedDeployment(_OwnedPreparation):
371
362
  unit: str | None # the systemd --user unit file
372
363
  slice: str | None
373
364
  files: list[str] # model files this tool downloaded or hard-linked and verified
374
- removed: bool # the service is gone; its files and log stay until a purge
365
+ removed: bool # deployment_lifecycle.Phase.REMOVED: files and log stay until a purge
375
366
 
376
367
 
377
368
  class _OwnedBifrostSince20261102(TypedDict, total=False):
@@ -663,10 +654,9 @@ def port_owned_elsewhere(port: int, deploy_dir: str, tools_dir: str | Path = TOO
663
654
  except (OSError, ValueError):
664
655
  return False
665
656
  return any(
666
- not entry["removed"]
667
- and not entry.get("failed")
657
+ lifecycle.is_live(entry)
668
658
  and entry["port"] == port
669
- and not _same_place(entry["deploy_dir"], deploy_dir)
659
+ and not lifecycle.same_dir(entry["deploy_dir"], deploy_dir)
670
660
  for entry in entries
671
661
  )
672
662
 
@@ -677,29 +667,27 @@ def own_deployment(plan: Plan, tools_dir: str | Path = TOOLS_DIR, *, ok: bool =
677
667
  verified deployment, and on failure never registers a competing owner on a port another live
678
668
  deployment holds."""
679
669
  entry = owned_entry(plan)
680
- if not ok:
681
- entry["failed"] = True
682
670
  recorded = False
683
671
 
684
672
  def add(doc: Owned) -> None:
685
673
  nonlocal recorded
686
674
  existing = doc["deployments"].get(plan["name"])
687
- if existing is not None and not _same_place(existing["deploy_dir"], entry["deploy_dir"]):
688
- existing_live = not existing["removed"] and not existing.get("failed")
689
- if existing_live or not ok:
675
+ if existing is not None and not lifecycle.same_dir(
676
+ existing["deploy_dir"], entry["deploy_dir"]
677
+ ):
678
+ if lifecycle.is_live(existing) or not ok:
690
679
  return
691
680
  for other in doc["deployments"].values():
692
- if (
693
- other["removed"]
694
- or other.get("failed")
695
- or _same_place(other["deploy_dir"], entry["deploy_dir"])
681
+ if not lifecycle.is_live(other) or lifecycle.same_dir(
682
+ other["deploy_dir"], entry["deploy_dir"]
696
683
  ):
697
684
  continue
698
685
  if other["service"] == entry["service"]:
699
686
  return
700
687
  if not ok and other["port"] == entry["port"]:
701
688
  return
702
- doc["deployments"][plan["name"]] = entry
689
+ event = lifecycle.Event.DEPLOYED if ok else lifecycle.Event.DEPLOY_FAILED
690
+ lifecycle.advance(doc["deployments"], plan["name"], event, entry)
703
691
  if entry["slice"]:
704
692
  doc["slices"] = sorted({*doc["slices"], entry["slice"]})
705
693
  recorded = True