@simplexai/localmodels-darwin-x64 0.1.0-dev.58 → 0.1.0-dev.59

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 (59) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +57 -56
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/app.py +1 -1
  5. package/modules/localmodels/bifrost_admin.py +53 -8
  6. package/modules/localmodels/bifrost_config.py +103 -4
  7. package/modules/localmodels/bifrost_log.py +166 -0
  8. package/modules/localmodels/budget.py +1 -1
  9. package/modules/localmodels/catalog.json +55 -32
  10. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +94 -0
  11. package/modules/localmodels/frontend.py +26 -21
  12. package/modules/localmodels/gateway_bifrost.py +30 -6
  13. package/modules/localmodels/hosts.py +99 -12
  14. package/modules/localmodels/library_convert.py +34 -0
  15. package/modules/localmodels/library_elastic.py +150 -123
  16. package/modules/localmodels/library_gateway.py +101 -10
  17. package/modules/localmodels/library_jobs.py +16 -7
  18. package/modules/localmodels/library_pricing.py +14 -4
  19. package/modules/localmodels/library_serve.py +84 -16
  20. package/modules/localmodels/library_state.py +4 -1
  21. package/modules/localmodels/library_status.py +18 -4
  22. package/modules/localmodels/metal.py +1 -1
  23. package/modules/localmodels/metal_probe.py +4 -4
  24. package/modules/localmodels/plan_envelope.py +4 -1
  25. package/modules/localmodels/process_identity_linux.py +39 -0
  26. package/modules/localmodels/remote_ops.py +4 -3
  27. package/modules/localmodels/remote_ops_download.py +37 -24
  28. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  29. package/modules/localmodels/remote_ops_service.py +93 -36
  30. package/modules/localmodels/runtime_auth.py +4 -1
  31. package/modules/localmodels/service_wiring.py +238 -12
  32. package/modules/localmodels/setup_inspection.py +47 -70
  33. package/modules/localmodels/setup_inspection_harness.py +159 -15
  34. package/modules/localmodels/setup_text.py +14 -0
  35. package/modules/localmodels/setup_upgrade.py +1 -1
  36. package/modules/localmodels/source_byok.py +6 -2
  37. package/modules/localmodels/source_byok_probe.py +6 -1
  38. package/modules/localmodels/stack.py +9 -1
  39. package/modules/localmodels/stack_binding.py +3 -35
  40. package/modules/localmodels/stack_cleanup.py +4 -0
  41. package/modules/localmodels/stack_compose.py +18 -2
  42. package/modules/localmodels/stack_lifecycle.py +24 -1
  43. package/modules/localmodels/stack_plan.py +6 -2
  44. package/modules/localmodels/stack_ports.py +2 -0
  45. package/modules/localmodels/stack_remove.py +10 -1
  46. package/modules/localmodels/stack_up.py +33 -7
  47. package/modules/localmodels/stack_update.py +3 -1
  48. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.5.txt} +1 -1
  49. package/modules/localmodels/suite.py +43 -27
  50. package/modules/localmodels/transport.py +13 -2
  51. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/METADATA +1 -1
  52. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/RECORD +54 -53
  53. package/package.json +1 -1
  54. package/tool.json +1 -1
  55. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  56. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/WHEEL +0 -0
  57. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/entry_points.txt +0 -0
  58. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/NOTICE +0 -0
  59. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -109,7 +109,7 @@ def _start_windows(paths: dict[str, str]) -> None:
109
109
 
110
110
 
111
111
  def _previous_install(
112
- p: remote_ops.InstallParams, paths: dict[str, str]
112
+ p: remote_ops.ServiceParams, paths: dict[str, str]
113
113
  ) -> remote_ops.InstallParams:
114
114
  try:
115
115
  record = json.loads(remote_ops._read(paths["spec"]))
@@ -136,7 +136,10 @@ def _previous_install(
136
136
  raise RuntimeError(
137
137
  "cannot confirm who owns the existing deployment; config left unchanged"
138
138
  ) from exc
139
- return {**p, "argv": cast("list[str]", argv), "env": cast("dict[str, str]", env), "port": port}
139
+ return cast(
140
+ "remote_ops.InstallParams",
141
+ {**p, "argv": cast("list[str]", argv), "env": cast("dict[str, str]", env), "port": port},
142
+ )
140
143
 
141
144
 
142
145
  def _darwin_listener_pids(port: int) -> set[int] | None:
@@ -272,14 +275,15 @@ def _unit_property(unit: str, prop: str) -> str:
272
275
  return value
273
276
 
274
277
 
278
+ _FOREIGN_UNIT = "a systemd unit with this name belongs to another deployment"
279
+
280
+
275
281
  def _require_own_fragment(unit: str, paths: dict[str, str]) -> None:
276
282
  # The user manager loads a unit by name from its own search path, which need not
277
283
  # include the one HOME points at; a same-named unit there is another deployment's.
278
284
  fragment = _unit_property(unit, "FragmentPath")
279
285
  if fragment and Path(fragment).resolve() != Path(paths["unit"]).resolve():
280
- raise RuntimeError(
281
- "a systemd unit with this name belongs to another deployment; config left unchanged"
282
- )
286
+ raise RuntimeError(f"{_FOREIGN_UNIT}; config left unchanged")
283
287
 
284
288
 
285
289
  def _unit_not_loaded(unit: str) -> bool:
@@ -329,8 +333,13 @@ def _recorded_service(paths: dict[str, str]) -> str | None:
329
333
 
330
334
 
331
335
  def unit_runs_elsewhere(paths: dict[str, str]) -> bool:
332
- """The unit file of this name exists but runs another directory's run.sh: before unit names
333
- carried the root tag, two installs could share one name, and only one of them owns it."""
336
+ """The unit file of this name exists (or is a symlink) and does not run this directory's
337
+ run.sh: before unit names carried the root tag, two installs could share one name, and only
338
+ one of them owns it."""
339
+ if os.path.islink(paths["unit"]):
340
+ return True
341
+ if not os.path.exists(paths["unit"]):
342
+ return False
334
343
  try:
335
344
  text = remote_ops._read(paths["unit"])
336
345
  except OSError:
@@ -368,6 +377,8 @@ def _prepare_install(p: remote_ops.InstallParams, paths: dict[str, str]) -> None
368
377
  systemd = p["service_kind"] == "systemd-user"
369
378
  if systemd:
370
379
  _retire_renamed_unit(p, paths)
380
+ if unit_runs_elsewhere(paths):
381
+ raise RuntimeError(f"{_FOREIGN_UNIT}; config left unchanged")
371
382
  state = remote_ops._systemctl("is-active", p["service"] + ".service")[1] if systemd else ""
372
383
  pid = None if systemd else remote_ops._pid_alive(paths["pid"])
373
384
  if pid is not None:
@@ -376,9 +387,11 @@ def _prepare_install(p: remote_ops.InstallParams, paths: dict[str, str]) -> None
376
387
  pid = None
377
388
  if systemd and state not in ("active", "inactive", "failed", "unknown"):
378
389
  raise RuntimeError("the systemd service state is uncertain; config left unchanged")
379
- if systemd and state in ("inactive", "failed"):
390
+ if systemd and state in ("inactive", "failed", "unknown"):
380
391
  unit = p["service"] + ".service"
381
- if _unit_property(unit, "MainPID") != "0" or _unit_property(unit, "ControlGroup"):
392
+ if state in ("inactive", "failed") and (
393
+ _unit_property(unit, "MainPID") != "0" or _unit_property(unit, "ControlGroup")
394
+ ):
382
395
  raise RuntimeError("the systemd service still has processes; config left unchanged")
383
396
  _require_own_fragment(unit, paths)
384
397
  if state == "active" or pid is not None:
@@ -445,11 +458,32 @@ def act_install(p: remote_ops.InstallParams) -> None:
445
458
  remote_ops.emit("result", **{k: paths[k] for k in keys})
446
459
 
447
460
 
461
+ def _has_service_record(paths: dict[str, str]) -> bool:
462
+ if not os.path.isfile(paths["spec"]):
463
+ return False
464
+ try:
465
+ record = json.loads(remote_ops._read(paths["spec"]))
466
+ except (OSError, ValueError):
467
+ return True # unreadable or malformed spec still fails closed
468
+ return not (isinstance(record, dict) and not record)
469
+
470
+
471
+ def _foreign_systemd_unit(unit: str, paths: dict[str, str]) -> bool:
472
+ if unit_runs_elsewhere(paths):
473
+ return True
474
+ code, fragment = remote_ops._systemctl("show", "-p", "FragmentPath", "--value", unit)
475
+ return bool(
476
+ code == 0 and fragment and Path(fragment).resolve() != Path(paths["unit"]).resolve()
477
+ )
478
+
479
+
448
480
  def act_start(p: remote_ops.ServiceParams) -> None:
449
481
  paths, unit = remote_ops._paths(p), p["service"] + ".service"
450
482
  if remote_ops.receipts() and p["service_kind"] == "nohup":
451
483
  process_identity.require_owned(paths["pid"])
452
484
  systemd = p["service_kind"] == "systemd-user"
485
+ if systemd and unit_runs_elsewhere(paths):
486
+ raise RuntimeError(f"{_FOREIGN_UNIT}; not started")
453
487
  running = (
454
488
  remote_ops_launchd.status(p["deploy_dir"])[0] == "active"
455
489
  if p["service_kind"] == "launchd-user"
@@ -457,13 +491,23 @@ def act_start(p: remote_ops.ServiceParams) -> None:
457
491
  if systemd
458
492
  else remote_ops._pid_alive(paths["pid"])
459
493
  )
494
+ if (
495
+ not systemd
496
+ and p["service_kind"] != "launchd-user"
497
+ and running
498
+ and sys.platform.startswith("linux")
499
+ and _has_service_record(paths)
500
+ and not command_matches(int(running), _previous_install(p, paths)["argv"])
501
+ ):
502
+ raise RuntimeError("the existing PID does not belong to this deployment; not started")
460
503
  if not running and remote_ops._port_owner(p["port"]):
461
504
  raise RuntimeError(f"port {p['port']} is held by another process")
462
505
  if p["service_kind"] == "launchd-user":
463
506
  remote_ops_launchd.start(p["deploy_dir"])
464
507
  elif systemd:
465
- if not running:
466
- _require_own_fragment(unit, paths)
508
+ _require_own_fragment(unit, paths)
509
+ if running and not os.path.isfile(paths["unit"]):
510
+ raise RuntimeError(f"{_FOREIGN_UNIT}; not started")
467
511
  remote_ops._systemctl_ok("start", unit)
468
512
  elif not running and sys.platform == "win32":
469
513
  _start_windows(paths)
@@ -482,6 +526,35 @@ def act_start(p: remote_ops.ServiceParams) -> None:
482
526
  remote_ops.emit("result", started=True)
483
527
 
484
528
 
529
+ def _stop_nohup_verified(p: remote_ops.ServiceParams, paths: dict[str, str]) -> None:
530
+ pid = remote_ops._pid_alive(paths["pid"])
531
+ state = _process_state(pid) if pid is not None else None
532
+ if pid is not None and state and not (state == "Z" and not _group_members(pid)):
533
+ _stop_owned_group(pid, _previous_install(p, paths)["argv"])
534
+
535
+
536
+ def _stop_nohup_signals(paths: dict[str, str]) -> None:
537
+ # SIGKILL what SIGTERM leaves running: whisper-server b5454 can hang on SIGTERM.
538
+ for sig in (signal.SIGTERM, signal.SIGKILL):
539
+ if sys.platform == "darwin":
540
+ process_identity.require_owned(paths["pid"])
541
+ pid, deadline = (
542
+ remote_ops._pid_alive(paths["pid"]),
543
+ time.monotonic() + remote_ops.STOP_GRACE_S,
544
+ )
545
+ if pid is not None:
546
+ try:
547
+ os.killpg(pid, sig)
548
+ except ProcessLookupError: # it exited after the check: stopped, as wanted
549
+ pid = None
550
+ while (
551
+ pid is not None and remote_ops._pid_alive(paths["pid"]) and time.monotonic() < deadline
552
+ ):
553
+ time.sleep(0.2)
554
+ if remote_ops._pid_alive(paths["pid"]):
555
+ raise RuntimeError("the service process is still running after SIGKILL")
556
+
557
+
485
558
  def act_stop(p: remote_ops.ServiceParams) -> None:
486
559
  paths = remote_ops._paths(p)
487
560
  if remote_ops.receipts() and p["service_kind"] == "nohup":
@@ -502,28 +575,10 @@ def act_stop(p: remote_ops.ServiceParams) -> None:
502
575
  pass
503
576
  elif remote_ops._systemctl("stop", unit)[0]:
504
577
  raise RuntimeError("systemctl could not stop the service")
578
+ elif sys.platform.startswith("linux") and _has_service_record(paths):
579
+ _stop_nohup_verified(p, paths)
505
580
  else:
506
- # SIGKILL what SIGTERM leaves running: whisper-server b5454 can hang on SIGTERM.
507
- for sig in (signal.SIGTERM, signal.SIGKILL):
508
- if sys.platform == "darwin":
509
- process_identity.require_owned(paths["pid"])
510
- pid, deadline = (
511
- remote_ops._pid_alive(paths["pid"]),
512
- time.monotonic() + remote_ops.STOP_GRACE_S,
513
- )
514
- if pid is not None:
515
- try:
516
- os.killpg(pid, sig)
517
- except ProcessLookupError: # it exited after the check: stopped, as wanted
518
- pid = None
519
- while (
520
- pid is not None
521
- and remote_ops._pid_alive(paths["pid"])
522
- and time.monotonic() < deadline
523
- ):
524
- time.sleep(0.2)
525
- if remote_ops._pid_alive(paths["pid"]):
526
- raise RuntimeError("the service process is still running after SIGKILL")
581
+ _stop_nohup_signals(paths)
527
582
  remote_ops.emit("result", stopped=True)
528
583
 
529
584
 
@@ -652,11 +707,13 @@ def act_status(p: remote_ops.ServiceParams) -> None:
652
707
  if p["service_kind"] == "launchd-user":
653
708
  state, pid = remote_ops_launchd.status(p["deploy_dir"])
654
709
  elif p["service_kind"] == "systemd-user":
655
- _, state = remote_ops._systemctl("is-active", p["service"] + ".service")
710
+ unit = p["service"] + ".service"
711
+ if _foreign_systemd_unit(unit, paths):
712
+ remote_ops.emit("result", state="inactive", health=f"{_FOREIGN_UNIT}, not probed")
713
+ return
714
+ _, state = remote_ops._systemctl("is-active", unit)
656
715
  if state == "active":
657
- _, number = remote_ops._systemctl(
658
- "show", "-p", "MainPID", "--value", p["service"] + ".service"
659
- )
716
+ _, number = remote_ops._systemctl("show", "-p", "MainPID", "--value", unit)
660
717
  pid = int(number) if number.isdigit() and int(number) > 0 else None
661
718
  elif remote_ops.receipts():
662
719
  state, pid = process_identity.status(paths["pid"])
@@ -28,6 +28,7 @@ from localmodels.runtime_io import (
28
28
  )
29
29
 
30
30
  MAX_CONTEXT_WINDOW = 2_147_483_647
31
+ _USER_AGENT = "localmodels-auth"
31
32
 
32
33
 
33
34
  def model_config(profile: Path, owned: dict[str, str]) -> dict[str, Any] | None:
@@ -292,6 +293,7 @@ def _verify_config(value: dict[str, Any]) -> None:
292
293
  else:
293
294
  url, data = "https://api.anthropic.com/v1/models", None
294
295
  headers = {"x-api-key": key, "anthropic-version": "2023-06-01"}
296
+ headers["User-Agent"] = _USER_AGENT
295
297
  try:
296
298
  request = urllib.request.Request(url, data=data, headers=headers)
297
299
  with urllib.request.build_opener(http_local.NoRedirectHandler()).open(
@@ -380,7 +382,8 @@ def _endpoint_metadata(value: dict[str, Any]) -> tuple[int, bool]:
380
382
  for url in (base.removesuffix("/v1") + "/props", base + "/models"):
381
383
  try:
382
384
  request = urllib.request.Request(
383
- url, headers={"Authorization": "Bearer " + value["apiKey"]}
385
+ url,
386
+ headers={"Authorization": "Bearer " + value["apiKey"], "User-Agent": _USER_AGENT},
384
387
  )
385
388
  with opener.open(request, timeout=5) as response:
386
389
  if response.status != 200:
@@ -2,16 +2,36 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import contextlib
5
6
  import copy
6
7
  import json
7
8
  import os
8
9
  import platform
9
10
  from pathlib import Path
11
+ from typing import Any
10
12
  from urllib.parse import urlsplit
11
13
 
12
- from localmodels import gateway, gateway_keys, harness, harness_gateway, hosts, stack
14
+ from localmodels import (
15
+ bifrost_config,
16
+ bifrost_provider,
17
+ gateway,
18
+ gateway_bifrost,
19
+ gateway_keys,
20
+ harness,
21
+ harness_gateway,
22
+ hosts,
23
+ library_convert,
24
+ library_gateway,
25
+ library_model,
26
+ library_serve,
27
+ library_state,
28
+ source_byok,
29
+ stack,
30
+ )
13
31
  from localmodels.gateway import AuxEndpoint
32
+ from localmodels.records import Plan
14
33
  from localmodels.service_jobs import ServiceJobs
34
+ from localmodels.stack_plan import StackPlan
15
35
 
16
36
 
17
37
  def planned_gateway(root: Path, binding: dict[str, str] | None = None) -> harness.ToolPlan:
@@ -73,10 +93,211 @@ def auxiliary_endpoints(bindings: dict[str, dict[str, str]]) -> list[AuxEndpoint
73
93
  ]
74
94
 
75
95
 
96
+ def _library_stack_active(plan: StackPlan) -> bool:
97
+ """Whether every stack LLM in ``plan`` is actively loaded as a converted stack member."""
98
+ parts: list[tuple[Plan, str]] = [(plan["llm"], plan["harness"]["gateway"]["llm_provider"])]
99
+ if fast := plan.get("llm_fast"):
100
+ parts.append((fast, bifrost_config.FAST_PROVIDER))
101
+ for part, expected_provider in parts:
102
+ mid = library_model.library_id(part["model"]["id"], part["model"]["quant"])
103
+ if library_state.job_alive(mid):
104
+ job = library_state.read_job(mid)
105
+ if job is not None and job.get("kind") in ("unload", "remove", "load"):
106
+ return False
107
+ record = library_state.load(mid)
108
+ if record is None or record.get("state") != "loaded":
109
+ return False
110
+ if library_serve.stack_member(record) != expected_provider:
111
+ return False
112
+ reg = record.get("registration")
113
+ if reg is not None and reg.get("kind") not in ("stack", "agent"):
114
+ return False
115
+ return True
116
+
117
+
118
+ def _stack_llm_active(plan: StackPlan) -> bool:
119
+ """Whether ``plan``'s local stack LLM is still active and selected as the model source."""
120
+ try:
121
+ source = source_byok.load_source_state()
122
+ except (OSError, ValueError, source_byok.ByokError):
123
+ source = None
124
+ if source is not None and source["mode"] != "local":
125
+ return False
126
+
127
+ if library_convert.initialized() and not _library_stack_active(plan):
128
+ return False
129
+
130
+ owned_file = hosts.owned_path(plan["harness"]["tools_dir"])
131
+ if owned_file.is_file():
132
+ try:
133
+ owned = hosts.load_owned(plan["harness"]["tools_dir"])
134
+ except (OSError, ValueError):
135
+ owned = None
136
+ if owned is not None:
137
+ entry = owned["deployments"].get(plan["llm"]["name"])
138
+ if entry is not None and entry.get("removed"):
139
+ return False
140
+ key_file = Path(os.path.expanduser(plan["llm"]["service"]["deploy_dir"]), "api-key")
141
+ if entry is None and not key_file.is_file():
142
+ return False
143
+ return True
144
+
145
+
146
+ def _owned_bifrost(tools_dir: str) -> hosts.OwnedBifrost | None:
147
+ """Find an owned Bifrost record from ``tools_dir`` or the default library/BYOK tools root."""
148
+ for candidate in dict.fromkeys((tools_dir, hosts.tools_dir())):
149
+ try:
150
+ record = hosts.load_owned(candidate)["gateway"].get("bifrost")
151
+ except (OSError, ValueError):
152
+ continue
153
+ if record is not None:
154
+ return record
155
+ return None
156
+
157
+
158
+ def _bifrost_needs_inactive_sync(config: dict[str, Any], decision_provider: str) -> bool:
159
+ """Whether an on-disk Bifrost config has stale foundation providers or needs governance repair."""
160
+ providers = config.get("providers")
161
+ foundation_ids = {
162
+ decision_provider,
163
+ bifrost_config.AUX_PROVIDERS["embedding"],
164
+ bifrost_config.AUX_PROVIDERS["rerank"],
165
+ }
166
+ if isinstance(providers, dict) and foundation_ids.intersection(providers):
167
+ return True
168
+ return bifrost_config.sanitize_governance(copy.deepcopy(config))
169
+
170
+
171
+ def _sync_bifrost_foundations(
172
+ record: hosts.OwnedBifrost,
173
+ tools_plan: harness.HarnessPlan,
174
+ bindings: dict[str, dict[str, str]],
175
+ ) -> str | None:
176
+ """Update only foundation providers in an existing owned Bifrost without touching LLM routes.
177
+
178
+ Returns the gateway address while Bifrost remains active, or None when absent or stopped.
179
+ """
180
+ with library_gateway.gateway_locked():
181
+ app = Path(record["app_dir"])
182
+ config = gateway_bifrost.read_config(app)
183
+ if not config:
184
+ return None
185
+ providers = config.setdefault("providers", {})
186
+ decision_pid = tools_plan["gateway"]["decision_provider"]
187
+ if decision := bindings.get("decision"):
188
+ providers[decision_pid] = bifrost_provider.render(
189
+ "decision", decision["baseUrl"], decision["model"], decision["key"], decision_pid
190
+ )
191
+ else:
192
+ providers.pop(decision_pid, None)
193
+ desired_aux: set[str] = set()
194
+ for ep in auxiliary_endpoints(bindings):
195
+ pid = bifrost_config.AUX_PROVIDERS.get(str(ep.get("contract")))
196
+ if pid:
197
+ desired_aux.add(pid)
198
+ providers[pid] = bifrost_provider.render(
199
+ str(ep["contract"]), str(ep["url"]), str(ep["model"]), str(ep["key"]), pid
200
+ )
201
+ for contract in ("embedding", "rerank"):
202
+ pid = bifrost_config.AUX_PROVIDERS[contract]
203
+ if pid not in desired_aux:
204
+ providers.pop(pid, None)
205
+ bifrost_config.sanitize_governance(config)
206
+ library_gateway.apply_config(record, config, library_gateway.read_sheet(app))
207
+ return record["addr"] if config.get("providers") else None
208
+
209
+
76
210
  class Wiring:
77
211
  def __init__(self) -> None:
78
212
  self.last: object = None
79
213
 
214
+ def _sync_inactive_bifrost(
215
+ self,
216
+ signature: object,
217
+ record: hosts.OwnedBifrost | None,
218
+ config_doc: dict[str, Any],
219
+ tools_plan: harness.HarnessPlan,
220
+ bindings: dict[str, dict[str, str]],
221
+ had_bindings: bool,
222
+ jobs: ServiceJobs,
223
+ ) -> None:
224
+ if record is None or not config_doc:
225
+ if not bindings:
226
+ if had_bindings:
227
+ jobs.set_gateway(None)
228
+ self.last = copy.deepcopy(signature)
229
+ return
230
+ decision_pid = tools_plan["gateway"]["decision_provider"]
231
+ if (
232
+ not bindings
233
+ and not had_bindings
234
+ and not _bifrost_needs_inactive_sync(config_doc, decision_pid)
235
+ ):
236
+ self.last = copy.deepcopy(signature)
237
+ return
238
+ addr = _sync_bifrost_foundations(record, tools_plan, bindings)
239
+ if addr is None:
240
+ jobs.set_gateway(None)
241
+ else:
242
+ set_gateway_binding(jobs, addr, "bifrost")
243
+ self.last = copy.deepcopy(signature)
244
+
245
+ def _sync_inactive_magpie(
246
+ self,
247
+ signature: object,
248
+ tools_plan: harness.HarnessPlan,
249
+ kind: str,
250
+ bindings: dict[str, dict[str, str]],
251
+ had_bindings: bool,
252
+ jobs: ServiceJobs,
253
+ ) -> None:
254
+ decision_pid = tools_plan["gateway"]["decision_provider"]
255
+ managed = {*gateway.FOUNDATION_PROVIDERS, decision_pid}
256
+ if not bindings and not had_bindings:
257
+ owned_providers = hosts.load_owned(tools_plan["tools_dir"])["gateway"]["providers"]
258
+ if not managed.intersection(owned_providers):
259
+ self.last = copy.deepcopy(signature)
260
+ return
261
+ decision = bindings.get("decision")
262
+ gateway.wire_foundations(
263
+ tools_plan,
264
+ {"url": decision["baseUrl"], "model": decision["model"]} if decision else None,
265
+ decision["key"] if decision else None,
266
+ auxiliary_endpoints(bindings),
267
+ decision_provider=decision_pid,
268
+ )
269
+ if bindings:
270
+ set_gateway_binding(jobs, tools_plan["gateway"]["addr"], kind)
271
+ else:
272
+ jobs.set_gateway(None)
273
+ self.last = copy.deepcopy(signature)
274
+
275
+ def _sync_inactive(
276
+ self,
277
+ main_plan: Path,
278
+ plan_id: str,
279
+ tools_plan: harness.HarnessPlan,
280
+ kind: str,
281
+ bindings: dict[str, dict[str, str]],
282
+ jobs: ServiceJobs,
283
+ ) -> None:
284
+ signature: object = ("inactive", str(main_plan), plan_id, bindings)
285
+ if self.last == signature:
286
+ return
287
+ had_bindings = isinstance(self.last, tuple) and bool(self.last[-1])
288
+ bifrost_record = _owned_bifrost(tools_plan["tools_dir"])
289
+ bifrost_doc = (
290
+ gateway_bifrost.read_config(Path(bifrost_record["app_dir"]))
291
+ if bifrost_record is not None
292
+ else {}
293
+ )
294
+ if kind == "bifrost" or bifrost_doc:
295
+ self._sync_inactive_bifrost(
296
+ signature, bifrost_record, bifrost_doc, tools_plan, bindings, had_bindings, jobs
297
+ )
298
+ return
299
+ self._sync_inactive_magpie(signature, tools_plan, kind, bindings, had_bindings, jobs)
300
+
80
301
  def sync(self, main_plan: Path | None, jobs: ServiceJobs) -> None:
81
302
  bindings = jobs.bindings()
82
303
  if main_plan is None:
@@ -114,24 +335,29 @@ class Wiring:
114
335
  ready = json.loads(receipt.read_text())
115
336
  if not ready.get("ready") or ready.get("planId") != plan["plan_id"]:
116
337
  return
338
+ tools_plan = copy.deepcopy(plan["harness"])
339
+ kind = harness.gateway_kind(tools_plan["gateway"])
340
+ if not _stack_llm_active(plan):
341
+ self._sync_inactive(main_plan, plan["plan_id"], tools_plan, kind, bindings, jobs)
342
+ return
117
343
  signature = (str(main_plan), plan["plan_id"], receipt.stat().st_mtime_ns, bindings)
118
344
  if self.last == signature:
119
345
  return
120
- tools_plan = copy.deepcopy(plan["harness"])
121
346
  decision = bindings.get("decision")
122
347
  tools_plan["gateway"]["decision"] = (
123
348
  {"url": decision["baseUrl"], "model": decision["model"]} if decision else None
124
349
  )
125
350
  aux = auxiliary_endpoints(bindings)
126
351
  # Only update the owned routing group. Never replace a user's current Pi selection.
127
- gateway.wire(
128
- tools_plan,
129
- stack.service_key(plan["llm"]),
130
- decision["key"] if decision else None,
131
- aux,
132
- select_pi=False,
133
- )
134
- set_gateway_binding(
135
- jobs, tools_plan["gateway"]["addr"], harness.gateway_kind(tools_plan["gateway"])
136
- )
352
+ with library_gateway.gateway_locked() if kind == "bifrost" else contextlib.nullcontext():
353
+ if kind == "bifrost" and not _stack_llm_active(plan):
354
+ return
355
+ gateway.wire(
356
+ tools_plan,
357
+ stack.service_key(plan["llm"]),
358
+ decision["key"] if decision else None,
359
+ aux,
360
+ select_pi=False,
361
+ )
362
+ set_gateway_binding(jobs, tools_plan["gateway"]["addr"], kind)
137
363
  self.last = copy.deepcopy(signature)