@simplexai/localmodels-darwin-x64 0.1.0-dev.64 → 0.1.0-dev.65

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 (107) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +105 -102
  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/bifrost_checks.py +2 -1
  7. package/modules/localmodels/catalog.json +4 -2
  8. package/modules/localmodels/catalog.py +2 -1
  9. package/modules/localmodels/catalog_recipes.py +3 -0
  10. package/modules/localmodels/component.py +1 -1
  11. package/modules/localmodels/context_policy.py +1 -1
  12. package/modules/localmodels/custom_probe.py +5 -5
  13. package/modules/localmodels/deploy.py +88 -12
  14. package/modules/localmodels/deployment_lifecycle.py +167 -0
  15. package/modules/localmodels/draft_spec.py +43 -1
  16. package/modules/localmodels/gateway.py +124 -13
  17. package/modules/localmodels/gateway_accept.py +1 -6
  18. package/modules/localmodels/gateway_cli.py +13 -24
  19. package/modules/localmodels/gateway_ops.py +185 -0
  20. package/modules/localmodels/gateway_server.py +3 -2
  21. package/modules/localmodels/harness.py +13 -16
  22. package/modules/localmodels/harness_core.py +4 -9
  23. package/modules/localmodels/harness_gateway.py +4 -3
  24. package/modules/localmodels/hosts.py +22 -34
  25. package/modules/localmodels/library_convert.py +3 -3
  26. package/modules/localmodels/library_custom.py +6 -6
  27. package/modules/localmodels/library_elastic.py +23 -10
  28. package/modules/localmodels/library_jobs.py +13 -3
  29. package/modules/localmodels/library_order.py +4 -3
  30. package/modules/localmodels/library_poly.py +2 -2
  31. package/modules/localmodels/library_pricing.py +34 -318
  32. package/modules/localmodels/library_serve.py +9 -8
  33. package/modules/localmodels/library_smoke.py +8 -1
  34. package/modules/localmodels/library_status.py +16 -16
  35. package/modules/localmodels/llm_rank.py +1 -1
  36. package/modules/localmodels/magpie_legacy.py +160 -0
  37. package/modules/localmodels/magpie_setup.py +6 -1
  38. package/modules/localmodels/pi_profile.py +3 -7
  39. package/modules/localmodels/plan_envelope.py +1 -1
  40. package/modules/localmodels/{budget.py → planning/budget.py} +48 -30
  41. package/modules/localmodels/{stack_llm_ram.py → planning/llm_ram.py} +11 -1
  42. package/modules/localmodels/planning/memory_pools.py +403 -0
  43. package/modules/localmodels/recommend.py +1 -1
  44. package/modules/localmodels/recommend_cli.py +3 -4
  45. package/modules/localmodels/residency_host.py +1 -1
  46. package/modules/localmodels/service_control.py +4 -4
  47. package/modules/localmodels/service_deployment.py +1 -1
  48. package/modules/localmodels/service_wiring.py +17 -19
  49. package/modules/localmodels/setup_inspection.py +1 -1
  50. package/modules/localmodels/setup_inspection_harness.py +1 -1
  51. package/modules/localmodels/setup_upgrade.py +3 -12
  52. package/modules/localmodels/speech_admission.py +1 -1
  53. package/modules/localmodels/speech_jobs.py +2 -1
  54. package/modules/localmodels/speech_model.py +2 -0
  55. package/modules/localmodels/speech_server.py +130 -9
  56. package/modules/localmodels/speech_state.py +11 -0
  57. package/modules/localmodels/speech_worker_sensevoice.py +21 -13
  58. package/modules/localmodels/speech_workers.py +5 -1
  59. package/modules/localmodels/stack.py +2 -5
  60. package/modules/localmodels/stack_auto.py +4 -4
  61. package/modules/localmodels/stack_aux_gpu.py +1 -1
  62. package/modules/localmodels/stack_binding.py +24 -143
  63. package/modules/localmodels/stack_capacity.py +1 -1
  64. package/modules/localmodels/stack_card.py +1 -1
  65. package/modules/localmodels/stack_cleanup.py +3 -3
  66. package/modules/localmodels/stack_client_settings.py +9 -2
  67. package/modules/localmodels/stack_compose.py +35 -6
  68. package/modules/localmodels/stack_console.py +2 -2
  69. package/modules/localmodels/stack_debug.py +1 -1
  70. package/modules/localmodels/stack_decision.py +1 -1
  71. package/modules/localmodels/stack_doctor.py +10 -7
  72. package/modules/localmodels/stack_down.py +3 -3
  73. package/modules/localmodels/stack_gpu_memory.py +1 -1
  74. package/modules/localmodels/stack_hardware.py +3 -3
  75. package/modules/localmodels/stack_hardware_text.py +1 -1
  76. package/modules/localmodels/stack_lifecycle.py +7 -7
  77. package/modules/localmodels/stack_memory.py +1 -1
  78. package/modules/localmodels/stack_mlx.py +1 -1
  79. package/modules/localmodels/stack_plan.py +18 -13
  80. package/modules/localmodels/stack_ports.py +2 -2
  81. package/modules/localmodels/stack_preflight.py +4 -3
  82. package/modules/localmodels/stack_remove.py +13 -6
  83. package/modules/localmodels/stack_review.py +3 -5
  84. package/modules/localmodels/stack_rollback.py +1 -1
  85. package/modules/localmodels/stack_route.py +5 -4
  86. package/modules/localmodels/stack_suite.py +10 -3
  87. package/modules/localmodels/stack_summary.py +1 -1
  88. package/modules/localmodels/stack_try.py +8 -13
  89. package/modules/localmodels/stack_up.py +10 -9
  90. package/modules/localmodels/stack_update.py +2 -1
  91. package/modules/localmodels/stack_verify.py +4 -30
  92. package/modules/localmodels/stack_view.py +6 -4
  93. package/modules/localmodels/stack_view_apply.py +2 -2
  94. package/modules/localmodels/stack_view_text.py +2 -6
  95. package/modules/localmodels/stack_view_tick.py +2 -2
  96. package/modules/localmodels/stack_view_words.py +5 -2
  97. package/modules/localmodels/stack_warm.py +1 -1
  98. package/modules/localmodels/tui_views.py +11 -5
  99. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/METADATA +1 -1
  100. package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/RECORD +102 -99
  101. package/package.json +1 -1
  102. package/tool.json +1 -1
  103. package/modules/localmodels/library_vram.py +0 -123
  104. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/WHEEL +0 -0
  105. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/entry_points.txt +0 -0
  106. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/NOTICE +0 -0
  107. /package/modules/{simplex_localmodels-0.1.0.dev64.dist-info → simplex_localmodels-0.1.0.dev65.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -26,6 +26,7 @@ from localmodels import (
26
26
  gateway_server,
27
27
  harness,
28
28
  http_local,
29
+ magpie_legacy,
29
30
  runtime_cli,
30
31
  runtime_io,
31
32
  )
@@ -35,11 +36,11 @@ from localmodels.gateway_server import read_state as read_state
35
36
  from localmodels.gateway_server import selected_runtime as selected_runtime
36
37
 
37
38
 
38
- def artifact_for(native_platform: str, kind: str = "magpie") -> dict[str, Any]:
39
+ def artifact_for(native_platform: str, kind: str = magpie_legacy.MAGPIE) -> dict[str, Any]:
39
40
  platform, arch = native_platform.split("-", 1)
40
41
  platform = "windows" if platform == "win32" else platform
41
- lock = harness.load_lock()
42
- tool = lock["bifrost"] if kind == "bifrost" else lock["magpie"]
42
+ adapter = magpie_legacy.for_kind(kind)
43
+ tool = harness.load_lock()[adapter.tool]
43
44
  build = next(
44
45
  (b for b in tool["builds"] if b["platform"] == platform and b["arch"] == arch),
45
46
  None,
@@ -52,9 +53,7 @@ def artifact_for(native_platform: str, kind: str = "magpie") -> dict[str, Any]:
52
53
  digest=build["sha256"],
53
54
  maxBytes=build["size_bytes"],
54
55
  format="binary",
55
- executable=("magpie.exe" if platform == "windows" else "magpie")
56
- if kind == "magpie"
57
- else "bifrost-http",
56
+ executable=adapter.executable(platform),
58
57
  )
59
58
 
60
59
 
@@ -83,7 +82,7 @@ def reuse_binary(artifact: dict[str, Any], destination: Path) -> bool:
83
82
  def choose_kind(
84
83
  choice: str, runtime: str | None, row: dict[str, Any], root: Path, state: dict[str, Any]
85
84
  ) -> str:
86
- if choice not in ("auto", "bifrost", "magpie"):
85
+ if choice != "auto" and not magpie_legacy.known(choice):
87
86
  raise ValueError("Unknown gateway kind")
88
87
  if choice == "magpie":
89
88
  return choice
@@ -132,7 +131,7 @@ def build_plan(
132
131
  }
133
132
  kind = choose_kind(gateway, runtime, row, root, state)
134
133
  platform = runtime_cli.platform()
135
- artifact = artifact_for(platform) if kind == "magpie" else artifact_for(platform, kind)
134
+ artifact = artifact_for(platform, kind)
136
135
  target = root / artifact["executable"]
137
136
  action, download_bytes, disk_bytes = "download", artifact["size_bytes"], artifact["size_bytes"]
138
137
  if target.exists() or target.is_symlink():
@@ -148,11 +147,7 @@ def build_plan(
148
147
  runtime=runtime,
149
148
  kind=kind,
150
149
  platform=platform,
151
- version=(
152
- harness.load_lock()["bifrost"]["version"]
153
- if kind == "bifrost"
154
- else harness.load_lock()["magpie"]["version"]
155
- ),
150
+ version=harness.load_lock()[magpie_legacy.for_kind(kind).tool]["version"],
156
151
  action=action,
157
152
  artifacts=[artifact],
158
153
  downloadBytes=download_bytes,
@@ -239,7 +234,7 @@ def _stop(root: Path) -> dict[str, Any]:
239
234
  except (OSError, ValueError, urllib.error.URLError, http.client.HTTPException):
240
235
  pass # The server may have closed between its status and stop requests.
241
236
  if worker_idle(root):
242
- if state.get("kind") == "bifrost":
237
+ if not magpie_legacy.of(state).legacy:
243
238
  gateway_bifrost.stop_serve(root / "bifrost")
244
239
  result = status(root)
245
240
  if result["ready"]:
@@ -263,11 +258,7 @@ def _port() -> int:
263
258
 
264
259
 
265
260
  def ensure_binary(root: Path, kind: str, event: runtime_io.Event) -> None:
266
- artifact = (
267
- artifact_for(runtime_cli.platform())
268
- if kind == "magpie"
269
- else artifact_for(runtime_cli.platform(), kind)
270
- )
261
+ artifact = artifact_for(runtime_cli.platform(), kind)
271
262
  binary = root / artifact["executable"]
272
263
  if binary.exists() or binary.is_symlink():
273
264
  runtime_io.private_permissions(binary)
@@ -278,7 +269,7 @@ def ensure_binary(root: Path, kind: str, event: runtime_io.Event) -> None:
278
269
  staged = Path(temporary) / artifact["executable"]
279
270
  if reuse_binary(artifact, staged):
280
271
  event({"kind": "stage", "stage": f"reuse-{kind}", "state": "succeeded"})
281
- elif kind == "bifrost" and "npm" in artifact:
272
+ elif not magpie_legacy.for_kind(kind).legacy and "npm" in artifact:
282
273
  # Beside the binary, not in the staging directory: a later ensure resumes it,
283
274
  # and removing the gateway root removes it too.
284
275
  tarball = root / f".{artifact['name']}.tgz" # versioned: no stale resume
@@ -296,7 +287,7 @@ def wait_ready(
296
287
  event: runtime_io.Event,
297
288
  worker: subprocess.Popen[bytes] | None = None,
298
289
  ) -> dict[str, Any]:
299
- timeout = gateway_bifrost.HEALTH_TIMEOUT_S if kind == "bifrost" else 30
290
+ timeout = magpie_legacy.for_kind(kind).health_timeout_s or gateway_bifrost.HEALTH_TIMEOUT_S
300
291
  deadline = time.monotonic() + timeout
301
292
  while time.monotonic() < deadline:
302
293
  if worker is not None and worker.poll() is not None:
@@ -356,9 +347,7 @@ def ensure(
356
347
  _stop(root)
357
348
  if state.get("kind", "magpie") != kind:
358
349
  # The previous upstream has exited; only its private config is removed.
359
- config = (
360
- root / "home" / ".config" / "magpie" if kind == "bifrost" else root / "bifrost"
361
- )
350
+ config = root.joinpath(*magpie_legacy.of(state).app_config)
362
351
  if config.exists() or config.is_symlink():
363
352
  runtime_io.validate_runtime_root(config)
364
353
  shutil.rmtree(config)
@@ -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,
@@ -290,7 +291,7 @@ def magpie_target(tools_dir: str) -> harness_core.ToolPlan | None:
290
291
  return None
291
292
  if _magpie_tool(target) is not None:
292
293
  return target
293
- if harness_core.gateway_kind(target.get("gateway")) != "bifrost": # type: ignore[arg-type]
294
+ if magpie_legacy.of(target.get("gateway")).legacy: # type: ignore[arg-type]
294
295
  return None
295
296
  return None
296
297
 
@@ -438,7 +439,7 @@ def gateway_profile(plan: harness_core.ToolPlan | None) -> Path | None:
438
439
  profile = pi_profile.gateway_home(plan["tools_dir"])
439
440
  environment = harness_core.gateway_environment(plan)
440
441
  gateway = plan.get("gateway")
441
- if isinstance(gateway, dict) and harness_core.gateway_kind(gateway) == "bifrost":
442
+ if isinstance(gateway, dict) and not magpie_legacy.of(gateway).legacy:
442
443
  if any(
443
444
  environment.get(key) != value
444
445
  for key, value in pi_profile.client_environment(plan["tools_dir"]).items()
@@ -456,7 +457,7 @@ def purge_gateway_profile(plan: harness_core.ToolPlan | None, notes: list[str])
456
457
  if profile is None or not profile.exists() or plan is None:
457
458
  return
458
459
  gateway = plan.get("gateway")
459
- if isinstance(gateway, dict) and harness_core.gateway_kind(gateway) == "bifrost":
460
+ if isinstance(gateway, dict) and not magpie_legacy.of(gateway).legacy:
460
461
  record = hosts.load_owned(plan["tools_dir"])["gateway"].get("bifrost")
461
462
  if (
462
463
  record is not None
@@ -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
@@ -23,7 +23,6 @@ from localmodels import (
23
23
  harness,
24
24
  hosts,
25
25
  library_gateway,
26
- library_pricing,
27
26
  library_state,
28
27
  library_status,
29
28
  stack_run,
@@ -33,6 +32,7 @@ from localmodels.contracts import decode
33
32
  from localmodels.library_model import library_id
34
33
  from localmodels.library_state import Record, Registration
35
34
  from localmodels.plan_envelope import utc_now
35
+ from localmodels.planning import memory_pools
36
36
  from localmodels.records import Plan
37
37
  from localmodels.stack_plan import StackPlan
38
38
 
@@ -304,7 +304,7 @@ def _adopt_record(model: str, provider: str, deployed: Plan, base_dir: str | Non
304
304
  if library_state.job_alive(model):
305
305
  return False
306
306
  spec = deployed["model"]
307
- pool = library_pricing.pool_of(deployed)
307
+ pool = memory_pools.pool_of(deployed)
308
308
  existing = library_state.load(model)
309
309
  prev_deploy_dir = existing["plan"]["service"]["deploy_dir"] if existing is not None else None
310
310
  if existing is None:
@@ -331,7 +331,7 @@ def _adopt_record(model: str, provider: str, deployed: Plan, base_dir: str | Non
331
331
  record["state"] = "loaded"
332
332
  record["converted"] = True
333
333
  record["stack_provider"] = provider
334
- record["memory_bytes"] = library_pricing.memory_bytes(deployed)
334
+ record["memory_bytes"] = memory_pools.memory_bytes(deployed)
335
335
  if base_dir is not None:
336
336
  record["base_dir"] = base_dir
337
337
  elif prev_deploy_dir != deployed["service"]["deploy_dir"]: