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

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 (121) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +119 -98
  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_config.py +188 -0
  7. package/modules/localmodels/budget.py +13 -2
  8. package/modules/localmodels/catalog.py +51 -320
  9. package/modules/localmodels/catalog_add.py +2 -8
  10. package/modules/localmodels/catalog_recipes.py +321 -0
  11. package/modules/localmodels/cli_parser.py +4 -1
  12. package/modules/localmodels/console.py +5 -4
  13. package/modules/localmodels/contracts.py +13 -3
  14. package/modules/localmodels/debug_cli.py +158 -0
  15. package/modules/localmodels/debug_mode.py +727 -0
  16. package/modules/localmodels/debug_stub_server.py +192 -0
  17. package/modules/localmodels/decode_calibration.json +1 -1
  18. package/modules/localmodels/decode_calibration.py +34 -17
  19. package/modules/localmodels/gateway.py +21 -155
  20. package/modules/localmodels/gateway_accept.py +201 -0
  21. package/modules/localmodels/gateway_bifrost.py +19 -184
  22. package/modules/localmodels/gateway_cli.py +11 -4
  23. package/modules/localmodels/gateway_foundations.py +2 -4
  24. package/modules/localmodels/gateway_probe.py +0 -1
  25. package/modules/localmodels/gateway_server.py +2 -3
  26. package/modules/localmodels/gpu_specs.py +12 -0
  27. package/modules/localmodels/guard.py +2 -7
  28. package/modules/localmodels/harness.py +16 -129
  29. package/modules/localmodels/harness_cleanup.py +135 -0
  30. package/modules/localmodels/harness_gateway.py +16 -14
  31. package/modules/localmodels/harness_probe.py +12 -4
  32. package/modules/localmodels/hosts.py +25 -2
  33. package/modules/localmodels/http_local.py +59 -0
  34. package/modules/localmodels/install.py +23 -8
  35. package/modules/localmodels/library_gateway.py +9 -9
  36. package/modules/localmodels/library_jobs.py +76 -27
  37. package/modules/localmodels/library_serve.py +12 -1
  38. package/modules/localmodels/library_state.py +6 -1
  39. package/modules/localmodels/llm_rank.py +102 -9
  40. package/modules/localmodels/probe.py +108 -174
  41. package/modules/localmodels/process_identity.py +109 -154
  42. package/modules/localmodels/process_windows.py +86 -0
  43. package/modules/localmodels/recommend.py +1 -1
  44. package/modules/localmodels/recommend_cli.py +14 -6
  45. package/modules/localmodels/remote_ops.py +65 -0
  46. package/modules/localmodels/remote_ops_service.py +14 -2
  47. package/modules/localmodels/runtime_args.py +10 -3
  48. package/modules/localmodels/runtime_auth.py +5 -9
  49. package/modules/localmodels/runtime_cli.py +128 -129
  50. package/modules/localmodels/runtime_discovery.py +84 -0
  51. package/modules/localmodels/runtime_install.py +101 -0
  52. package/modules/localmodels/runtime_releases.py +302 -0
  53. package/modules/localmodels/service_stop.py +8 -108
  54. package/modules/localmodels/service_upgrade.py +394 -63
  55. package/modules/localmodels/services_cli.py +24 -14
  56. package/modules/localmodels/setup_inspection.py +97 -9
  57. package/modules/localmodels/setup_text.py +7 -0
  58. package/modules/localmodels/sizecalc.py +0 -1
  59. package/modules/localmodels/stack.py +14 -221
  60. package/modules/localmodels/stack_arena.py +732 -0
  61. package/modules/localmodels/stack_args.py +15 -9
  62. package/modules/localmodels/stack_auto.py +384 -3
  63. package/modules/localmodels/stack_aux_gpu.py +4 -3
  64. package/modules/localmodels/stack_capacity.py +138 -0
  65. package/modules/localmodels/stack_cleanup.py +9 -4
  66. package/modules/localmodels/stack_cli.py +286 -0
  67. package/modules/localmodels/stack_compose.py +58 -25
  68. package/modules/localmodels/stack_console.py +9 -6
  69. package/modules/localmodels/stack_hardware.py +92 -263
  70. package/modules/localmodels/stack_hardware_text.py +263 -0
  71. package/modules/localmodels/stack_journal.py +3 -9
  72. package/modules/localmodels/stack_ledger.py +48 -18
  73. package/modules/localmodels/stack_lifecycle.py +33 -312
  74. package/modules/localmodels/stack_mcp.py +729 -0
  75. package/modules/localmodels/stack_memory.py +0 -2
  76. package/modules/localmodels/stack_picks.py +59 -12
  77. package/modules/localmodels/stack_plan.py +19 -1
  78. package/modules/localmodels/stack_preflight.py +11 -19
  79. package/modules/localmodels/stack_remove.py +373 -0
  80. package/modules/localmodels/stack_route.py +101 -17
  81. package/modules/localmodels/stack_suite.py +11 -7
  82. package/modules/localmodels/stack_summary.py +14 -0
  83. package/modules/localmodels/stack_try.py +238 -24
  84. package/modules/localmodels/stack_try_client.py +53 -15
  85. package/modules/localmodels/stack_try_docs.py +2 -2
  86. package/modules/localmodels/stack_view.py +24 -171
  87. package/modules/localmodels/stack_view_access.py +114 -1
  88. package/modules/localmodels/stack_view_agent.py +3 -13
  89. package/modules/localmodels/stack_view_hub.py +9 -10
  90. package/modules/localmodels/stack_view_llm.py +1 -1
  91. package/modules/localmodels/stack_view_sandbox.py +2 -2
  92. package/modules/localmodels/stack_view_schema.py +183 -0
  93. package/modules/localmodels/stack_view_serve.py +7 -1
  94. package/modules/localmodels/stack_view_service.py +1 -2
  95. package/modules/localmodels/stack_view_text.py +13 -9
  96. package/modules/localmodels/stack_warm.py +3 -0
  97. package/modules/localmodels/stack_warm_store.py +517 -0
  98. package/modules/localmodels/tui.py +28 -4
  99. package/modules/localmodels/tui_dialogs.py +136 -0
  100. package/modules/localmodels/tui_modals.py +279 -0
  101. package/modules/localmodels/tui_screen.py +113 -154
  102. package/modules/localmodels/tui_views.py +134 -203
  103. package/modules/localmodels/web/index.html +510 -101
  104. package/modules/localmodels/web/sizecalc/app.js +363 -10
  105. package/modules/localmodels/web/sizecalc/page.html +27 -3
  106. package/modules/localmodels/web/view/fleet.html +11 -2
  107. package/modules/localmodels/web/view/fleet.js +191 -17
  108. package/modules/localmodels/web/view/i18n.js +3 -2
  109. package/modules/localmodels/web/view/index.html +1 -1
  110. package/modules/localmodels/web/view/nav.js +22 -3
  111. package/modules/localmodels/web/view/view.css +63 -18
  112. package/modules/localmodels/web/view/view.js +169 -32
  113. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
  114. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +115 -94
  115. package/package.json +1 -1
  116. package/tool.json +1 -1
  117. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  118. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
  119. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
  120. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
  121. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.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,7 +3,6 @@
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
@@ -17,36 +16,21 @@ from pathlib import Path
17
16
  from localmodels import (
18
17
  app,
19
18
  component,
20
- console,
21
19
  deploy,
22
20
  frontend,
23
21
  gateway,
24
22
  harness,
25
23
  hosts,
26
- stack_card,
27
- stack_client_settings,
28
- stack_down,
29
24
  stack_events,
30
25
  stack_journal,
31
- stack_ledger,
32
- stack_memory,
33
26
  stack_preflight,
34
- stack_progress,
35
- stack_rollback,
36
27
  stack_run,
37
- stack_try,
38
28
  stack_up,
39
29
  stack_update,
40
- stack_view_agent,
41
- stack_view_hub_cli,
42
- stack_warm,
43
- stack_whatif,
44
30
  )
45
31
  from localmodels import stack_decision as decide
46
- from localmodels import stack_doctor as day2
47
32
  from localmodels import stack_hardware as hardware
48
33
  from localmodels import stack_lifecycle as lifecycle
49
- from localmodels import stack_view_serve as board
50
34
  from localmodels.approval import digest, stack_changes
51
35
  from localmodels.contracts import decode
52
36
  from localmodels.plan_envelope import PlanError
@@ -57,7 +41,6 @@ from localmodels.stack_args import add_plan_arguments as add_plan_arguments
57
41
  from localmodels.stack_args import conversation_cache as _conversation_cache
58
42
  from localmodels.stack_args import options_from_args as options_from_args
59
43
  from localmodels.stack_compose import agent_posture, compose, running_record
60
- from localmodels.stack_console import Board
61
44
  from localmodels.stack_plan import (
62
45
  HARNESS_RAM,
63
46
  RAM_FLOOR,
@@ -68,16 +51,12 @@ from localmodels.stack_plan import (
68
51
  StackPlan,
69
52
  StackRecord,
70
53
  StackReplanError,
71
- command,
72
54
  default_options,
73
- guard_details,
74
55
  platform_error,
75
56
  )
76
- from localmodels.stack_progress import JsonlObserver, forward
57
+ from localmodels.stack_progress import forward
77
58
  from localmodels.stack_run import report as report
78
- from localmodels.stack_summary import styled
79
59
  from localmodels.stack_summary import summary as summary
80
- from localmodels.stack_view_service import ServiceError
81
60
 
82
61
  __all__ = [ # this module's API, with the stack_plan names callers reach through it
83
62
  "HARNESS_RAM",
@@ -535,207 +514,21 @@ def _run_components(
535
514
  # ---------------------------------------------------------------------------- command line
536
515
 
537
516
 
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
517
  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
- )
518
+ from localmodels import stack_cli
661
519
 
520
+ return stack_cli.day2(args)
662
521
 
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
- )
680
-
681
- def emit_progress(event: stack_events.ProgressEvent) -> None:
682
- print(json.dumps(event, separators=(",", ":")), file=sys.stderr, flush=True)
683
522
 
684
- progress = (
685
- emit_progress
686
- if machine or (not jsonl and os.environ.get("LOCALMODELS_PROGRESS_JSON") == "1")
687
- else None
523
+ def cli(args: argparse.Namespace) -> int:
524
+ from localmodels import stack_cli
525
+
526
+ return stack_cli.run_cli(
527
+ args,
528
+ build=build,
529
+ save=save,
530
+ load=load,
531
+ apply=apply,
532
+ report=report,
533
+ day2_fn=_day2,
688
534
  )
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)