@simplexai/localmodels-darwin-arm64 0.1.0-dev.37 → 0.1.0-dev.39

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 (86) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +85 -78
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/bifrost_checks.py +9 -6
  6. package/modules/localmodels/bifrost_config.py +35 -1
  7. package/modules/localmodels/bifrost_datasheet.py +12 -2
  8. package/modules/localmodels/catalog.json +155 -8
  9. package/modules/localmodels/catalog.py +19 -1
  10. package/modules/localmodels/catalog_recipes.py +33 -2
  11. package/modules/localmodels/cli_parser.py +26 -3
  12. package/modules/localmodels/deploy.py +37 -9
  13. package/modules/localmodels/deploy_steps.py +6 -3
  14. package/modules/localmodels/download-mirrors.json +52 -4
  15. package/modules/localmodels/engines-b11583.json +20 -4
  16. package/modules/localmodels/engines-b12167.json +5 -1
  17. package/modules/localmodels/engines-strata-0.1.47.json +5 -1
  18. package/modules/localmodels/engines-strata-0.1.49.2.json +5 -1
  19. package/modules/localmodels/engines-strata-0.1.59.1.json +5 -1
  20. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +5 -1
  21. package/modules/localmodels/engines-whisper-b5454.json +5 -1
  22. package/modules/localmodels/engines.json +55 -11
  23. package/modules/localmodels/frontend.py +5 -2
  24. package/modules/localmodels/gateway_bifrost.py +11 -9
  25. package/modules/localmodels/gateway_cli.py +4 -2
  26. package/modules/localmodels/guard.py +15 -6
  27. package/modules/localmodels/harness.py +65 -33
  28. package/modules/localmodels/harness_gateway.py +9 -3
  29. package/modules/localmodels/hf_repo.py +15 -8
  30. package/modules/localmodels/library_gateway.py +26 -13
  31. package/modules/localmodels/library_jobs.py +51 -3
  32. package/modules/localmodels/library_model.py +10 -0
  33. package/modules/localmodels/library_pricing.py +29 -22
  34. package/modules/localmodels/library_serve.py +5 -0
  35. package/modules/localmodels/library_state.py +9 -1
  36. package/modules/localmodels/library_status.py +30 -0
  37. package/modules/localmodels/llm_rank.py +83 -30
  38. package/modules/localmodels/metal_probe.py +16 -6
  39. package/modules/localmodels/npm_signatures.py +131 -0
  40. package/modules/localmodels/npm_transport.py +26 -10
  41. package/modules/localmodels/process_identity.py +32 -5
  42. package/modules/localmodels/recommend.py +5 -2
  43. package/modules/localmodels/region.py +244 -0
  44. package/modules/localmodels/remote_ops.py +69 -13
  45. package/modules/localmodels/remote_ops_download.py +210 -10
  46. package/modules/localmodels/remote_ops_prepare.py +61 -8
  47. package/modules/localmodels/runtime-lock.json +13 -13
  48. package/modules/localmodels/runtime_args.py +4 -2
  49. package/modules/localmodels/runtime_cli.py +19 -37
  50. package/modules/localmodels/runtime_discovery.py +30 -0
  51. package/modules/localmodels/runtime_install.py +81 -6
  52. package/modules/localmodels/runtime_io.py +61 -5
  53. package/modules/localmodels/runtime_pi.py +79 -0
  54. package/modules/localmodels/runtime_process.py +99 -15
  55. package/modules/localmodels/runtime_releases.py +51 -71
  56. package/modules/localmodels/search_server.py +5 -1
  57. package/modules/localmodels/service_probe.py +62 -4
  58. package/modules/localmodels/setup_inspection.py +21 -4
  59. package/modules/localmodels/setup_text.py +6 -0
  60. package/modules/localmodels/source_byok.py +484 -0
  61. package/modules/localmodels/source_byok_probe.py +275 -0
  62. package/modules/localmodels/source_cli.py +426 -0
  63. package/modules/localmodels/stack.py +31 -14
  64. package/modules/localmodels/stack_args.py +8 -4
  65. package/modules/localmodels/stack_binding.py +47 -4
  66. package/modules/localmodels/stack_cli.py +2 -0
  67. package/modules/localmodels/stack_compose.py +5 -5
  68. package/modules/localmodels/stack_events.py +3 -0
  69. package/modules/localmodels/stack_hardware.py +21 -6
  70. package/modules/localmodels/stack_llm_ram.py +16 -6
  71. package/modules/localmodels/stack_picks.py +4 -4
  72. package/modules/localmodels/stack_progress.py +9 -1
  73. package/modules/localmodels/stack_run.py +29 -0
  74. package/modules/localmodels/stack_suite.py +10 -3
  75. package/modules/localmodels/stack_warm.py +45 -4
  76. package/modules/localmodels/tools.json +1396 -32
  77. package/modules/localmodels/transport.py +40 -13
  78. package/modules/localmodels/windows_job.py +69 -0
  79. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/METADATA +1 -1
  80. package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/RECORD +82 -75
  81. package/package.json +1 -1
  82. package/tool.json +1 -1
  83. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/WHEEL +0 -0
  84. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/entry_points.txt +0 -0
  85. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/NOTICE +0 -0
  86. /package/modules/{simplex_localmodels-0.1.0.dev37.dist-info → simplex_localmodels-0.1.0.dev39.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -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(
@@ -286,7 +289,8 @@ def add_plan_arguments(plan: argparse.ArgumentParser) -> None:
286
289
  default=deploy.hf_endpoint(),
287
290
  metavar="URL",
288
291
  help="where weights are downloaded from (default: $HF_ENDPOINT, else Hugging Face); "
289
- "faster sources of the same pinned files, such as ModelScope, are still tried",
292
+ "other sources of the same pinned files (ModelScope, hf-mirror.com) are still tried, "
293
+ "China-first in download region cn",
290
294
  )
291
295
  where.add_argument(
292
296
  "--offline",
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import hashlib
6
+ import json
6
7
  import os
7
8
  from pathlib import Path
8
9
  from typing import TypedDict, cast
@@ -64,8 +65,33 @@ def _acceptance_ready(plan: StackPlan) -> bool:
64
65
  return bool(view and view["ok"])
65
66
 
66
67
 
67
- def _deployments_ready(plan: StackPlan, owned: hosts.Owned) -> bool:
68
- parts = {part["name"]: part for part in deployments(plan)}
68
+ def _adopted(plan: StackPlan) -> set[str]:
69
+ """The plan's LLM components the library adopted (``library_convert``): from then on the
70
+ library loads, unloads and wires them, so their deployments, gateway route and pi selection
71
+ are no longer the stack's to check. Read only; it never converts."""
72
+ from localmodels import library_convert, library_state, stack_verify
73
+
74
+ try:
75
+ marker = json.loads((library_state.root() / library_convert.MARKER).read_text("utf-8"))
76
+ except (OSError, ValueError):
77
+ return set()
78
+ if not isinstance(marker, dict) or marker.get("plan_id") != plan["plan_id"]:
79
+ return set()
80
+ providers = {r.get("stack_provider") for r in library_state.records() if r.get("converted")}
81
+ return {
82
+ component
83
+ for component, _ in stack_verify.parts(plan)
84
+ if library_convert.STACK_LLMS.get(component) in providers
85
+ }
86
+
87
+
88
+ def _deployments_ready(
89
+ plan: StackPlan, owned: hosts.Owned, adopted: frozenset[str] | set[str] = frozenset()
90
+ ) -> bool:
91
+ from localmodels import stack_verify
92
+
93
+ library = {part["name"] for component, part in stack_verify.parts(plan) if component in adopted}
94
+ parts = {part["name"]: part for part in deployments(plan) if part["name"] not in library}
69
95
  records = [
70
96
  record for record in hosts.records(hosts.LOCAL_ID) if record["plan"]["name"] in parts
71
97
  ]
@@ -211,6 +237,22 @@ def _pi_binding(plan: StackPlan, owned: hosts.Owned, lang: Lang = "zh") -> PiBin
211
237
  }
212
238
 
213
239
 
240
+ def _library_binding(plan: StackPlan) -> PiBinding:
241
+ """The stack's pi once the library adopted its LLM: the library unwires the route and may
242
+ stop the gateway on unload, so only the executable and the owned profile are checked."""
243
+ from localmodels import bifrost_pi
244
+
245
+ executable = Path(harness.tool_path(plan["harness"], "pi"))
246
+ profile = bifrost_pi.pi_profile(harness.gateway_environment(plan["harness"]))
247
+ if not executable.is_absolute() or not profile.is_absolute():
248
+ raise ValueError("Pi paths must be absolute")
249
+ return {
250
+ "executable": str(executable),
251
+ "environment": {"PI_CODING_AGENT_DIR": str(profile)},
252
+ "configFingerprint": _profile_fingerprint(executable, profile),
253
+ }
254
+
255
+
214
256
  def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
215
257
  report: BindingReport = {
216
258
  "schema": "localmodels.stack-binding/v1",
@@ -234,10 +276,11 @@ def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
234
276
  report["reasons"] = [_reason("acceptance-unavailable", lang)]
235
277
  return report
236
278
  owned = hosts.load_owned(plan["harness"]["tools_dir"])
237
- if not _deployments_ready(plan, owned):
279
+ adopted = _adopted(plan)
280
+ if not _deployments_ready(plan, owned, adopted):
238
281
  report["reasons"] = [_reason("deployment-unavailable", lang)]
239
282
  return report
240
- binding = _pi_binding(plan, owned, lang)
283
+ binding = _library_binding(plan) if adopted else _pi_binding(plan, owned, lang)
241
284
  if "code" in binding:
242
285
  report["reasons"] = [cast(Reason, binding)]
243
286
  else:
@@ -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(
@@ -5,6 +5,8 @@ import json
5
5
  from collections.abc import Callable, Mapping, Sequence
6
6
  from typing import Literal, Protocol, TypedDict, runtime_checkable
7
7
 
8
+ from localmodels import region
9
+
8
10
  MAX_SAFE_INTEGER = 9_007_199_254_740_991
9
11
  MAX_EVENT_CHARS = 65_536
10
12
  STACK_PLAN_SECTIONS = (
@@ -293,6 +295,7 @@ class ToolEvents(io.StringIO):
293
295
  return
294
296
  if not isinstance(event, dict):
295
297
  return
298
+ region.observe(event)
296
299
  if event.get("event") == "log":
297
300
  self.log(str(event.get("message", "")))
298
301
  elif event.get("event") == "progress":
@@ -19,7 +19,15 @@ from localmodels import (
19
19
  stack_warm_store,
20
20
  suite,
21
21
  )
22
- from localmodels.budget import gib, holders, host_ram, placements, sharing_cards, unknown_services
22
+ from localmodels.budget import (
23
+ gib,
24
+ gpu_conflicts,
25
+ holders,
26
+ host_ram,
27
+ placements,
28
+ sharing_cards,
29
+ unknown_services,
30
+ )
23
31
  from localmodels.context_policy import AGENT, AgentPosture, cache_floor_bytes, posture_for
24
32
  from localmodels.estimator import (
25
33
  AGENT_VRAM_RESERVE_BYTES,
@@ -70,6 +78,10 @@ _FIRST_TIER_RAM = 60 * GIB # 64 GB of RAM reads about 62 GiB
70
78
  UNIFIED_MEMORY_ENV = "LOCALMODELS_UNIFIED_MEMORY"
71
79
 
72
80
 
81
+ class GpuOwnershipError(StackError):
82
+ """No eligible GPU can be shared because discovery could not verify ownership."""
83
+
84
+
73
85
  def add_arguments(parser: argparse._ActionsContainer) -> None:
74
86
  """``--unified-memory``, which ``stack plan``, ``install``, ``stack hardware`` and
75
87
  ``setup inspect`` share; LOCALMODELS_UNIFIED_MEMORY is its default."""
@@ -128,7 +140,7 @@ def decision_reserve(card_budget_bytes: int, options: StackOptions) -> int:
128
140
  def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False) -> list[int]:
129
141
  """Single-card choices by free memory; foreign GPU work needs explicit sharing."""
130
142
  if share_gpu and unknown_services(facts):
131
- raise StackError(
143
+ raise GpuOwnershipError(
132
144
  "GPU service owners unknown; explicit sharing cannot skip the unknown-service check"
133
145
  )
134
146
  if metal.device(facts) is not None:
@@ -145,9 +157,11 @@ def cards(facts: HostFacts, gpu: int | None = None, *, share_gpu: bool = False)
145
157
  f"no placeable GPU {gpu} here (usable cards: {found}; MIG-mode cards excluded)"
146
158
  )
147
159
  if share_gpu and gpu not in {g["index"] for g in sharing_cards(facts, 0)}:
148
- raise StackError("GPU process owners unknown; cannot share this GPU")
160
+ raise GpuOwnershipError("GPU process owners unknown; cannot share this GPU")
149
161
  return [gpu]
150
162
  allowed = {g["index"] for g in sharing_cards(facts, 0)} if share_gpu else set()
163
+ if share_gpu and singles and not allowed and gpu_conflicts(facts):
164
+ raise GpuOwnershipError("GPU process owners unknown; cannot share any GPU")
151
165
  free = [
152
166
  p.gpu_indices[0]
153
167
  for p in singles
@@ -329,10 +343,11 @@ def llm_fits(
329
343
  )
330
344
  if fits:
331
345
  speed = cat.decode_estimate(entry, variant, budget)
346
+ unscored = llm_rank.windows_fallback(entry, facts) or llm_rank.mac_rung(entry, facts)
332
347
  fit: LlmFit = {
333
348
  "id": entry.id,
334
349
  "quant": variant.quant,
335
- "quality": 0 if llm_rank.windows_fallback(entry, facts) else entry.quality,
350
+ "quality": 0 if unscored else entry.quality,
336
351
  "decode_tok_s": round(speed.tok_s, 1),
337
352
  "decode_basis": speed.basis,
338
353
  }
@@ -340,7 +355,7 @@ def llm_fits(
340
355
  if llm_rank.windows_fallback(entry, facts):
341
356
  fit["candidate_fallback"] = True
342
357
  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))
358
+ found.append((((0 if unscored else entry.quality), tok_s), fit))
344
359
 
345
360
  llama_score = max(
346
361
  (f["quality"] for _, f in found if not f.get("candidate_fallback")), default=-1
@@ -566,7 +581,7 @@ def view(facts: HostFacts, options: StackOptions, posture: AgentPosture | None)
566
581
  seen["service_manager"] = manager
567
582
  if posture is not None:
568
583
  _set_linux_note(facts, notes, seen["cards"])
569
- seen["picks"] = picks(seen["cards"], llm_rank.mac_default(facts))
584
+ seen["picks"] = picks(seen["cards"], llm_rank.mac_ladder(facts))
570
585
  return seen
571
586
 
572
587
 
@@ -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: