@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
@@ -10,7 +10,7 @@ import json
10
10
  import os
11
11
  import secrets
12
12
  from collections.abc import Callable
13
- from dataclasses import dataclass
13
+ from dataclasses import dataclass, replace
14
14
 
15
15
  from localmodels import catalog as cat
16
16
  from localmodels import (
@@ -24,15 +24,6 @@ from localmodels import (
24
24
  stack_debug,
25
25
  vision,
26
26
  )
27
- from localmodels.budget import (
28
- Placement,
29
- agent_budget,
30
- cpu_placement,
31
- gib,
32
- launch_budget,
33
- placements,
34
- unknown_services,
35
- )
36
27
  from localmodels.context_policy import (
37
28
  DEFAULT_UBATCH,
38
29
  RUNTIME_OVERHEAD_BYTES,
@@ -70,6 +61,15 @@ from localmodels.plan_envelope import (
70
61
  utc_now,
71
62
  )
72
63
  from localmodels.plan_envelope import plan_envelope as build_plan_envelope
64
+ from localmodels.planning.budget import (
65
+ Placement,
66
+ agent_budget,
67
+ cpu_placement,
68
+ gib,
69
+ launch_budget,
70
+ placements,
71
+ unknown_services,
72
+ )
73
73
  from localmodels.probe import HostFacts
74
74
  from localmodels.records import (
75
75
  FinishedRecord,
@@ -319,6 +319,54 @@ def _companion_args(
319
319
  return args
320
320
 
321
321
 
322
+ def drafter_engine_ok(
323
+ spec: draft_spec.DraftSpec, build: str | None, commit: str | None = None
324
+ ) -> bool:
325
+ """Whether llama.cpp ``build`` accepts the drafter's ``--spec-type``: at least its
326
+ ``min_engine`` release, from the same fork (``b12757-mix-…`` needs a ``mix`` build), or a
327
+ reused engine that is ``min_engine`` itself: probe reads only ``b12757`` and a commit from
328
+ ``--version``, so the commit must be the lock's pinned one or the tag's own suffix."""
329
+ if not spec.min_engine:
330
+ return True
331
+ have, need = cat.build_number(build), cat.build_number(spec.min_engine)
332
+ if have is None or need is None or have < need:
333
+ return False
334
+ tag_commit = spec.min_engine.split("-")[-1] if spec.min_engine.count("-") >= 2 else None
335
+ if commit_matches(engine_lock_commit(spec.min_engine), commit) or commit_matches(
336
+ tag_commit, commit
337
+ ):
338
+ return True
339
+ fork = spec.min_engine.split("-")[1:2]
340
+ return not fork or str(build).split("-")[1:2] == fork
341
+
342
+
343
+ def asset_dest(base_dir: str, local_name: str) -> str:
344
+ """Where a plan keeps a companion file (projector, drafter, MTP head) under ``base_dir``."""
345
+ return f"{base_dir.rstrip('/')}/models/assets/{local_name}"
346
+
347
+
348
+ def drafter_in_place(entry: cat.CatalogEntry, base_dir: str) -> bool:
349
+ """Whether ``entry``'s optional external drafter is under ``base_dir`` with the catalog's
350
+ pinned bytes (its SHA256 receipt). A library load plans the drafter only then: it is an
351
+ accelerator, so a model downloaded before its drafter shipped (Inkling 2 Mini before dev64),
352
+ or one whose drafter fails verification, loads without speculation instead of failing."""
353
+ asset = entry.draft
354
+ if asset is None or asset.sha256 is None:
355
+ return False
356
+ pinned = catalog_pins([(asset.repo or entry.repo, asset)], "")[0]
357
+ planned: ReusableFile = {
358
+ "repo": pinned["repo"],
359
+ "path": pinned["path"],
360
+ "revision": pinned["revision"],
361
+ "size_bytes": pinned["size_bytes"],
362
+ "sha256": pinned["sha256"],
363
+ "local_name": pinned["local_name"],
364
+ "url": "",
365
+ "dest": asset_dest(base_dir, pinned["local_name"]),
366
+ }
367
+ return plan_envelope.verified_in_place(planned)
368
+
369
+
322
370
  def build_plan(
323
371
  host_id: str,
324
372
  facts: HostFacts,
@@ -339,7 +387,7 @@ def build_plan(
339
387
  warnings: list[str] = []
340
388
 
341
389
  base = options.base_dir.rstrip("/")
342
- models_dir, assets_dir = f"{base}/models", f"{base}/models/assets"
390
+ models_dir = f"{base}/models"
343
391
  reader = decision.vision_reader if options.agent else "gpu" if entry.mmproj else "off"
344
392
  mmproj = entry.mmproj if reader != "off" else None
345
393
  draft = entry.draft if options.agent is not None and decision.draft_n_max > 0 else None
@@ -360,7 +408,7 @@ def build_plan(
360
408
  "dest": (
361
409
  f"{models_dir}/{f['local_name']}"
362
410
  if f["path"] in model_names or f["local_name"].startswith("custom/")
363
- else f"{assets_dir}/{f['local_name']}"
411
+ else asset_dest(base, f["local_name"])
364
412
  ),
365
413
  "url": hub_url(options.hf_download_endpoint, f["repo"], f["revision"], f["path"]),
366
414
  }
@@ -421,6 +469,34 @@ def build_plan(
421
469
  elif placement.backend == "metal":
422
470
  argv += ["--device", "MTL0"]
423
471
  engine = engine_plan(facts, options, entry, placement.backend, warnings, argv)
472
+ if (
473
+ draft is not None
474
+ and options.agent is not None
475
+ and entry.draft_spec is not None
476
+ and not drafter_engine_ok(
477
+ entry.draft_spec,
478
+ engine.get("build"),
479
+ next(
480
+ (e.get("commit") for e in facts["engines"] if e["path"] == engine["binary"]),
481
+ None,
482
+ ),
483
+ )
484
+ ):
485
+ # The drafter was priced before the engine was known; plan again without it.
486
+ plan = build_plan(
487
+ host_id,
488
+ facts,
489
+ replace(options, agent=replace(options.agent, draft="off")),
490
+ entries,
491
+ resolver,
492
+ )
493
+ plan["warnings"] = [
494
+ f"speculation: the {entry.draft_spec.spec_type} drafter needs llama.cpp "
495
+ f"{entry.draft_spec.min_engine} or newer; engine {engine.get('build') or 'unknown'} "
496
+ "runs without it",
497
+ *plan["warnings"],
498
+ ]
499
+ return plan
424
500
  argv[0] = engine["binary"]
425
501
 
426
502
  gpus = {g["index"]: g for g in facts.get("gpus") or []}
@@ -0,0 +1,167 @@
1
+ """One owned deployment's lifecycle: the phases its manifest entry moves through, and the service
2
+ states ``stack up`` starts and ``stack down`` stops.
3
+
4
+ The owned manifest (``hosts.Owned["deployments"]``) keeps one entry per deployment name. Its
5
+ phase is read from two stored flags, written only by ``advance``:
6
+
7
+ ========= =====================================================================================
8
+ ABSENT no entry: never installed on this computer, or purged
9
+ LIVE installed and verified (``removed`` false, no ``failed`` flag)
10
+ FAILED recorded from a failed or interrupted deploy (``failed`` true); its service may exist,
11
+ but it never blocks a live owner of the same port, unit or name
12
+ REMOVED service and directory are gone (``removed`` true); its model files and log stay
13
+ until a purge. ``removed`` wins over ``failed``: a failed deployment that was
14
+ removed keeps its ``failed`` flag, as manifests written before this module did
15
+ ========= =====================================================================================
16
+
17
+ ``TRANSITIONS`` is total: every phase accepts every event, so a retried remove or purge, or a
18
+ deploy over any earlier phase, is safe. Purging drops only the manifest entry. The permanent
19
+ empty lock files ``tools/owned.lock`` (WHI-317) and ``engines/.engine.lock`` (WHI-759) are not
20
+ deployment state and stay after a purge (``stack_cleanup.tidy``).
21
+
22
+ A service's state word (``stack_lifecycle.liveness``: systemd ``ActiveState``, launchd or pid
23
+ state) is RUNNING (``active``), DOWN (``inactive``, ``failed``, ``dead``: no process to stop),
24
+ or SETTLING (anything else, ``activating``, ``unknown``...). ``stack up`` starts what is not
25
+ RUNNING and ``stack down`` stops what is not DOWN, so both act on a SETTLING service.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import enum
31
+ import os
32
+ from collections.abc import Mapping, MutableMapping
33
+ from dataclasses import dataclass
34
+ from typing import Any, Final
35
+
36
+
37
+ class Phase(enum.Enum):
38
+ ABSENT = "absent"
39
+ LIVE = "live"
40
+ FAILED = "failed"
41
+ REMOVED = "removed"
42
+
43
+
44
+ class Event(enum.Enum):
45
+ DEPLOYED = "deployed" # hosts.own_deployment(ok=True)
46
+ DEPLOY_FAILED = "deploy-failed" # hosts.own_deployment(ok=False)
47
+ REMOVE = "remove" # service and directory deleted; model files kept (delete_record)
48
+ PURGE = "purge" # nothing kept (delete_record(purged=True))
49
+
50
+
51
+ TRANSITIONS: Final[Mapping[tuple[Phase, Event], Phase]] = {
52
+ **{(phase, Event.DEPLOYED): Phase.LIVE for phase in Phase},
53
+ **{(phase, Event.DEPLOY_FAILED): Phase.FAILED for phase in Phase},
54
+ (Phase.ABSENT, Event.REMOVE): Phase.ABSENT, # nothing recorded, nothing to keep
55
+ (Phase.LIVE, Event.REMOVE): Phase.REMOVED,
56
+ (Phase.FAILED, Event.REMOVE): Phase.REMOVED,
57
+ (Phase.REMOVED, Event.REMOVE): Phase.REMOVED,
58
+ **{(phase, Event.PURGE): Phase.ABSENT for phase in Phase},
59
+ }
60
+
61
+
62
+ class LifecycleError(ValueError):
63
+ """An event the lifecycle has no transition for."""
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class DeploymentLifecycle:
68
+ """One deployment's manifest phase and the transitions it allows."""
69
+
70
+ phase: Phase
71
+
72
+ @classmethod
73
+ def of(cls, entry: Mapping[str, Any] | None) -> DeploymentLifecycle:
74
+ return cls(phase_of(entry))
75
+
76
+ def on(self, event: Event) -> DeploymentLifecycle:
77
+ try:
78
+ return DeploymentLifecycle(TRANSITIONS[self.phase, event])
79
+ except KeyError:
80
+ raise LifecycleError(f"{event.value} is not allowed while {self.phase.value}") from None
81
+
82
+
83
+ def phase_of(entry: Mapping[str, Any] | None) -> Phase:
84
+ if entry is None:
85
+ return Phase.ABSENT
86
+ if entry["removed"]:
87
+ return Phase.REMOVED
88
+ return Phase.FAILED if entry.get("failed") else Phase.LIVE
89
+
90
+
91
+ def is_live(entry: Mapping[str, Any] | None) -> bool:
92
+ """A verified owner: the only phase that holds its name, port and unit against others."""
93
+ return phase_of(entry) is Phase.LIVE
94
+
95
+
96
+ def holds_service(entry: Mapping[str, Any] | None) -> bool:
97
+ """Recorded and not yet removed: its service, directory and model files may be in use."""
98
+ return phase_of(entry) in (Phase.LIVE, Phase.FAILED)
99
+
100
+
101
+ def is_removed(entry: Mapping[str, Any] | None) -> bool:
102
+ """Removed with its model files kept; only a purge clears it."""
103
+ return phase_of(entry) is Phase.REMOVED
104
+
105
+
106
+ def advance(
107
+ deployments: MutableMapping[str, Any],
108
+ name: str,
109
+ event: Event,
110
+ entry: Mapping[str, Any] | None = None,
111
+ ) -> Phase:
112
+ """Apply ``event`` to the manifest entry ``name`` in ``deployments`` and return the new phase.
113
+ A deploy event stores ``entry`` (``hosts.owned_entry``), marking it failed for
114
+ DEPLOY_FAILED; remove and purge change the entry already there."""
115
+ current = deployments.get(name)
116
+ target = DeploymentLifecycle.of(current).on(event).phase
117
+ if event in (Event.DEPLOYED, Event.DEPLOY_FAILED):
118
+ if entry is None:
119
+ raise LifecycleError(f"{event.value} needs the deployment's manifest entry")
120
+ deployments[name] = {**entry, "failed": True} if target is Phase.FAILED else entry
121
+ elif target is Phase.ABSENT:
122
+ deployments.pop(name, None)
123
+ elif target is Phase.REMOVED and current is not None:
124
+ current["removed"] = True
125
+ return target
126
+
127
+
128
+ def same_dir(a: str, b: str) -> bool:
129
+ """Whether two deployment directories are one place: a manifest entry belongs to the
130
+ deployment whose directory resolves to its own."""
131
+
132
+ def norm(path: str) -> str:
133
+ return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
134
+
135
+ return norm(a) == norm(b)
136
+
137
+
138
+ # ---------------------------------------------------------------------------- service start/stop
139
+
140
+
141
+ class Service(enum.Enum):
142
+ RUNNING = "running"
143
+ DOWN = "down"
144
+ SETTLING = "settling"
145
+
146
+
147
+ DOWN_STATES: Final = ("inactive", "failed", "dead") # service states with no process to stop
148
+
149
+
150
+ def service(state: str) -> Service:
151
+ if state == "active":
152
+ return Service.RUNNING
153
+ return Service.DOWN if state in DOWN_STATES else Service.SETTLING
154
+
155
+
156
+ def needs_start(state: str) -> bool:
157
+ """``stack up`` starts every service that is not running."""
158
+ return service(state) is not Service.RUNNING
159
+
160
+
161
+ def needs_stop(state: str) -> bool:
162
+ """``stack down`` stops every service that may still have a process."""
163
+ return service(state) is not Service.DOWN
164
+
165
+
166
+ def healthy(state: str, health: str) -> bool:
167
+ return service(state) is Service.RUNNING and health in ("ok", "ready")
@@ -5,7 +5,10 @@ separate pinned GGUF paired with ``--model-draft``, ``--spec-type``, and ``--spe
5
5
  It is strictly headroom-gated: admitted only after window, KV precision, slots, ubatch, and GPU
6
6
  vision are chosen, and only when the device still keeps ``METAL_DRAFT_HEADROOM_BYTES`` free. It
7
7
  never degrades context length, KV precision, or vision, and never passes ``-devd`` (DSpark borrows
8
- the target model's embeddings and LM head)."""
8
+ the target model's embeddings and LM head). Two later gates can still leave it off: deploy drops it
9
+ on an engine older than ``DraftSpec.min_engine`` (deploy.drafter_engine_ok), and the stack drops it
10
+ when, on unified memory, it would leave ``--cache-ram`` below the full prompt cache
11
+ (planning.llm_ram.drafter_costs_cache)."""
9
12
 
10
13
  from __future__ import annotations
11
14
 
@@ -19,6 +22,7 @@ from localmodels.context_policy import (
19
22
  WindowDecision,
20
23
  )
21
24
  from localmodels.estimator import HardwareBudget
25
+ from localmodels.records import Plan
22
26
 
23
27
  GIB = 1 << 30
24
28
  # Spare device budget kept before enabling an optional Metal drafter (matches Metal ubatch).
@@ -38,6 +42,9 @@ class DraftSpec:
38
42
  kv_bytes_per_token: int # full-attention KV bytes/token at q8_0/q8_0
39
43
  kv_swa_bytes: int = 0 # fixed sliding-window KV bytes
40
44
  backends: tuple[str, ...] = ("metal",)
45
+ # Oldest llama.cpp build that accepts ``spec_type`` ("" = any); deploy omits the drafter on an
46
+ # older or different-fork engine (b12588-mix has no draft-dspark).
47
+ min_engine: str = ""
41
48
 
42
49
 
43
50
  def device_bytes(spec: DraftSpec, window: int, kv_types: tuple[str, str]) -> int:
@@ -63,6 +70,9 @@ def llama_args(path: str, spec_type: str, n_max: int) -> list[str]:
63
70
  ]
64
71
 
65
72
 
73
+ _LAUNCH_KEYS = ("draft_type", "draft_n_max", "draft_bytes")
74
+
75
+
66
76
  def launch_keys(decision: WindowDecision) -> dict[str, object]:
67
77
  """Plan ``launch`` keys emitted only when an optional drafter is active."""
68
78
  if decision.draft_n_max <= 0 or not decision.draft_type:
@@ -80,6 +90,38 @@ def active(launch: Mapping[str, object]) -> bool:
80
90
  return isinstance(raw, int) and not isinstance(raw, bool) and raw > 0
81
91
 
82
92
 
93
+ def drafter_dest(plan: Plan) -> str | None:
94
+ """The file an active external drafter runs from (its ``--model-draft``), else None. A plan
95
+ still starts without it: ``without_drafter`` drops the drafter and its flags."""
96
+ argv = plan["service"]["argv"]
97
+ if not active(plan["launch"]) or "--model-draft" not in argv[:-1]:
98
+ return None
99
+ return argv[argv.index("--model-draft") + 1]
100
+
101
+
102
+ def without_drafter(plan: Plan) -> Plan:
103
+ """``plan`` with its external drafter left out: no drafter file, flags, or ``draft_*`` launch
104
+ keys. The model runs unchanged, only without speculation; the memory figures stay as priced
105
+ (with the drafter), an overestimate."""
106
+ dest = drafter_dest(plan)
107
+ if dest is None:
108
+ return plan
109
+ argv = plan["service"]["argv"]
110
+ at = argv.index("--model-draft")
111
+ kept = argv[:at] + argv[at + 2 :]
112
+ for flag in ("--spec-type", "--spec-draft-n-max"):
113
+ if flag in kept[:-1]:
114
+ i = kept.index(flag)
115
+ kept = kept[:i] + kept[i + 2 :]
116
+ launch = {k: v for k, v in plan["launch"].items() if k not in _LAUNCH_KEYS}
117
+ return {
118
+ **plan,
119
+ "files": [f for f in plan["files"] if f["dest"] != dest],
120
+ "service": {**plan["service"], "argv": kept},
121
+ "launch": launch,
122
+ }
123
+
124
+
83
125
  def priced(
84
126
  spec: DraftSpec | None,
85
127
  planned: LaunchPlan,
@@ -19,6 +19,7 @@ from pathlib import Path
19
19
  from typing import Literal, TypedDict
20
20
 
21
21
  from localmodels import (
22
+ bifrost_checks,
22
23
  bifrost_clients,
23
24
  gateway_accept,
24
25
  gateway_admin,
@@ -30,6 +31,7 @@ from localmodels import (
30
31
  harness_gateway,
31
32
  harness_probe,
32
33
  hosts,
34
+ magpie_legacy,
33
35
  pi_profile,
34
36
  process_identity,
35
37
  runtime_io,
@@ -91,14 +93,12 @@ def require_magpie(out: subprocess.CompletedProcess[str], what: str) -> None:
91
93
  raise HarnessError(f"magpie {what} failed (exit {out.returncode})")
92
94
 
93
95
 
94
- def _bifrost(plan: ToolPlan) -> bool:
95
- return harness_core.gateway_kind(plan.get("gateway")) == "bifrost" # type: ignore[arg-type]
96
-
97
-
98
96
  def ensure_gateway(plan: ToolPlan) -> str:
99
97
  """Reuse a gateway that answers; otherwise start the one the plan names."""
100
- if _bifrost(plan):
101
- return gateway_bifrost.ensure(plan)
98
+ return _gateway(plan).ensure(plan)
99
+
100
+
101
+ def _ensure_magpie(plan: ToolPlan) -> str:
102
102
  action = next(t for t in plan["tools"] if t["tool"] == "gateway")
103
103
  if run_magpie(plan, "healthcheck", timeout=20).returncode == 0:
104
104
  return "reused"
@@ -112,10 +112,29 @@ def ensure_gateway(plan: ToolPlan) -> str:
112
112
  return "started"
113
113
 
114
114
 
115
+ def answers(plan: HarnessPlan) -> bool:
116
+ """The plan's gateway is the one this tool runs there, and it answers its health check."""
117
+ return _gateway(plan).answers(plan)
118
+
119
+
120
+ def _answers_magpie(plan: HarnessPlan) -> bool:
121
+ try:
122
+ env = harness_gateway.checked_gateway_environment(plan)
123
+ except HarnessError:
124
+ return False
125
+ magpie = tool_path(plan, "magpie")
126
+ return harness_core.run_tool([magpie, "healthcheck"], timeout=20, env=env).returncode == 0
127
+
128
+
129
+ def wired_providers(plan: HarnessPlan, doc: hosts.Owned) -> set[str]:
130
+ """The provider ids the plan's gateway holds now: its Bifrost config, or the ones this tool
131
+ added to Magpie (the owned manifest)."""
132
+ return _gateway(plan).wired_providers(doc)
133
+
134
+
115
135
  def revive(plan: HarnessPlan, started: str | None) -> str:
116
- if _bifrost(plan):
117
- return gateway_bifrost.revive(plan)
118
- return _revive_magpie(plan, started)
136
+ """``stack up``: start the plan's gateway again if it does not answer."""
137
+ return _gateway(plan).revive(plan, started)
119
138
 
120
139
 
121
140
  def _revive_magpie(plan: HarnessPlan, started: str | None) -> str:
@@ -427,10 +446,17 @@ def wire(
427
446
  point pi at it. Idempotent: providers are updated by id, and adding a group by its name
428
447
  replaces it with its rules. A re-sync (``select_pi=False``) leaves the gateway keys alone, so a
429
448
  key the user removed stays removed. A Bifrost plan goes to ``gateway_bifrost.wire``."""
449
+ return _gateway(plan).wire(plan, llm_key, decision_key, aux, select_pi)
450
+
451
+
452
+ def _wire_magpie(
453
+ plan: HarnessPlan,
454
+ llm_key: str,
455
+ decision_key: str | None,
456
+ aux: list[AuxEndpoint],
457
+ select_pi: bool,
458
+ ) -> list[str]:
430
459
  tools_dir = plan["tools_dir"]
431
- if _bifrost(plan):
432
- done = leave_magpie(tools_dir) if select_pi else []
433
- return done + gateway_bifrost.wire(plan, llm_key, decision_key, aux, select_pi=select_pi)
434
460
  done = leave(tools_dir) if select_pi else []
435
461
  if select_pi and (key := gateway_keys.ensure(plan)):
436
462
  done.append(key)
@@ -692,13 +718,18 @@ def accept(
692
718
  gateway (the decision model must be consulted), one embedding, rerank or transcription request
693
719
  per wired auxiliary (Magpie's usage log must gain its row), and one pi prompt with the stack's model.
694
720
  A Bifrost plan is accepted by ``bifrost_checks.accept``."""
721
+ return _gateway(plan).accept(plan, decision_key, aux, timeout)
722
+
723
+
724
+ def _accept_magpie(
725
+ plan: HarnessPlan, decision_key: str | None, aux: list[AuxEndpoint], timeout: float
726
+ ) -> list[Check]:
695
727
  return gateway_accept.accept(
696
728
  plan,
697
729
  decision_key,
698
730
  aux,
699
731
  timeout,
700
732
  aux_providers=AUX_PROVIDERS,
701
- is_bifrost=_bifrost(plan),
702
733
  post_fn=_post,
703
734
  magpie=run_magpie,
704
735
  run_tool=run_tool,
@@ -706,3 +737,83 @@ def accept(
706
737
  calls_fn=logged_calls,
707
738
  after_fn=logged_after,
708
739
  )
740
+
741
+
742
+ class _BifrostGateway:
743
+ """This tool's Bifrost, which ``gateway_bifrost`` runs and ``bifrost_checks`` accepts."""
744
+
745
+ def ensure(self, plan: ToolPlan) -> str:
746
+ return gateway_bifrost.ensure(plan)
747
+
748
+ def revive(self, plan: HarnessPlan, started: str | None) -> str:
749
+ return gateway_bifrost.revive(plan)
750
+
751
+ def answers(self, plan: HarnessPlan) -> bool:
752
+ try:
753
+ record = gateway_bifrost.require_target(plan)
754
+ except HarnessError:
755
+ return False
756
+ return bool(
757
+ record
758
+ and gateway_bifrost.owned_listener(record)
759
+ and gateway_bifrost.healthy(plan["gateway"]["addr"])
760
+ )
761
+
762
+ def wired_providers(self, doc: hosts.Owned) -> set[str]:
763
+ return bifrost_checks.wired_providers(doc)
764
+
765
+ def wire(
766
+ self,
767
+ plan: HarnessPlan,
768
+ llm_key: str,
769
+ decision_key: str | None,
770
+ aux: list[AuxEndpoint],
771
+ select_pi: bool,
772
+ ) -> list[str]:
773
+ done = leave_magpie(plan["tools_dir"]) if select_pi else []
774
+ return done + gateway_bifrost.wire(plan, llm_key, decision_key, aux, select_pi=select_pi)
775
+
776
+ def accept(
777
+ self, plan: HarnessPlan, decision_key: str | None, aux: list[AuxEndpoint], timeout: float
778
+ ) -> list[Check]:
779
+ return bifrost_checks.accept(plan, decision_key, aux, timeout)
780
+
781
+
782
+ class _MagpieGateway(_BifrostGateway):
783
+ """Legacy Magpie, which this module runs through the ``magpie`` CLI."""
784
+
785
+ def ensure(self, plan: ToolPlan) -> str:
786
+ return _ensure_magpie(plan)
787
+
788
+ def revive(self, plan: HarnessPlan, started: str | None) -> str:
789
+ return _revive_magpie(plan, started)
790
+
791
+ def answers(self, plan: HarnessPlan) -> bool:
792
+ return _answers_magpie(plan)
793
+
794
+ def wired_providers(self, doc: hosts.Owned) -> set[str]:
795
+ return set(doc["gateway"]["providers"])
796
+
797
+ def wire(
798
+ self,
799
+ plan: HarnessPlan,
800
+ llm_key: str,
801
+ decision_key: str | None,
802
+ aux: list[AuxEndpoint],
803
+ select_pi: bool,
804
+ ) -> list[str]:
805
+ return _wire_magpie(plan, llm_key, decision_key, aux, select_pi)
806
+
807
+ def accept(
808
+ self, plan: HarnessPlan, decision_key: str | None, aux: list[AuxEndpoint], timeout: float
809
+ ) -> list[Check]:
810
+ return _accept_magpie(plan, decision_key, aux, timeout)
811
+
812
+
813
+ _BIFROST = _BifrostGateway()
814
+ _MAGPIE = _MagpieGateway()
815
+
816
+
817
+ def _gateway(plan: ToolPlan) -> _BifrostGateway:
818
+ """The implementation of the gateway the plan names: the one place this module asks."""
819
+ return _MAGPIE if magpie_legacy.of(plan.get("gateway")).legacy else _BIFROST # type: ignore[arg-type]
@@ -101,7 +101,6 @@ def accept(
101
101
  timeout: float = 600,
102
102
  *,
103
103
  aux_providers: dict[str, str],
104
- is_bifrost: bool,
105
104
  post_fn: PostFn = post,
106
105
  magpie: MagpieFn,
107
106
  run_tool: Callable[..., subprocess.CompletedProcess[str]],
@@ -112,11 +111,7 @@ def accept(
112
111
  """Each claim needs a request: provider tests through Magpie, one routed turn through the
113
112
  gateway (the decision model must be consulted), one embedding, rerank or transcription request
114
113
  per wired auxiliary (Magpie's usage log must gain its row), and one pi prompt with the stack's model.
115
- A Bifrost plan is accepted by ``bifrost_checks.accept``."""
116
- if is_bifrost:
117
- from localmodels import bifrost_checks
118
-
119
- return bifrost_checks.accept(plan, decision_key, aux, timeout)
114
+ Magpie only: a Bifrost plan is accepted by ``bifrost_checks.accept``."""
120
115
  gw = plan["gateway"]
121
116
  checks: list[Check] = []
122
117