@simplexai/localmodels-linux-x64 0.1.0-dev.36 → 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 (134) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +132 -110
  3. package/kit.py +1 -0
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +9 -3
  6. package/modules/localmodels/bifrost_checks.py +9 -6
  7. package/modules/localmodels/bifrost_config.py +203 -0
  8. package/modules/localmodels/bifrost_datasheet.py +12 -2
  9. package/modules/localmodels/budget.py +13 -2
  10. package/modules/localmodels/catalog.json +137 -2
  11. package/modules/localmodels/catalog.py +70 -321
  12. package/modules/localmodels/catalog_add.py +2 -8
  13. package/modules/localmodels/catalog_recipes.py +352 -0
  14. package/modules/localmodels/cli_parser.py +4 -1
  15. package/modules/localmodels/console.py +5 -4
  16. package/modules/localmodels/contracts.py +13 -3
  17. package/modules/localmodels/debug_cli.py +158 -0
  18. package/modules/localmodels/debug_mode.py +727 -0
  19. package/modules/localmodels/debug_stub_server.py +192 -0
  20. package/modules/localmodels/decode_calibration.json +1 -1
  21. package/modules/localmodels/decode_calibration.py +34 -17
  22. package/modules/localmodels/gateway.py +21 -155
  23. package/modules/localmodels/gateway_accept.py +201 -0
  24. package/modules/localmodels/gateway_bifrost.py +30 -193
  25. package/modules/localmodels/gateway_cli.py +15 -6
  26. package/modules/localmodels/gateway_foundations.py +2 -4
  27. package/modules/localmodels/gateway_probe.py +0 -1
  28. package/modules/localmodels/gateway_server.py +2 -3
  29. package/modules/localmodels/gpu_specs.py +12 -0
  30. package/modules/localmodels/guard.py +2 -7
  31. package/modules/localmodels/harness.py +16 -129
  32. package/modules/localmodels/harness_cleanup.py +135 -0
  33. package/modules/localmodels/harness_gateway.py +16 -14
  34. package/modules/localmodels/harness_probe.py +12 -4
  35. package/modules/localmodels/hosts.py +25 -2
  36. package/modules/localmodels/http_local.py +59 -0
  37. package/modules/localmodels/install.py +23 -8
  38. package/modules/localmodels/library_gateway.py +20 -9
  39. package/modules/localmodels/library_jobs.py +125 -28
  40. package/modules/localmodels/library_model.py +10 -0
  41. package/modules/localmodels/library_pricing.py +29 -22
  42. package/modules/localmodels/library_serve.py +17 -1
  43. package/modules/localmodels/library_state.py +15 -2
  44. package/modules/localmodels/library_status.py +30 -0
  45. package/modules/localmodels/llm_rank.py +185 -39
  46. package/modules/localmodels/probe.py +108 -174
  47. package/modules/localmodels/process_identity.py +120 -154
  48. package/modules/localmodels/process_windows.py +86 -0
  49. package/modules/localmodels/recommend.py +6 -3
  50. package/modules/localmodels/recommend_cli.py +14 -6
  51. package/modules/localmodels/remote_ops.py +65 -0
  52. package/modules/localmodels/remote_ops_service.py +14 -2
  53. package/modules/localmodels/runtime_args.py +10 -3
  54. package/modules/localmodels/runtime_auth.py +5 -9
  55. package/modules/localmodels/runtime_cli.py +128 -129
  56. package/modules/localmodels/runtime_discovery.py +84 -0
  57. package/modules/localmodels/runtime_install.py +101 -0
  58. package/modules/localmodels/runtime_releases.py +302 -0
  59. package/modules/localmodels/search_server.py +5 -1
  60. package/modules/localmodels/service_stop.py +8 -108
  61. package/modules/localmodels/service_upgrade.py +394 -63
  62. package/modules/localmodels/services_cli.py +24 -14
  63. package/modules/localmodels/setup_inspection.py +97 -9
  64. package/modules/localmodels/setup_text.py +7 -0
  65. package/modules/localmodels/sizecalc.py +0 -1
  66. package/modules/localmodels/stack.py +45 -235
  67. package/modules/localmodels/stack_arena.py +732 -0
  68. package/modules/localmodels/stack_args.py +21 -12
  69. package/modules/localmodels/stack_auto.py +384 -3
  70. package/modules/localmodels/stack_aux_gpu.py +4 -3
  71. package/modules/localmodels/stack_capacity.py +138 -0
  72. package/modules/localmodels/stack_cleanup.py +9 -4
  73. package/modules/localmodels/stack_cli.py +288 -0
  74. package/modules/localmodels/stack_compose.py +63 -30
  75. package/modules/localmodels/stack_console.py +9 -6
  76. package/modules/localmodels/stack_hardware.py +95 -265
  77. package/modules/localmodels/stack_hardware_text.py +263 -0
  78. package/modules/localmodels/stack_journal.py +3 -9
  79. package/modules/localmodels/stack_ledger.py +48 -18
  80. package/modules/localmodels/stack_lifecycle.py +33 -312
  81. package/modules/localmodels/stack_llm_ram.py +16 -6
  82. package/modules/localmodels/stack_mcp.py +729 -0
  83. package/modules/localmodels/stack_memory.py +0 -2
  84. package/modules/localmodels/stack_picks.py +62 -15
  85. package/modules/localmodels/stack_plan.py +19 -1
  86. package/modules/localmodels/stack_preflight.py +11 -19
  87. package/modules/localmodels/stack_progress.py +9 -1
  88. package/modules/localmodels/stack_remove.py +373 -0
  89. package/modules/localmodels/stack_route.py +101 -17
  90. package/modules/localmodels/stack_run.py +29 -0
  91. package/modules/localmodels/stack_suite.py +21 -10
  92. package/modules/localmodels/stack_summary.py +14 -0
  93. package/modules/localmodels/stack_try.py +238 -24
  94. package/modules/localmodels/stack_try_client.py +53 -15
  95. package/modules/localmodels/stack_try_docs.py +2 -2
  96. package/modules/localmodels/stack_view.py +24 -171
  97. package/modules/localmodels/stack_view_access.py +114 -1
  98. package/modules/localmodels/stack_view_agent.py +3 -13
  99. package/modules/localmodels/stack_view_hub.py +9 -10
  100. package/modules/localmodels/stack_view_llm.py +1 -1
  101. package/modules/localmodels/stack_view_sandbox.py +2 -2
  102. package/modules/localmodels/stack_view_schema.py +183 -0
  103. package/modules/localmodels/stack_view_serve.py +7 -1
  104. package/modules/localmodels/stack_view_service.py +1 -2
  105. package/modules/localmodels/stack_view_text.py +13 -9
  106. package/modules/localmodels/stack_warm.py +48 -4
  107. package/modules/localmodels/stack_warm_store.py +517 -0
  108. package/modules/localmodels/tools.json +32 -18
  109. package/modules/localmodels/transport.py +38 -13
  110. package/modules/localmodels/tui.py +28 -4
  111. package/modules/localmodels/tui_dialogs.py +136 -0
  112. package/modules/localmodels/tui_modals.py +279 -0
  113. package/modules/localmodels/tui_screen.py +113 -154
  114. package/modules/localmodels/tui_views.py +134 -203
  115. package/modules/localmodels/web/index.html +510 -101
  116. package/modules/localmodels/web/sizecalc/app.js +363 -10
  117. package/modules/localmodels/web/sizecalc/page.html +27 -3
  118. package/modules/localmodels/web/view/fleet.html +11 -2
  119. package/modules/localmodels/web/view/fleet.js +191 -17
  120. package/modules/localmodels/web/view/i18n.js +3 -2
  121. package/modules/localmodels/web/view/index.html +1 -1
  122. package/modules/localmodels/web/view/nav.js +22 -3
  123. package/modules/localmodels/web/view/view.css +63 -18
  124. package/modules/localmodels/web/view/view.js +169 -32
  125. package/modules/localmodels/windows_job.py +69 -0
  126. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/METADATA +1 -1
  127. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/RECORD +128 -106
  128. package/package.json +1 -1
  129. package/tool.json +1 -1
  130. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  131. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/WHEEL +0 -0
  132. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/entry_points.txt +0 -0
  133. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/NOTICE +0 -0
  134. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -28,7 +28,7 @@ from localmodels.plan_envelope import PlanError
28
28
  from localmodels.probe import HostFacts, Services
29
29
  from localmodels.runtime_cli import inspect_runtimes
30
30
  from localmodels.setup_text import Lang, text
31
- from localmodels.stack_plan import RAM_FLOOR, StackError, StackPlan, platform_error
31
+ from localmodels.stack_plan import RAM_FLOOR, StackError, StackOptions, StackPlan, platform_error
32
32
 
33
33
 
34
34
  class Reason(TypedDict):
@@ -36,10 +36,28 @@ class Reason(TypedDict):
36
36
  message: str
37
37
 
38
38
 
39
+ class StackMemory(TypedDict, total=False):
40
+ """What the plan needs against what is free now, in bytes; VRAM only for discrete GPUs."""
41
+
42
+ ramAvailableBytes: int
43
+ ramRequiredBytes: int
44
+ vramFreeBytes: int
45
+ vramRequiredBytes: int
46
+
47
+
39
48
  class _Basis(TypedDict, total=False):
40
49
  # "capacity": the plan fits this computer's hardware once other programs release the
41
- # memory they hold now; absent for a plan priced on the memory free now.
50
+ # memory they hold now (``available`` is then false); absent for a plan priced on the
51
+ # memory free now.
42
52
  basis: Literal["capacity"]
53
+ # Since 2026-11-17 (roadmap decision 56), set by inspect_setup: "ready" (an install now
54
+ # plans), "blocked-now" (the hardware can run local models, but an install now would be
55
+ # refused; the reasons say what to change) or "unavailable". Only "ready" is available
56
+ # and recommends local-models. hardwareCapable is null when the facts could not be read.
57
+ state: Literal["ready", "blocked-now", "unavailable"]
58
+ hardwareCapable: bool | None
59
+ # With a capacity plan: the memory the install needs against the memory free now.
60
+ memory: StackMemory
43
61
  # With a plan (since 2026-11-13): the model, every GPU it uses and what it needs, with a
44
62
  # sentence in --lang, so an installer shows the recommendation without composing its own.
45
63
  summary: stack_review.PlanSummary
@@ -108,10 +126,30 @@ def _stack(
108
126
  try:
109
127
  plan = stack.build(options, facts=roomy)
110
128
  except (PlanError, stack.StackError, harness.HarnessError):
111
- pass # the hardware itself is too small; the live refusal stands
129
+ # The hardware itself is too small and the live refusal stands, unless only
130
+ # another inference app on a Mac's GPU stands in the way: that memory is not
131
+ # counted as freeable (roadmap decision 43), but the refusal names the app
132
+ # instead of blaming the hardware.
133
+ if alone := _fits_without_other_inference(options, roomy):
134
+ reason = {
135
+ "code": "plan-unavailable",
136
+ "message": text(
137
+ "inference-app-running",
138
+ lang,
139
+ apps="; ".join(metal.conflicts(facts)),
140
+ ),
141
+ }
142
+ return {
143
+ "available": False,
144
+ "reasons": [reason],
145
+ "plan": alone,
146
+ "basis": "capacity",
147
+ }
112
148
  else:
149
+ # Roadmap decision 56: an install now prices the memory free now and would
150
+ # refuse, so the stack is not available; the plan shows what it needs.
113
151
  return {
114
- "available": True,
152
+ "available": False,
115
153
  "reasons": [_free_memory_reason(facts, roomy, lang)],
116
154
  "plan": plan,
117
155
  "basis": "capacity",
@@ -148,6 +186,25 @@ def _capacity_facts(facts: HostFacts) -> HostFacts | None:
148
186
  return None if roomy == facts else roomy
149
187
 
150
188
 
189
+ def _fits_without_other_inference(options: StackOptions, roomy: HostFacts) -> StackPlan | None:
190
+ """A Mac's capacity plan once the inference apps this tool does not own on its GPU
191
+ (``metal.conflicts``) are quit as well, or None when it still does not fit."""
192
+ if not metal.supported(roomy) or not metal.conflicts(roomy):
193
+ return None
194
+ alone = copy.deepcopy(roomy)
195
+ services = alone["services"]
196
+ assert services is not None # conflicts come from service discovery
197
+ services["compute_processes"] = [
198
+ p
199
+ for p in services.get("compute_processes") or []
200
+ if p["gpu_uuid"] != metal.METAL_UUID or p["owned"] is True
201
+ ]
202
+ try:
203
+ return stack.build(options, facts=alone)
204
+ except (PlanError, stack.StackError, harness.HarnessError):
205
+ return None
206
+
207
+
151
208
  def _free_memory_reason(facts: HostFacts, roomy: HostFacts, lang: Lang = "zh") -> Reason:
152
209
  """Names the memory other programs hold now: each reading the capacity plan counted as freed."""
153
210
  gib = budget.gib
@@ -166,6 +223,33 @@ def _free_memory_reason(facts: HostFacts, roomy: HostFacts, lang: Lang = "zh") -
166
223
  }
167
224
 
168
225
 
226
+ def _classify(availability: StackAvailability, facts: HostFacts) -> None:
227
+ """Sets the stack's state, whether the hardware can run local models, and, for a capacity
228
+ plan, the memory the install needs against the memory free now."""
229
+ codes = {reason["code"] for reason in availability["reasons"]}
230
+ if availability["available"]:
231
+ availability["state"], availability["hardwareCapable"] = "ready", True
232
+ elif availability.get("basis") == "capacity" or "gpu-sharing-required" in codes:
233
+ availability["state"], availability["hardwareCapable"] = "blocked-now", True
234
+ else:
235
+ availability["state"] = "unavailable"
236
+ availability["hardwareCapable"] = None if "facts-unavailable" in codes else False
237
+ plan, summary = availability["plan"], availability.get("summary")
238
+ if availability.get("basis") != "capacity" or plan is None or summary is None:
239
+ return
240
+ memory: StackMemory = {
241
+ "ramAvailableBytes": facts["ram"]["available_bytes"],
242
+ "ramRequiredBytes": summary["memoryBytes"],
243
+ }
244
+ if summary["memoryKind"] == "discrete" and summary["vramBytes"]:
245
+ used = {g["index"] for g in summary["gpus"]}
246
+ memory["vramFreeBytes"] = sum(
247
+ g["free_bytes"] for g in facts.get("gpus") or [] if g["index"] in used
248
+ )
249
+ memory["vramRequiredBytes"] = summary["vramBytes"]
250
+ availability["memory"] = memory
251
+
252
+
169
253
  def _nvidia_cards_unmeasured(facts: HostFacts) -> bool:
170
254
  """An NVIDIA driver is loaded but nvidia-smi listed no card: the cards are unknown, not absent,
171
255
  and planning would fall back to CPU and RAM. A unified-memory part has no nvidia-smi memory
@@ -206,6 +290,7 @@ def inspect_setup(
206
290
  )
207
291
  if availability["plan"] is not None:
208
292
  availability["summary"] = stack_review.summarize(availability["plan"], lang)
293
+ _classify(availability, facts)
209
294
  if unified_memory:
210
295
  try:
211
296
  facts = stack_hardware.assumed(facts, unified_memory)
@@ -248,17 +333,20 @@ INSPECT = (
248
333
  "stack with the existing planner, and check the native agent runtimes (codex, claude, pi) "
249
334
  "on PATH and under --root. Read-only: nothing is installed, downloaded, started or saved; "
250
335
  "without --offline the planner asks the model hub for file pins.\n\nPrints "
251
- "localmodels.setup-report/v1: facts, stack {available, reasons, plan, summary}, harness and "
252
- "recommendation (local-models, else an installed agent runtime, else codex). "
336
+ "localmodels.setup-report/v1: facts, stack {available, state, hardwareCapable, reasons, "
337
+ "plan, summary, memory}, harness and recommendation (local-models only when stack.state is "
338
+ "ready, i.e. an install now would plan; else an installed agent runtime, else codex). "
339
+ "blocked-now: the hardware can run local models but an install now would be refused. "
253
340
  "stack.summary (with a plan) names the model, the GPUs the plan uses and what it needs; "
254
341
  "--lang en gives it and the reasons in English."
255
342
  )
256
343
  INSPECT_REASONS = (
257
344
  "unsupported-platform · facts-unavailable · plan-unavailable · gpu-sharing-required\n"
258
345
  "(the last: a plan fits only beside known busy GPUs; ask, then rerun with --share-gpu)\n"
259
- "free-memory-required (stack.available is true, stack.basis is capacity: the plan fits "
260
- "this computer once other programs release the memory they hold now; `stack plan` still "
261
- "prices the memory free then)"
346
+ "free-memory-required (stack.state is blocked-now, stack.basis is capacity: the plan fits "
347
+ "this computer once other programs release the memory they hold now; stack.memory gives "
348
+ "the RAM free and needed). On a Mac whose hardware fits only once another inference app "
349
+ "on its GPU is quit, plan-unavailable (blocked-now) names that app instead of the hardware"
262
350
  )
263
351
  BINDING = (
264
352
  "Read-only handoff check of a stack that `stack apply` installed from --plan: the plan's "
@@ -45,6 +45,13 @@ MESSAGES: dict[str, tuple[str, str]] = {
45
45
  ),
46
46
  "free-gpu": ("GPU {index} 空闲显存 {free}", "GPU {index} has {free} free"),
47
47
  "free-ram": ("可用内存 {free}", "{free} of RAM is available"),
48
+ "inference-app-running": (
49
+ "这台电脑的硬件可以运行本地模型,但另一个推理程序正占用这台 Mac 的 GPU 与统一内存({apps})。"
50
+ "本工具不会把它的内存算作可释放;请退出该程序后重新检查。",
51
+ "This computer's hardware can run local models, but another inference app holds this "
52
+ "Mac's GPU and unified memory ({apps}). This tool does not count that memory as free; "
53
+ "quit the app and check again.",
54
+ ),
48
55
  "plan-invalid": (
49
56
  "批准计划不存在、无效或摘要不一致。",
50
57
  "The approved plan is missing or invalid, or its digest does not match.",
@@ -22,7 +22,6 @@ from localmodels.memcalc import GIB, KIB, MemcalcError
22
22
  from localmodels.quant_formats import QuantFormat
23
23
 
24
24
  SCHEMA = "localmodels.sizecalc/v1"
25
- MIB = 1 << 20
26
25
 
27
26
  # KV cache guess: f16 K+V bytes one token adds, scaled from Llama-3.1-8B's 128 KiB (32 full
28
27
  # layers x 8 KV heads x 128 x 2 x 2) by active parameters^0.45, which lands within 20% of
@@ -3,13 +3,13 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import argparse
6
- import contextlib
7
6
  import copy
8
7
  import json
9
8
  import os
10
9
  import secrets
11
10
  import subprocess
12
11
  import sys
12
+ import time
13
13
  from collections.abc import Callable
14
14
  from dataclasses import dataclass, replace
15
15
  from pathlib import Path
@@ -17,36 +17,21 @@ from pathlib import Path
17
17
  from localmodels import (
18
18
  app,
19
19
  component,
20
- console,
21
20
  deploy,
22
21
  frontend,
23
22
  gateway,
24
23
  harness,
25
24
  hosts,
26
- stack_card,
27
- stack_client_settings,
28
- stack_down,
29
25
  stack_events,
30
26
  stack_journal,
31
- stack_ledger,
32
- stack_memory,
33
27
  stack_preflight,
34
- stack_progress,
35
- stack_rollback,
36
28
  stack_run,
37
- stack_try,
38
29
  stack_up,
39
30
  stack_update,
40
- stack_view_agent,
41
- stack_view_hub_cli,
42
- stack_warm,
43
- stack_whatif,
44
31
  )
45
32
  from localmodels import stack_decision as decide
46
- from localmodels import stack_doctor as day2
47
33
  from localmodels import stack_hardware as hardware
48
34
  from localmodels import stack_lifecycle as lifecycle
49
- from localmodels import stack_view_serve as board
50
35
  from localmodels.approval import digest, stack_changes
51
36
  from localmodels.contracts import decode
52
37
  from localmodels.plan_envelope import PlanError
@@ -57,7 +42,6 @@ from localmodels.stack_args import add_plan_arguments as add_plan_arguments
57
42
  from localmodels.stack_args import conversation_cache as _conversation_cache
58
43
  from localmodels.stack_args import options_from_args as options_from_args
59
44
  from localmodels.stack_compose import agent_posture, compose, running_record
60
- from localmodels.stack_console import Board
61
45
  from localmodels.stack_plan import (
62
46
  HARNESS_RAM,
63
47
  RAM_FLOOR,
@@ -68,16 +52,12 @@ from localmodels.stack_plan import (
68
52
  StackPlan,
69
53
  StackRecord,
70
54
  StackReplanError,
71
- command,
72
55
  default_options,
73
- guard_details,
74
56
  platform_error,
75
57
  )
76
- from localmodels.stack_progress import JsonlObserver, forward
58
+ from localmodels.stack_progress import forward
77
59
  from localmodels.stack_run import report as report
78
- from localmodels.stack_summary import styled
79
60
  from localmodels.stack_summary import summary as summary
80
- from localmodels.stack_view_service import ServiceError
81
61
 
82
62
  __all__ = [ # this module's API, with the stack_plan names callers reach through it
83
63
  "HARNESS_RAM",
@@ -118,8 +98,8 @@ def build(
118
98
  raw = copy.deepcopy(seen)
119
99
  if seen["platform"] == "win32" and options.get("gateway") == "bifrost":
120
100
  raise StackError( # the default follows the computer planning; --facts may be another's
121
- "Bifrost has no Windows build; plan Windows facts with --gateway magpie, the gateway"
122
- " 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"
123
103
  )
124
104
  seen = hardware.assumed(seen, options.get("unified_memory"))
125
105
  resolver = deploy.catalog_pins if options.get("offline") else deploy.resolve_files
@@ -265,6 +245,15 @@ def _failed(component: str, detail: str, checks: list[gateway.Check] | None = No
265
245
  }
266
246
 
267
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
+
268
257
  # The two ways an approval fails before anything runs: a mistyped code, or a plan file whose
269
258
  # contents no longer hash to the code it was saved with.
270
259
  WRONG_CODE = "the --approve value is not this plan's approval code"
@@ -297,18 +286,25 @@ def apply(
297
286
  raise StackError(error)
298
287
  try:
299
288
  with hosts.stack_apply_lock():
300
- try:
301
- fresh = (
302
- rebuild(plan["options"]) if rebuild else build(plan["options"], approved=plan)
303
- )
304
- except (PlanError, StackError) as exc:
305
- raise StackReplanError(
306
- f"planning again from this computer's current state failed: {exc}. "
307
- "This computer changed, or the plan was made on another machine or "
308
- "with --facts; run stack plan again on this computer",
309
- cause_code="STACK_REPLAN_FAILED",
310
- ) from exc
311
- 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
312
308
  if moved:
313
309
  raise StackGuardError(
314
310
  "this computer's state or artifacts changed since the plan was made ("
@@ -535,207 +531,21 @@ def _run_components(
535
531
  # ---------------------------------------------------------------------------- command line
536
532
 
537
533
 
538
- def _hardware(facts: HostFacts | None, as_json: bool, unified_memory: str | None = None) -> int:
539
- """``stack hardware``: the readings and per-card fits, priced as ``stack plan`` would."""
540
- options = default_options()
541
- if facts is None:
542
- with console.status("Probing this computer's hardware…"):
543
- facts = app.probe(hosts.LOCAL_ID)
544
- read = hardware.assumed(facts, unified_memory)
545
- seen = hardware.view(read, options, agent_posture(options))
546
- if as_json:
547
- json.dump(seen, sys.stdout, ensure_ascii=False, indent=1)
548
- sys.stdout.write("\n")
549
- else:
550
- print("\n".join(hardware.lines(seen, command())))
551
- return 0
552
-
553
-
554
- # Day-2 commands that wait on services get a spinner; remove and rollback may prompt or
555
- # print a plan, and view draws its own screen, so they do not.
556
- _WAITS = {
557
- "status": "Reading each deployment's state and health check…",
558
- "verify": "Sending acceptance requests to the running stack…",
559
- "doctor": "Checking services, ports, gateway and tools…",
560
- "up": "Starting services that are not running and waiting for health checks…",
561
- "down": "Stopping the gateway and the stack's services…",
562
- }
563
-
564
-
565
534
  def _day2(args: argparse.Namespace) -> int:
566
- handlers = {
567
- "up": stack_up.cli,
568
- "down": stack_down.cli,
569
- "warm": stack_warm.cli,
570
- "try": stack_try.cli,
571
- "ledger": stack_ledger.cli,
572
- "card": stack_card.cli,
573
- "rollback": stack_rollback.cli,
574
- "view": board.cli,
575
- "clients": stack_client_settings.cli,
576
- "view-hub": stack_view_hub_cli.cli,
577
- "view-agent": stack_view_agent.cli,
578
- }
579
- run = handlers.get(args.stack_command, day2.cli)
580
- if getattr(args, "json", False) or args.stack_command not in _WAITS:
581
- return run(args)
582
- with console.status(_WAITS[args.stack_command]):
583
- return run(args)
584
-
585
-
586
- def cli(args: argparse.Namespace) -> int:
587
- if args.stack_command == "capabilities":
588
- stack_run.capabilities()
589
- return 0
590
- try:
591
- if args.stack_command in (
592
- *day2.COMMANDS,
593
- "up",
594
- "down",
595
- "warm",
596
- "try",
597
- "ledger",
598
- "card",
599
- "rollback",
600
- "view",
601
- "clients",
602
- "view-hub",
603
- "view-agent",
604
- ):
605
- return _day2(args)
606
- if args.stack_command == "decisions":
607
- print(decide.listing())
608
- return 0
609
- if args.stack_command == "memory":
610
- return stack_memory.cli(args)
611
- if args.stack_command == "what-if":
612
- return stack_whatif.cli(args)
613
- facts = (
614
- decode(json.loads(args.facts.read_text(encoding="utf-8")), HostFacts)
615
- if getattr(args, "facts", None)
616
- else None
617
- )
618
- if args.stack_command == "hardware":
619
- return _hardware(facts, args.json, args.unified_memory)
620
- if args.stack_command == "plan":
621
- options = stack_update.requested(
622
- options_from_args(args), args.update, getattr(args, "component_selections", ())
623
- )
624
- with console.status(
625
- "Probing this computer and pricing the whole stack…"
626
- if facts is None
627
- else "Pricing the whole stack…"
628
- ):
629
- plan = build(options, facts=facts)
630
- path = save(plan, args.out)
631
- if args.json:
632
- json.dump(plan, sys.stdout, ensure_ascii=False, indent=1)
633
- sys.stdout.write("\n")
634
- else:
635
- print(styled(summary(plan, path)))
636
- return 0
637
- return _apply_cli(args)
638
- except (
639
- StackError,
640
- PlanError,
641
- harness.HarnessError,
642
- ServiceError,
643
- ValueError,
644
- KeyError,
645
- ) as exc:
646
- if getattr(args, "jsonl", False):
647
- return stack_progress.error(2, guard_details(exc))
648
- print(f"stack: {exc}", file=sys.stderr)
649
- return 2
650
-
651
-
652
- def _mistyped_code(exc: BaseException, plan: StackPlan | None) -> bool:
653
- """The approval failed while the plan file is intact: the code given was wrong, so the plan's
654
- own apply line can be shown (an edited plan has no valid code to show)."""
655
- return (
656
- isinstance(exc, StackGuardError)
657
- and exc.cause_code == "STACK_APPROVAL_MISMATCH"
658
- and plan is not None
659
- and digest(plan) == plan["plan_id"]
660
- )
661
-
535
+ from localmodels import stack_cli
662
536
 
663
- def _apply_cli(args: argparse.Namespace) -> int:
664
- machine = args.json
665
- jsonl = getattr(args, "jsonl", False)
666
- attempt_ids: list[str] = []
667
- plan_id: str | None = None
668
- loaded: StackPlan | None = None
669
-
670
- def machine_error(exc: BaseException) -> int:
671
- interrupted = isinstance(exc, KeyboardInterrupt)
672
- return stack_run.machine_result(
673
- None,
674
- "interrupted" if interrupted else "failed" if attempt_ids else "rejected",
675
- "130" if interrupted else "1" if attempt_ids else "2",
676
- plan_id=plan_id,
677
- attempt_id=attempt_ids[-1] if attempt_ids else None,
678
- cause=stack_run.cause_of(exc, started=bool(attempt_ids)),
679
- )
537
+ return stack_cli.day2(args)
680
538
 
681
- def emit_progress(event: stack_events.ProgressEvent) -> None:
682
- print(json.dumps(event, separators=(",", ":")), file=sys.stderr, flush=True)
683
539
 
684
- progress = (
685
- emit_progress
686
- if machine or (not jsonl and os.environ.get("LOCALMODELS_PROGRESS_JSON") == "1")
687
- else None
540
+ def cli(args: argparse.Namespace) -> int:
541
+ from localmodels import stack_cli
542
+
543
+ return stack_cli.run_cli(
544
+ args,
545
+ build=build,
546
+ save=save,
547
+ load=load,
548
+ apply=apply,
549
+ report=report,
550
+ day2_fn=_day2,
688
551
  )
689
- log: Log = JsonlObserver(sys.stdout) if jsonl else lambda _m: None
690
- shown: Board | None = None
691
- stack_run.cancel_on_sigterm()
692
- try:
693
- plan = loaded = load(args.plan)
694
- plan_id = stack_run.safe_digest(plan["plan_id"])
695
- if not (jsonl or machine):
696
- log = shown = Board.for_plan(plan)
697
- with shown or contextlib.nullcontext():
698
- record = apply(
699
- plan,
700
- args.approve,
701
- log=log,
702
- on_progress=progress,
703
- on_attempt=attempt_ids.append if machine else None,
704
- )
705
- except KeyboardInterrupt as exc:
706
- if jsonl:
707
- return stack_progress.error(130, guard_details(exc))
708
- if machine:
709
- return machine_error(exc)
710
- print("stack: interrupted", file=sys.stderr)
711
- return 130
712
- except Exception as exc:
713
- if jsonl:
714
- return stack_progress.error(2, guard_details(exc))
715
- if machine:
716
- return machine_error(exc)
717
- if isinstance(exc, StackError | PlanError | harness.HarnessError | ValueError | KeyError):
718
- print(f"stack: {exc}", file=sys.stderr)
719
- if _mistyped_code(exc, loaded):
720
- assert loaded is not None
721
- print(
722
- f" this plan's apply line: {command()} stack apply {args.plan} "
723
- f"--approve {loaded['plan_id']}",
724
- file=sys.stderr,
725
- )
726
- return 2
727
- raise
728
- if args.stack_command == "apply" and args.json:
729
- return stack_run.machine_result(
730
- record,
731
- "completed" if record["ok"] else "failed",
732
- "0" if record["ok"] else "1",
733
- plan=plan,
734
- )
735
- if jsonl:
736
- return stack_progress.result(
737
- record["ok"],
738
- ((c["component"], c["status"]) for c in record["components"]),
739
- profile=record.get("profile"),
740
- )
741
- return report(record, timing=shown.timing() if shown else None)