@simplexai/localmodels-linux-x64 0.1.0-dev.37 → 0.1.0-dev.38

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 (44) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +43 -42
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_checks.py +9 -6
  5. package/modules/localmodels/bifrost_config.py +16 -1
  6. package/modules/localmodels/bifrost_datasheet.py +12 -2
  7. package/modules/localmodels/catalog.json +137 -2
  8. package/modules/localmodels/catalog.py +19 -1
  9. package/modules/localmodels/catalog_recipes.py +33 -2
  10. package/modules/localmodels/gateway_bifrost.py +11 -9
  11. package/modules/localmodels/gateway_cli.py +4 -2
  12. package/modules/localmodels/library_gateway.py +11 -0
  13. package/modules/localmodels/library_jobs.py +51 -3
  14. package/modules/localmodels/library_model.py +10 -0
  15. package/modules/localmodels/library_pricing.py +29 -22
  16. package/modules/localmodels/library_serve.py +5 -0
  17. package/modules/localmodels/library_state.py +9 -1
  18. package/modules/localmodels/library_status.py +30 -0
  19. package/modules/localmodels/llm_rank.py +83 -30
  20. package/modules/localmodels/process_identity.py +11 -0
  21. package/modules/localmodels/recommend.py +5 -2
  22. package/modules/localmodels/search_server.py +5 -1
  23. package/modules/localmodels/stack.py +31 -14
  24. package/modules/localmodels/stack_args.py +6 -3
  25. package/modules/localmodels/stack_cli.py +2 -0
  26. package/modules/localmodels/stack_compose.py +5 -5
  27. package/modules/localmodels/stack_hardware.py +4 -3
  28. package/modules/localmodels/stack_llm_ram.py +16 -6
  29. package/modules/localmodels/stack_picks.py +4 -4
  30. package/modules/localmodels/stack_progress.py +9 -1
  31. package/modules/localmodels/stack_run.py +29 -0
  32. package/modules/localmodels/stack_suite.py +10 -3
  33. package/modules/localmodels/stack_warm.py +45 -4
  34. package/modules/localmodels/tools.json +32 -18
  35. package/modules/localmodels/transport.py +38 -13
  36. package/modules/localmodels/windows_job.py +69 -0
  37. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/METADATA +1 -1
  38. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/RECORD +40 -39
  39. package/package.json +1 -1
  40. package/tool.json +1 -1
  41. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/WHEEL +0 -0
  42. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/entry_points.txt +0 -0
  43. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/NOTICE +0 -0
  44. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -11,6 +11,7 @@ stay in ``catalog``.
11
11
  from __future__ import annotations
12
12
 
13
13
  from collections.abc import Iterable, Mapping
14
+ from dataclasses import dataclass
14
15
 
15
16
  from localmodels import metal, vision
16
17
  from localmodels.budget import HARNESS_RAM, RAM_FLOOR, host_ram
@@ -70,37 +71,79 @@ PRODUCT_DEFAULTS = {
70
71
  }
71
72
 
72
73
 
73
- # The installed SimplexAI score at which a fitting model takes over from the user-selected small-Mac
74
- # default (roadmap decision 40, 2026-11-09: intelligence first): 50 is the AIHOT reference-model
75
- # mean. A 24 GB Mac with the memory free holds Qwen3.8-27B UD-IQ3_S (52); one under desktop load,
76
- # and every 16 GB Mac, keeps LFM3 rather than a lower-scored model such as Ling-3.0-tiny (25).
74
+ # The installed SimplexAI score at which a validated model takes over from the Mac ladder
75
+ # (roadmap decision 40, 2026-11-09: intelligence first): 50 is the AIHOT reference-model mean.
76
+ # A 24 GB Mac with the memory free holds Qwen3.8-27B UD-IQ3_S (52); one under desktop load, and
77
+ # every 16 GB Mac, stays on the ladder rather than a lower-scored model such as Qwen3.6-35B-A3B.
77
78
  MAC_DEFAULT_YIELD_SCORE = 50
78
79
 
80
+ # The Mac small-memory ladder (roadmap decision 57, 2026-11-16, user-selected; it replaces
81
+ # decision 39's LFM3-1.7B): on every Apple Silicon Mac of MAC_LADDER_MIN_BYTES or more, while no
82
+ # validated model scoring MAC_DEFAULT_YIELD_SCORE or more fits, the smartest pick is the first
83
+ # rung that fits, best first. The rungs are candidates outside SimplexAI ranking: their catalog
84
+ # numbers are unranked (0) or vendor anchors and never compete with installed scores.
85
+ MAC_LADDER = ("spark-x2.6-4b-q4km", "spark-x2.6-1.7b")
86
+ MAC_LADDER_MIN_BYTES = 16 * metal.GIB
87
+ # --prefer fastest on a Mac below this much memory tries the small rung first (16 GB: the 1.7B);
88
+ # larger Macs try the 4B first (24 GB: Spark-X2.6-4B Q4_K_M), beside any validated model.
89
+ MAC_SMALL_BELOW_BYTES = 20 * metal.GIB
90
+ # Validated darwin entries the ladder replaces in automatic selection (decision 57): Ling-3.0-tiny
91
+ # (25) was the 32 GB+ fallback. Explicit --llm still installs it.
92
+ MAC_LADDER_REPLACES = frozenset({"ling-3.0-tiny"})
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class MacLadder:
97
+ """One Mac's ladder: ``smartest`` in fallback order, ``fastest`` in the order --prefer fastest
98
+ tries the rungs (one rung at most joins the validated models in the speed race)."""
99
+
100
+ smartest: tuple[str, ...]
101
+ fastest: tuple[str, ...]
102
+
103
+ def rename(self, ids: Mapping[str, str]) -> MacLadder:
104
+ """The same ladder under other ids (a library's model ids), dropping absent rungs."""
105
+ return MacLadder(
106
+ tuple(ids[i] for i in self.smartest if i in ids),
107
+ tuple(ids[i] for i in self.fastest if i in ids),
108
+ )
79
109
 
80
- def mac_default(facts: HostFacts) -> str | None:
81
- """User-selected small-Mac default (roadmap decision 39), outside SimplexAI ranking; it yields
82
- to a fitting model scoring MAC_DEFAULT_YIELD_SCORE or more (decision 40, ``keeps_default``)."""
83
- if metal.supported(facts) and 16 * metal.GIB <= facts["ram"]["total_bytes"] <= 24 * metal.GIB:
84
- return "lfm3-1.7b"
85
- return None
110
+
111
+ def mac_ladder(facts: HostFacts) -> MacLadder | None:
112
+ """This Mac's ladder (decision 57), or None off Apple Silicon and below 16 GB."""
113
+ if not metal.supported(facts) or facts["ram"]["total_bytes"] < MAC_LADDER_MIN_BYTES:
114
+ return None
115
+ small = facts["ram"]["total_bytes"] < MAC_SMALL_BELOW_BYTES
116
+ return MacLadder(MAC_LADDER, tuple(reversed(MAC_LADDER)) if small else MAC_LADDER)
117
+
118
+
119
+ def mac_rung(entry: CatalogEntry, facts: HostFacts) -> bool:
120
+ """The entry is a rung of this Mac's ladder."""
121
+ ladder = mac_ladder(facts)
122
+ return ladder is not None and entry.status != "deprecated" and entry.id in ladder.smartest
86
123
 
87
124
 
88
125
  def keeps_default(scores: Iterable[int]) -> bool:
89
- """The small-Mac default stands unless one of the fitting models' scores reaches the yield."""
126
+ """The ladder stands unless one of the other fitting models' scores reaches the yield."""
90
127
  return all(score < MAC_DEFAULT_YIELD_SCORE for score in scores)
91
128
 
92
129
 
93
130
  def listed_default(facts: HostFacts, fits: list[tuple[str, int]]) -> str | None:
94
- """The small-Mac default to list first among ``(id, score)`` fits, or None once another fit
95
- reaches the yield score (decision 40)."""
96
- default = mac_default(facts)
97
- return default if keeps_default(q for i, q in fits if i != default) else None
131
+ """The ladder rung to list first among ``(id, score)`` fits, or None once another fit
132
+ reaches the yield score (decision 40) or no rung fits."""
133
+ ladder = mac_ladder(facts)
134
+ if ladder is None:
135
+ return None
136
+ rungs = [i for i in ladder.smartest if i in {i for i, _ in fits}]
137
+ others = (q for i, q in fits if i not in ladder.smartest)
138
+ return rungs[0] if rungs and keeps_default(others) else None
98
139
 
99
140
 
100
141
  def automatic_here(entry: CatalogEntry, facts: HostFacts) -> bool:
101
- """Validated entries and the scoped Mac default / Windows fallback candidates."""
142
+ """Validated entries and the scoped Mac ladder / Windows fallback candidates."""
143
+ if entry.id in MAC_LADDER_REPLACES and mac_ladder(facts) is not None:
144
+ return False
102
145
  return (
103
- (entry.status != "deprecated" and entry.id == mac_default(facts))
146
+ mac_rung(entry, facts)
104
147
  or windows_fallback(entry, facts)
105
148
  or validated_here(entry, facts["platform"])
106
149
  )
@@ -261,24 +304,34 @@ def rank_key(
261
304
  def choose(
262
305
  ranked: list[tuple[tuple[int, float], str, int]],
263
306
  prefer: str,
264
- default: str | None = None,
307
+ ladder: MacLadder | None = None,
265
308
  *,
266
309
  fallback_ids: Iterable[str] = (),
267
310
  ) -> tuple[str, int]:
268
311
  """(entry id, card index) out of ``(rank_key, id, card)`` triples for one scenario: fastest
269
- takes the highest decode speed whatever the score (the score breaks ties); otherwise the
270
- small-Mac ``default`` when it fits and keeps_default holds for the others; else smartest and
312
+ takes the highest decode speed whatever the score (the score breaks ties); smartest and
271
313
  concurrent take the best score (speed breaks ties); fast takes the fastest whose score is
272
- within FAST_QUALITY_BAND of the best. Scoped ``fallback_ids`` are considered only when
273
- no primary fits on any eligible card."""
314
+ within FAST_QUALITY_BAND of the best. Scoped ``fallback_ids`` are considered only when no
315
+ primary fits on any eligible card. On a Mac ``ladder`` rungs never rank by score: smartest
316
+ takes the first fitting rung while keeps_default holds for the other fits, and fastest races
317
+ the first fitting rung of ``ladder.fastest`` against the other fits."""
274
318
  fallback = set(fallback_ids)
275
319
  ranked = [row for row in ranked if row[1] not in fallback] or ranked
320
+ if ladder is not None:
321
+ rungs = {row[1]: row for row in ranked if row[1] in ladder.smartest}
322
+ primary = [row for row in ranked if row[1] not in rungs]
323
+ if prefer == "fastest":
324
+ rung = next((rungs[i] for i in ladder.fastest if i in rungs), None)
325
+ pool = primary + ([rung] if rung is not None else [])
326
+ _, entry_id, index = max(pool, key=lambda t: (t[0][1], t[0][0]))
327
+ return entry_id, index
328
+ if rungs and keeps_default(key[0] for key, _, _ in primary):
329
+ _, entry_id, index = next(rungs[i] for i in ladder.smartest if i in rungs)
330
+ return entry_id, index
331
+ ranked = primary or ranked
276
332
  if prefer == "fastest":
277
333
  _, entry_id, index = max(ranked, key=lambda t: (t[0][1], t[0][0]))
278
334
  return entry_id, index
279
- mine = [(entry_id, index) for _, entry_id, index in ranked if entry_id == default]
280
- if mine and keeps_default(key[0] for key, entry_id, _ in ranked if entry_id != default):
281
- return mine[0]
282
335
  if prefer == "fast":
283
336
  best = max(key[0] for key, _, _ in ranked)
284
337
  near = [t for t in ranked if t[0][0] >= best - FAST_QUALITY_BAND]
@@ -293,7 +346,7 @@ def recommended_entry(
293
346
  entries: tuple[CatalogEntry, ...],
294
347
  *,
295
348
  backend: str = "auto",
296
- default_id: str | None = None,
349
+ ladder: tuple[str, ...] = (),
297
350
  ) -> tuple[CatalogEntry, str] | None:
298
351
  """The default pick for THIS budget, with its reason key: product-default,
299
352
  best-quality-resident, or speed-gated-quality. Only resident entries that pass
@@ -312,10 +365,10 @@ def recommended_entry(
312
365
  return predicted_decode_tok_s(t[0], t[1].variant, budget, backend=backend)
313
366
 
314
367
  resident = [(e, c) for e, c in fitting if c.zero_spill and agent_ready(e, c.variant, budget)]
315
- if keeps_default(e.quality for e, _ in resident if e.id != default_id):
316
- for entry, _ in resident:
317
- if entry.id == default_id:
318
- return entry, "user-default"
368
+ rungs = {e.id: e for e, _ in resident if e.id in ladder}
369
+ resident = [(e, c) for e, c in resident if e.id not in rungs]
370
+ if rungs and keeps_default(e.quality for e, _ in resident):
371
+ return next(rungs[i] for i in ladder if i in rungs), "user-default"
319
372
  product_default = PRODUCT_DEFAULTS.get(hardware_key(budget, backend))
320
373
  for entry, _ in resident:
321
374
  if entry.id == product_default:
@@ -278,6 +278,17 @@ def _taskkill(pid: int, force: bool) -> bool:
278
278
  return subprocess.run(argv, capture_output=True, timeout=30, check=False).returncode == 0
279
279
 
280
280
 
281
+ def stop_children(pid: int) -> int:
282
+ """Windows: force-end the trees of ``pid``'s child processes (not ``pid`` itself); how many
283
+ children it found. A download ends the helper it runs this way when it is cancelled."""
284
+ if not _windows():
285
+ raise RuntimeError("stop_children is for Windows")
286
+ children = [child for child, parent in _parent_pids().items() if parent == pid and child > 0]
287
+ for child in children:
288
+ _taskkill(child, True)
289
+ return len(children)
290
+
291
+
281
292
  def windows_stop_tree(pid: int, saved: Identity, grace: float) -> bool:
282
293
  """Stop PID and descendants via polite ``taskkill /T`` (capped at 2 s) then ``/F``."""
283
294
  import time
@@ -77,7 +77,10 @@ _QUANT_REASONS = {
77
77
  }
78
78
  RECOMMENDED_REASONS = {
79
79
  "windows-candidate-fallback": llm_rank.WINDOWS_FALLBACK_WARNING,
80
- "user-default": "User-selected small-Mac default; SimplexAI score and full acceptance pending.",
80
+ "user-default": (
81
+ "User-selected Mac small-memory ladder (Spark-X2.6, 64K shared by two slots); "
82
+ "SimplexAI score and full acceptance pending."
83
+ ),
81
84
  "product-default": "This machine's default model, chosen by its maker.",
82
85
  "best-quality-resident": (
83
86
  "Candidates that pass the agent capacity gate are ranked by capability score first, "
@@ -171,7 +174,7 @@ def recommendation(
171
174
  placement.budget,
172
175
  live,
173
176
  backend=placement.backend,
174
- default_id=llm_rank.mac_default(facts),
177
+ ladder=ladder.smartest if (ladder := llm_rank.mac_ladder(facts)) else (),
175
178
  )
176
179
  if picked is not None:
177
180
  return picked[0], picked[1], placement
@@ -38,7 +38,11 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
38
38
  from io import BufferedIOBase
39
39
  from typing import Any, Protocol, TypedDict, cast
40
40
 
41
- ENGINES = "duckduckgo,yahoo,brave,mojeek" # DuckDuckGo first, always
41
+ # DuckDuckGo first, always; Bing last. From home-m6's network (Apple M6, 2026-11-17, ddgs 9.16.1,
42
+ # 10 queries each) DuckDuckGo, Brave and Mojeek answered none and Yahoo half (anti-bot pages read
43
+ # as no results), so a stack apply's search checks failed about one apply in four; Bing answered
44
+ # 7 of 10 at about 12 s. Asked only after every other engine found nothing.
45
+ ENGINES = "duckduckgo,yahoo,brave,mojeek,bing"
42
46
  MAX_QUERY_CHARS = 512
43
47
  MAX_RESULTS = 10
44
48
  REST_S = 120.0
@@ -9,6 +9,7 @@ import os
9
9
  import secrets
10
10
  import subprocess
11
11
  import sys
12
+ import time
12
13
  from collections.abc import Callable
13
14
  from dataclasses import dataclass, replace
14
15
  from pathlib import Path
@@ -97,8 +98,8 @@ def build(
97
98
  raw = copy.deepcopy(seen)
98
99
  if seen["platform"] == "win32" and options.get("gateway") == "bifrost":
99
100
  raise StackError( # the default follows the computer planning; --facts may be another's
100
- "Bifrost has no Windows build; plan Windows facts with --gateway magpie, the gateway"
101
- " stack plan picks on Windows itself"
101
+ "the stack runs Magpie on Windows (decision 48); plan Windows facts with --gateway"
102
+ " magpie, the gateway stack plan picks on Windows itself"
102
103
  )
103
104
  seen = hardware.assumed(seen, options.get("unified_memory"))
104
105
  resolver = deploy.catalog_pins if options.get("offline") else deploy.resolve_files
@@ -244,6 +245,15 @@ def _failed(component: str, detail: str, checks: list[gateway.Check] | None = No
244
245
  }
245
246
 
246
247
 
248
+ # Apply re-plans an approved plan from this computer's state and refuses one that changed. A busy
249
+ # Mac's free memory dips for about a second (home-m6, 2026-11-17: 0.37-0.56 GiB for 1-2 s, after
250
+ # another stack stopped), and the prompt cache priced in that dip came out smaller, so 2 of 12
251
+ # back-to-back plan/apply runs were refused although the next reading matched. A plan built now
252
+ # must still match the approved one exactly; a mismatch is read again this many times, this far
253
+ # apart, and refused only when every reading differs.
254
+ REPLAN_READINGS = 3
255
+ REPLAN_PAUSE_S = 1.0
256
+
247
257
  # The two ways an approval fails before anything runs: a mistyped code, or a plan file whose
248
258
  # contents no longer hash to the code it was saved with.
249
259
  WRONG_CODE = "the --approve value is not this plan's approval code"
@@ -276,18 +286,25 @@ def apply(
276
286
  raise StackError(error)
277
287
  try:
278
288
  with hosts.stack_apply_lock():
279
- try:
280
- fresh = (
281
- rebuild(plan["options"]) if rebuild else build(plan["options"], approved=plan)
282
- )
283
- except (PlanError, StackError) as exc:
284
- raise StackReplanError(
285
- f"planning again from this computer's current state failed: {exc}. "
286
- "This computer changed, or the plan was made on another machine or "
287
- "with --facts; run stack plan again on this computer",
288
- cause_code="STACK_REPLAN_FAILED",
289
- ) from exc
290
- moved = stack_changes(plan, fresh)
289
+ for reading in range(REPLAN_READINGS):
290
+ if reading:
291
+ time.sleep(REPLAN_PAUSE_S)
292
+ try:
293
+ fresh = (
294
+ rebuild(plan["options"])
295
+ if rebuild
296
+ else build(plan["options"], approved=plan)
297
+ )
298
+ except (PlanError, StackError) as exc:
299
+ raise StackReplanError(
300
+ f"planning again from this computer's current state failed: {exc}. "
301
+ "This computer changed, or the plan was made on another machine or "
302
+ "with --facts; run stack plan again on this computer",
303
+ cause_code="STACK_REPLAN_FAILED",
304
+ ) from exc
305
+ moved = stack_changes(plan, fresh)
306
+ if not moved:
307
+ break
291
308
  if moved:
292
309
  raise StackGuardError(
293
310
  "this computer's state or artifacts changed since the plan was made ("
@@ -189,9 +189,12 @@ def add_plan_arguments(plan: argparse.ArgumentParser) -> None:
189
189
  choices=PREFERENCES,
190
190
  default="smartest",
191
191
  help="what auto optimizes (roadmap decision 26): smartest, the highest installed "
192
- "SimplexAI score that fits (default); concurrent, at least two requests decoding "
193
- "together; fast, the fastest model within a few points of the smartest; fastest, the "
194
- "highest decode speed that fits whatever its score (the second choice `stack hardware` "
192
+ "SimplexAI score that fits (default), except that a Mac of 16 GB or more takes its "
193
+ "Spark-X2.6 ladder while no validated model scoring 50 fits, and Windows NVIDIA falls "
194
+ "back to Spark-X2.6-4B Q8_0 when no validated model fits; concurrent, at least two "
195
+ "requests decoding together; fast, the fastest model within a few points of the "
196
+ "smartest; fastest, the highest decode speed that fits whatever its score, the Mac "
197
+ "ladder's rung and the Windows fallback included (the second choice `stack hardware` "
195
198
  "and `install` offer)",
196
199
  )
197
200
  choose.add_argument(
@@ -200,10 +200,12 @@ def apply_cli(
200
200
  plan=plan,
201
201
  )
202
202
  if jsonl:
203
+ failure = stack_run.component_failure(record)
203
204
  return stack_progress.result(
204
205
  record["ok"],
205
206
  ((c["component"], c["status"]) for c in record["components"]),
206
207
  profile=record.get("profile"),
208
+ cause=failure[1][0] if failure else None,
207
209
  )
208
210
  return report(record, timing=shown.timing() if shown else None)
209
211
 
@@ -344,8 +344,8 @@ def _choose_llm(
344
344
  if fitting:
345
345
  if kept := stack_auto.approved_llama_choice(fitting, approved):
346
346
  return kept[0], placement(kept[1])
347
- prefer, default = str(options.get("prefer") or "smartest"), llm_rank.mac_default(facts)
348
- llm_id, index = llm_rank.choose(fitting, prefer, default, fallback_ids=fallback_ids)
347
+ prefer, ladder = str(options.get("prefer") or "smartest"), llm_rank.mac_ladder(facts)
348
+ llm_id, index = llm_rank.choose(fitting, prefer, ladder, fallback_ids=fallback_ids)
349
349
  return llm_id, placement(index)
350
350
  where = (
351
351
  f"GPU {gpu}"
@@ -423,10 +423,10 @@ def _llm_warnings(
423
423
  and options["llm"] == "auto"
424
424
  ):
425
425
  warnings.append(f"LLM: {llm_rank.WINDOWS_FALLBACK_WARNING}")
426
- if llm_id == llm_rank.mac_default(facts) and options["llm"] == "auto":
426
+ if llm_id in getattr(llm_rank.mac_ladder(facts), "smartest", ()) and options["llm"] == "auto":
427
427
  warnings.append(
428
- "LLM: LFM3-1.7B is the user-selected small-Mac default (LFM1); "
429
- "no SimplexAI score, physical 16 GB install and full product acceptance pending"
428
+ f"LLM: {llm_id} is on the user-selected Mac small-memory ladder (decision 57, 64K x 2);"
429
+ " no SimplexAI score, physical 16 GB install and full product acceptance pending"
430
430
  )
431
431
  if options["conversation_cache"] not in ("auto", "off"):
432
432
  warnings.append(
@@ -329,10 +329,11 @@ def llm_fits(
329
329
  )
330
330
  if fits:
331
331
  speed = cat.decode_estimate(entry, variant, budget)
332
+ unscored = llm_rank.windows_fallback(entry, facts) or llm_rank.mac_rung(entry, facts)
332
333
  fit: LlmFit = {
333
334
  "id": entry.id,
334
335
  "quant": variant.quant,
335
- "quality": 0 if llm_rank.windows_fallback(entry, facts) else entry.quality,
336
+ "quality": 0 if unscored else entry.quality,
336
337
  "decode_tok_s": round(speed.tok_s, 1),
337
338
  "decode_basis": speed.basis,
338
339
  }
@@ -340,7 +341,7 @@ def llm_fits(
340
341
  if llm_rank.windows_fallback(entry, facts):
341
342
  fit["candidate_fallback"] = True
342
343
  tok_s = float(fit["decode_tok_s"]) if fit["decode_tok_s"] is not None else -1.0
343
- found.append(((entry.quality, tok_s), fit))
344
+ found.append((((0 if unscored else entry.quality), tok_s), fit))
344
345
 
345
346
  llama_score = max(
346
347
  (f["quality"] for _, f in found if not f.get("candidate_fallback")), default=-1
@@ -566,7 +567,7 @@ def view(facts: HostFacts, options: StackOptions, posture: AgentPosture | None)
566
567
  seen["service_manager"] = manager
567
568
  if posture is not None:
568
569
  _set_linux_note(facts, notes, seen["cards"])
569
- seen["picks"] = picks(seen["cards"], llm_rank.mac_default(facts))
570
+ seen["picks"] = picks(seen["cards"], llm_rank.mac_ladder(facts))
570
571
  return seen
571
572
 
572
573
 
@@ -65,20 +65,30 @@ def prompt_cache_bytes(llm: Plan) -> int:
65
65
  # and apply and the approved plan still fits: a desktop's free RAM moves by tens of MiB a minute,
66
66
  # and a cache sized to the last megabyte made every apply on one fail its RAM check (WINSTK1).
67
67
  DRIFT_MIB = 256
68
+ # A Mac's available memory (free, inactive and speculative pages: page cache the desktop takes
69
+ # back) swings further. home-m6 (Apple M6, 2026-11-17): a plan priced at one reading met readings
70
+ # 373-564 MiB lower for several seconds at apply, so the approved cache no longer fitted and apply
71
+ # refused it (2 of 12 back-to-back plan/apply runs). Unified-memory plans leave this much.
72
+ UNIFIED_DRIFT_MIB = 768
68
73
 
69
74
 
70
75
  def prompt_cache_fit(
71
- llm: Plan, room_bytes: int, posture: AgentPosture, *, approved_mib: int | None = None
76
+ llm: Plan,
77
+ room_bytes: int,
78
+ posture: AgentPosture,
79
+ *,
80
+ approved_mib: int | None = None,
81
+ drift_mib: int = DRIFT_MIB,
72
82
  ) -> list[str]:
73
- """Size the LLM's ``--cache-ram`` to the host RAM left for it, less ``DRIFT_MIB``, between
74
- the posture's minimum and its full cache. Returns the warning to show when the RAM left held
75
- it back. ``approved_mib``: apply re-plans an approved plan, whose cache stays as approved
76
- while the RAM left now still holds it."""
83
+ """Size the LLM's ``--cache-ram`` to the host RAM left for it, less ``drift_mib``
84
+ (``UNIFIED_DRIFT_MIB`` on a Mac), between the posture's minimum and its full cache. Returns
85
+ the warning to show when the RAM left held it back. ``approved_mib``: apply re-plans an
86
+ approved plan, whose cache stays as approved while the RAM left now still holds it."""
77
87
  if prompt_cache_bytes(llm) == 0:
78
88
  return []
79
89
  planned = posture.prompt_cache_mib << 20
80
90
  fits = min(planned, room_bytes) >> 20
81
- mib = max(posture.prompt_cache_min_mib, min(planned, room_bytes - (DRIFT_MIB << 20)) >> 20)
91
+ mib = max(posture.prompt_cache_min_mib, min(planned, room_bytes - (drift_mib << 20)) >> 20)
82
92
  if approved_mib is not None and posture.prompt_cache_min_mib <= approved_mib <= fits:
83
93
  mib = approved_mib
84
94
  argv = llm["service"]["argv"]
@@ -56,10 +56,10 @@ class CardFits(TypedDict):
56
56
  llm: list[Fit]
57
57
 
58
58
 
59
- def picks(cards: Sequence[CardFits], default: str | None = None) -> list[Pick]:
59
+ def picks(cards: Sequence[CardFits], ladder: llm_rank.MacLadder | None = None) -> list[Pick]:
60
60
  """The smartest fitting LLM, then the fastest when it is another model and worth it. Each
61
61
  model counts on the first card that holds it, in the order ``--llm auto`` tries cards (most
62
- free memory first); ``default`` is the small-Mac default (llm_rank.mac_default). When every
62
+ free memory first); ``ladder`` is the Mac small-memory ladder (llm_rank.mac_ladder). When every
63
63
  card that holds a model runs another program's service (a shared Mac's one GPU), the picks
64
64
  are what sharing it would install and say so. Empty when nothing eligible fits."""
65
65
  free = [c for c in cards if c["auto"] and c["llm"]]
@@ -96,10 +96,10 @@ def picks(cards: Sequence[CardFits], default: str | None = None) -> list[Pick]:
96
96
  for p in eligible
97
97
  ]
98
98
  fallback_ids = {p["id"] for p in eligible if p.get("candidate_fallback")}
99
- smartest = found[llm_rank.choose(ranked, "smartest", default, fallback_ids=fallback_ids)[0]]
99
+ smartest = found[llm_rank.choose(ranked, "smartest", ladder, fallback_ids=fallback_ids)[0]]
100
100
  llama_ranked = [row for row in ranked if row[1] not in strata_ids]
101
101
  fastest = (
102
- found[llm_rank.choose(llama_ranked, "fastest", fallback_ids=fallback_ids)[0]]
102
+ found[llm_rank.choose(llama_ranked, "fastest", ladder, fallback_ids=fallback_ids)[0]]
103
103
  if llama_ranked
104
104
  else smartest
105
105
  )
@@ -26,7 +26,14 @@ class JsonlObserver:
26
26
  self.output.flush()
27
27
 
28
28
 
29
- def result(ok: bool, components: Iterable[tuple[str, str]], *, profile: str | None = None) -> int:
29
+ def result(
30
+ ok: bool,
31
+ components: Iterable[tuple[str, str]],
32
+ *,
33
+ profile: str | None = None,
34
+ cause: str | None = None,
35
+ ) -> int:
36
+ """The final JSONL line; ``cause`` is the fixed public code of a run that did not pass."""
30
37
  print(
31
38
  json.dumps(
32
39
  {
@@ -35,6 +42,7 @@ def result(ok: bool, components: Iterable[tuple[str, str]], *, profile: str | No
35
42
  "components": [
36
43
  {"component": component, "status": status} for component, status in components
37
44
  ],
45
+ **({"causeCode": cause} if cause is not None and not ok else {}),
38
46
  **(
39
47
  {"profile": "macos-mlx-preview", "product_acceptance": "incomplete"}
40
48
  if profile == "macos-mlx-preview"
@@ -446,9 +446,34 @@ CAUSES = {
446
446
  "STACK_APPLY_REJECTED": "the plan could not be loaded or checked; "
447
447
  "run the same command without --json to see why",
448
448
  "STACK_APPLY_FAILED": "applying the plan failed; stack status and stack doctor show the state",
449
+ # An apply that ran to the end with a component that did not pass (a run record exists).
450
+ "STACK_COMPONENT_FAILED": "a component did not pass; failed_components names it, and stack "
451
+ "status and stack doctor show why",
452
+ SEARCH_UNAVAILABLE: "no free web search engine answered from this network; plan again "
453
+ "without --search, or apply again later",
449
454
  }
450
455
 
451
456
 
457
+ def component_failure(record: StackRecord) -> tuple[list[str], tuple[str, str]] | None:
458
+ """For a run that ended not ok: the components that did not pass, in run order (a planned
459
+ one that never ran counts), and the public cause. Names come from the fixed component set,
460
+ the cause from CAUSES; a component's own detail never leaves the record."""
461
+ if record["ok"]:
462
+ return None
463
+ parts = {part["component"]: part for part in record["components"]}
464
+ planned = [str(name) for name in record.get("required_components") or [] if name in COMPONENTS]
465
+ order = [name for name in parts if name in COMPONENTS]
466
+ order += [name for name in planned if name not in parts]
467
+ failed = [name for name in order if name not in parts or parts[name]["status"] != "ok"]
468
+ first = parts.get(failed[0]) if failed else None
469
+ checks = (first.get("checks") or []) if first is not None else []
470
+ unanswered = [check for check in checks if isinstance(check, dict) and not check.get("ok")]
471
+ if unanswered and all(check.get("detail") == SEARCH_UNAVAILABLE for check in unanswered):
472
+ # web search's own verify, or acceptance whose only failure is the direct search check
473
+ return failed, (SEARCH_UNAVAILABLE, CAUSES[SEARCH_UNAVAILABLE])
474
+ return failed, ("STACK_COMPONENT_FAILED", CAUSES["STACK_COMPONENT_FAILED"])
475
+
476
+
452
477
  def cause_of(exc: BaseException, *, started: bool) -> tuple[str, str]:
453
478
  """(cause code, fixed message) for an apply that raised ``exc``: a guard's own code (and its
454
479
  literal public sentence when it has one), else interrupted, failed after starting, or
@@ -477,6 +502,9 @@ def machine_result(
477
502
  if record is not None and (view is None or (state == "completed" and not view["ok"])):
478
503
  state, code = "failed", "1"
479
504
  exit_code = int(code)
505
+ failure = component_failure(record) if record is not None and state == "failed" else None
506
+ if failure is not None and cause is None:
507
+ cause = failure[1]
480
508
  print(
481
509
  json.dumps(
482
510
  {
@@ -496,6 +524,7 @@ def machine_result(
496
524
  if view and view.get("profile") == "macos-mlx-preview"
497
525
  else {}
498
526
  ),
527
+ **({"failed_components": failure[0]} if failure is not None else {}),
499
528
  **({"cause_code": cause[0], "message": cause[1]} if cause else {}),
500
529
  },
501
530
  separators=(",", ":"),
@@ -660,8 +660,9 @@ def fit_llama_ram(
660
660
  # comes first and the rest of it last (below). On a Mac that minimum is the floor deploy
661
661
  # reserved inside the LLM's unified bytes before the window and decision model were chosen.
662
662
  floor = int(str(llm["launch"].get("cache_floor_bytes") or 0)) if metal else 0
663
- if floor: # never shrink below what deploy reserved, nor demand more than that
664
- posture = replace(posture, prompt_cache_min_mib=floor >> 20)
663
+ if floor: # never shrink below what deploy reserved; --cache-ram counts whole MiB, so round
664
+ # up (a model-sized floor such as 257.9 MiB truncated to 257 left the cache under it)
665
+ posture = replace(posture, prompt_cache_min_mib=-(-floor >> 20))
665
666
  if running and metal: # a running Mac LLM's cache beyond the floor is the same RAM
666
667
  spill += prompt_cache_bytes(llm) - floor
667
668
  if not running and not metal:
@@ -699,6 +700,12 @@ def fit_llama_ram(
699
700
  - reserved_bytes
700
701
  )
701
702
  left = room - sum(map(suite.bounded_ram, aux)) + floor
702
- warnings += prompt_cache_fit(llm, left, posture, approved_mib=approved_mib)
703
+ warnings += prompt_cache_fit(
704
+ llm,
705
+ left,
706
+ posture,
707
+ approved_mib=approved_mib,
708
+ drift_mib=llm_ram.UNIFIED_DRIFT_MIB if metal else llm_ram.DRIFT_MIB,
709
+ )
703
710
  spill += prompt_cache_bytes(llm) - floor
704
711
  return aux, spill
@@ -317,12 +317,27 @@ def host_steps(platform: str, allow_sudo: bool, run: Run = _run) -> list[Step]:
317
317
  return _linux_steps(run)
318
318
 
319
319
 
320
- def _chat(url: str, model: str, secret: str) -> tuple[float, dict[str, object]]:
321
- """One short completion straight at the LLM: (wall seconds, the response document)."""
320
+ # The prompt-speed request: about 500 tokens no earlier request shares a prefix with (so the
321
+ # server's prompt cache cannot skip them), one token of answer. The warm requests' own prompts
322
+ # are a few dozen tokens, too short for a prompt speed that means anything.
323
+ PREFILL_PROMPT = (
324
+ " ".join(
325
+ f"Station {i} logged a calm morning, light westerly wind, clear skies and dry air."
326
+ for i in range(1, 31)
327
+ )
328
+ + " Which station logged rain? Answer with one word."
329
+ )
330
+ PREFILL_MIN_TOKENS = 256 # fewer prompt tokens than this: no prompt speed is reported
331
+
332
+
333
+ def _chat(
334
+ url: str, model: str, secret: str, prompt: str = WARM_PROMPT, max_tokens: int = WARM_TOKENS
335
+ ) -> tuple[float, dict[str, object]]:
336
+ """One completion straight at the LLM: (wall seconds, the response document)."""
322
337
  body = {
323
338
  "model": model,
324
- "messages": [{"role": "user", "content": WARM_PROMPT}],
325
- "max_tokens": WARM_TOKENS,
339
+ "messages": [{"role": "user", "content": prompt}],
340
+ "max_tokens": max_tokens,
326
341
  "stream": False,
327
342
  }
328
343
  request = urllib.request.Request(
@@ -352,6 +367,32 @@ def _decode_speed(doc: dict[str, object], seconds: float) -> float | None:
352
367
 
353
368
 
354
369
  Chat = Callable[[str, str, str], tuple[float, dict[str, object]]]
370
+ Prefill = Callable[[str, str, str, str, int], tuple[float, dict[str, object]]]
371
+
372
+
373
+ def prompt_speed(part: Plan, chat: Prefill = _chat) -> float | None:
374
+ """Prompt tokens/s of a loaded LLM: llama-server's own ``timings`` for a ~500-token prompt
375
+ it has not seen; None when it gives no timings, counts too few tokens, or does not answer."""
376
+ secret = stack_verify.key(part)
377
+ if secret is None:
378
+ return None
379
+ url, model = str(part["endpoint"]["base_url"]), str(part["model"]["model_id"])
380
+ try:
381
+ _, doc = chat(url, model, secret, PREFILL_PROMPT, 1)
382
+ except (OSError, ValueError):
383
+ return None
384
+ timings = doc.get("timings")
385
+ if not isinstance(timings, dict):
386
+ return None
387
+ count, speed = timings.get("prompt_n"), timings.get("prompt_per_second")
388
+ if (
389
+ isinstance(count, int)
390
+ and count >= PREFILL_MIN_TOKENS
391
+ and isinstance(speed, int | float)
392
+ and 0 < speed < float("inf")
393
+ ):
394
+ return float(speed)
395
+ return None
355
396
 
356
397
 
357
398
  def warm_llm(part: Plan, chat: Chat = _chat) -> LlmWarm: