@simplexai/localmodels-darwin-x64 0.1.0-dev.104 → 0.1.0-dev.105

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 (81) hide show
  1. package/README.md +1 -1
  2. package/bootstrap.identity +1 -1
  3. package/bootstrap.sha256 +80 -78
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +204 -86
  6. package/modules/localmodels/apple_sensors.py +23 -0
  7. package/modules/localmodels/approval.py +25 -2
  8. package/modules/localmodels/catalog.json +454 -31
  9. package/modules/localmodels/catalog.py +11 -0
  10. package/modules/localmodels/catalog_recipes.py +61 -3
  11. package/modules/localmodels/cli_help.py +10 -0
  12. package/modules/localmodels/cli_parser.py +313 -230
  13. package/modules/localmodels/component.py +20 -2
  14. package/modules/localmodels/custom_probe.py +4 -2
  15. package/modules/localmodels/deploy.py +11 -1
  16. package/modules/localmodels/engine_adapters/suite_plan.py +21 -21
  17. package/modules/localmodels/host_sensors.py +25 -2
  18. package/modules/localmodels/hosts.py +26 -5
  19. package/modules/localmodels/library_cli.py +34 -16
  20. package/modules/localmodels/library_custom.py +9 -1
  21. package/modules/localmodels/library_direct.py +41 -1
  22. package/modules/localmodels/library_jobs.py +23 -4
  23. package/modules/localmodels/library_model.py +146 -1
  24. package/modules/localmodels/library_order.py +175 -69
  25. package/modules/localmodels/library_poly.py +42 -11
  26. package/modules/localmodels/library_presentation.py +485 -0
  27. package/modules/localmodels/library_pricing.py +3 -1
  28. package/modules/localmodels/library_serve.py +208 -3
  29. package/modules/localmodels/library_state.py +47 -10
  30. package/modules/localmodels/library_status.py +29 -16
  31. package/modules/localmodels/llm_rank.py +9 -3
  32. package/modules/localmodels/plan_envelope.py +11 -2
  33. package/modules/localmodels/probe.py +34 -7
  34. package/modules/localmodels/quant_formats.py +9 -2
  35. package/modules/localmodels/records.py +19 -2
  36. package/modules/localmodels/remote_ops_verify.py +91 -24
  37. package/modules/localmodels/runtime_index.py +303 -0
  38. package/modules/localmodels/setup_inspection.py +22 -3
  39. package/modules/localmodels/speech_cli.py +20 -14
  40. package/modules/localmodels/speech_serve.py +9 -2
  41. package/modules/localmodels/speech_server.py +3 -0
  42. package/modules/localmodels/stack_args.py +270 -139
  43. package/modules/localmodels/stack_auto.py +90 -5
  44. package/modules/localmodels/stack_cli.py +117 -116
  45. package/modules/localmodels/stack_compose.py +5 -1
  46. package/modules/localmodels/stack_debug.py +14 -4
  47. package/modules/localmodels/stack_down.py +2 -0
  48. package/modules/localmodels/stack_hardware.py +14 -12
  49. package/modules/localmodels/stack_mlx.py +8 -1
  50. package/modules/localmodels/stack_picks.py +19 -20
  51. package/modules/localmodels/stack_plan.py +3 -2
  52. package/modules/localmodels/stack_review.py +28 -7
  53. package/modules/localmodels/stack_suite.py +11 -9
  54. package/modules/localmodels/stack_up.py +2 -0
  55. package/modules/localmodels/stack_view.py +180 -35
  56. package/modules/localmodels/stack_view_demo.py +2 -0
  57. package/modules/localmodels/stack_view_gpu.py +36 -2
  58. package/modules/localmodels/stack_view_schema.py +26 -3
  59. package/modules/localmodels/stack_view_slots.py +3 -1
  60. package/modules/localmodels/stack_view_telemetry.py +90 -4
  61. package/modules/localmodels/stack_view_tick.py +246 -40
  62. package/modules/localmodels/stack_view_words.py +7 -0
  63. package/modules/localmodels/stack_whatif_html.py +9 -12
  64. package/modules/localmodels/suite.py +129 -2
  65. package/modules/localmodels/telemetry_math.py +458 -18
  66. package/modules/localmodels/transport.py +8 -1
  67. package/modules/localmodels/tts_cli.py +24 -20
  68. package/modules/localmodels/tts_serve.py +9 -2
  69. package/modules/localmodels/tts_sidecar.py +3 -0
  70. package/modules/localmodels/web/whatif/app.js +1 -1
  71. package/modules/localmodels/web/whatif/sim.js +8 -14
  72. package/modules/localmodels/win_probe.py +89 -16
  73. package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/METADATA +1 -1
  74. package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/RECORD +76 -74
  75. package/package.json +1 -1
  76. package/tool.json +1 -1
  77. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/WHEEL +0 -0
  78. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/entry_points.txt +0 -0
  79. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/licenses/LICENSE +0 -0
  80. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/licenses/NOTICE +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev104.dist-info → simplex_localmodels-0.1.0.dev105.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -3,10 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import contextlib
6
+ import importlib
6
7
  import json
7
8
  import os
8
9
  import sys
9
- from collections.abc import Callable, Iterator
10
+ from collections.abc import Callable, Iterator, Sequence
10
11
  from typing import TYPE_CHECKING, Any
11
12
 
12
13
  if TYPE_CHECKING:
@@ -17,31 +18,15 @@ if TYPE_CHECKING:
17
18
  __version__,
18
19
  app,
19
20
  approval,
20
- catalog_add,
21
21
  catalog_license,
22
22
  cli_help,
23
23
  console,
24
- debug_cli,
25
- debug_mode,
26
24
  deploy,
27
- desktop,
28
25
  discovery,
29
- guard,
30
26
  hf_repo,
31
27
  hosts,
32
- install,
33
- library_cli,
34
- memcalc_cli,
35
- plan_envelope,
36
28
  recommend_cli,
37
- runtime_cli,
38
- services_cli,
39
- setup_inspection,
40
- sizecalc_cli,
41
- speech_cli,
42
- stack_cli,
43
29
  stack_lifecycle,
44
- tts_cli,
45
30
  )
46
31
  from localmodels import catalog as cat
47
32
  from localmodels.catalog import load_catalog_file
@@ -53,48 +38,66 @@ if TYPE_CHECKING:
53
38
  from localmodels.stack_console import Board
54
39
  from localmodels.stack_plan import command
55
40
 
56
- _DEPS_LOADED = False
57
- _LAZY_MODULES = (
58
- "app approval catalog_add catalog_license cli_help console debug_cli debug_mode deploy desktop "
59
- "discovery guard hf_repo hosts install library_cli memcalc_cli "
60
- "plan_envelope recommend_cli runtime_cli services_cli setup_inspection sizecalc_cli "
61
- "speech_cli stack_cli stack_lifecycle tts_cli"
62
- )
63
- _LAZY_ATTRS = (
64
- ("__version__", "localmodels", "__version__"),
65
- ("cat", "localmodels.catalog", None),
66
- ("gib", "localmodels.planning.budget", "gib"),
67
- ("load_catalog_file", "localmodels.catalog", "load_catalog_file"),
68
- ("argument_parser", "localmodels.cli_parser", "argument_parser"),
69
- ("window_k", "localmodels.context_policy", "window_k"),
70
- ("Board", "localmodels.stack_console", "Board"),
71
- ("command", "localmodels.stack_plan", "command"),
41
+ _LAZY_MODULES = frozenset(
42
+ (
43
+ "app approval catalog_add catalog_license cli_help console debug_cli debug_mode deploy "
44
+ "desktop discovery guard hf_repo hosts install library_cli memcalc_cli "
45
+ "plan_envelope recommend_cli runtime_cli services_cli setup_inspection sizecalc_cli "
46
+ "speech_cli stack_cli stack_lifecycle tts_cli"
47
+ ).split()
72
48
  )
49
+ _LAZY_STDLIB = frozenset(("argparse", "difflib"))
50
+ _LAZY_ATTRS: dict[str, tuple[str, str | None]] = {
51
+ "__version__": ("localmodels", "__version__"),
52
+ "cat": ("localmodels.catalog", None),
53
+ "gib": ("localmodels.planning.budget", "gib"),
54
+ "load_catalog_file": ("localmodels.catalog", "load_catalog_file"),
55
+ "argument_parser": ("localmodels.cli_parser", "argument_parser"),
56
+ "window_k": ("localmodels.context_policy", "window_k"),
57
+ "Board": ("localmodels.stack_console", "Board"),
58
+ "command": ("localmodels.cli_help", "command"),
59
+ }
60
+ _MODULE_COMMANDS: dict[str, str] = {
61
+ "guard": "guard",
62
+ "memcalc": "memcalc_cli",
63
+ "sizecalc": "sizecalc_cli",
64
+ "catalog": "catalog_add",
65
+ "install": "install",
66
+ "harness": "runtime_cli",
67
+ "setup": "setup_inspection",
68
+ "foundations": "services_cli",
69
+ "library": "library_cli",
70
+ "speech": "speech_cli",
71
+ "tts": "tts_cli",
72
+ "debug": "debug_cli",
73
+ }
73
74
 
74
75
 
75
- def _load_cli_deps() -> None:
76
- global _DEPS_LOADED
77
- if _DEPS_LOADED:
78
- return
79
- import argparse
80
- import difflib
81
- import importlib
82
-
76
+ def _load(name: str) -> Any:
83
77
  ns = globals()
84
- ns["argparse"], ns["difflib"] = argparse, difflib
85
- for name in _LAZY_MODULES.split():
86
- ns[name] = importlib.import_module(f"localmodels.{name}")
87
- for alias, mod_name, attr in _LAZY_ATTRS:
78
+ if name in ns:
79
+ return ns[name]
80
+ if name in _LAZY_STDLIB:
81
+ value: Any = importlib.import_module(name)
82
+ elif name in _LAZY_MODULES:
83
+ value = importlib.import_module(f"localmodels.{name}")
84
+ elif name in _LAZY_ATTRS:
85
+ mod_name, attr = _LAZY_ATTRS[name]
88
86
  mod = importlib.import_module(mod_name)
89
- ns[alias] = mod if attr is None else getattr(mod, attr)
90
- _DEPS_LOADED = True
87
+ value = mod if attr is None else getattr(mod, attr)
88
+ else:
89
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
90
+ ns[name] = value
91
+ return value
92
+
93
+
94
+ def _load_many(*names: str) -> None:
95
+ for name in names:
96
+ _load(name)
91
97
 
92
98
 
93
99
  def __getattr__(name: str) -> Any:
94
- _load_cli_deps()
95
- if name in globals():
96
- return globals()[name]
97
- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
100
+ return _load(name)
98
101
 
99
102
 
100
103
  _FLAG_PREVIEW = 40
@@ -103,6 +106,7 @@ _FLAG_PREVIEW = 40
103
106
  def _device(target: str) -> tuple[str, HostFacts | None]:
104
107
  """Registered device id, plus fresh facts when this call added a new SSH target. A new
105
108
  target is probed once at registration and kept only when that probe succeeds."""
109
+ _load_many("hosts", "app")
106
110
  if target == hosts.LOCAL_ID or any(d["id"] == target for d in hosts.devices()):
107
111
  return target, None
108
112
  dev, facts = app.register_device(target)
@@ -115,8 +119,7 @@ def _print(data: object) -> None:
115
119
 
116
120
 
117
121
  def _width(text: str) -> int:
118
- _load_cli_deps()
119
- return console.cells(text)
122
+ return int(_load("console").cells(text))
120
123
 
121
124
 
122
125
  def _pad(text: str, width: int) -> str:
@@ -138,6 +141,7 @@ def _shown_facts(facts: HostFacts) -> dict[str, object]:
138
141
 
139
142
  def _host_hint(target: str) -> str:
140
143
  """Closest registered or ssh_config device names when the operator may have mistyped."""
144
+ _load_many("hosts", "discovery", "difflib")
141
145
  names = {
142
146
  name
143
147
  for device in hosts.devices()
@@ -149,12 +153,14 @@ def _host_hint(target: str) -> str:
149
153
 
150
154
 
151
155
  def _model_hint(model_id: str) -> str:
156
+ _load_many("load_catalog_file", "hf_repo")
152
157
  ids = [entry.id for entry in load_catalog_file()]
153
158
  shown = hf_repo.close_ids(model_id, ids) or ids
154
159
  return f"model ids: {', '.join(shown)} (the models command lists them all)"
155
160
 
156
161
 
157
162
  def _service_hint(dev_id: str) -> str:
163
+ _load("hosts")
158
164
  names = [record["plan"]["name"] for record in hosts.records(dev_id)]
159
165
  shown = ", ".join(names) if names else "none"
160
166
  return f"deployment records on {dev_id}: {shown} (see the services command)"
@@ -168,6 +174,7 @@ def _fail(message: str, *, hint: str = "") -> int:
168
174
 
169
175
 
170
176
  def _devices_list() -> int:
177
+ _load_many("hosts", "console")
171
178
  for device in hosts.devices():
172
179
  facts = hosts.load_facts(device["id"])
173
180
  gpus = facts["gpus"] if facts else []
@@ -188,6 +195,7 @@ def _devices_list() -> int:
188
195
 
189
196
 
190
197
  def _devices_remove(dev_id: str) -> int:
198
+ _load("hosts")
191
199
  if dev_id == hosts.LOCAL_ID:
192
200
  return _fail("本机不能移除")
193
201
  hosts.get_device(dev_id)
@@ -208,11 +216,13 @@ _TASK_LABELS = {
208
216
 
209
217
 
210
218
  def _status_label(entry: cat.CatalogEntry) -> str:
219
+ _load("recommend_cli")
211
220
  return recommend_cli.status_label(entry.status, entry.validated_on)
212
221
 
213
222
 
214
223
  def _discover() -> int:
215
224
  """Candidates as an aligned table (CJK names included), then how to register one."""
225
+ _load_many("discovery", "console", "command")
216
226
  found = discovery.discover()
217
227
  if not found:
218
228
  print("没有找到候选设备:~/.ssh/config、Tailscale 和 mDNS 都没有给出主机。")
@@ -239,6 +249,15 @@ def _discover() -> int:
239
249
 
240
250
 
241
251
  def _models_list() -> int:
252
+ _load_many(
253
+ "load_catalog_file",
254
+ "gib",
255
+ "window_k",
256
+ "console",
257
+ "cat",
258
+ "recommend_cli",
259
+ "catalog_license",
260
+ )
242
261
  print("主 LLM(默认 llama.cpp;MLX 候选仅用于显式 macos-mlx-preview)")
243
262
  rows = [["id", "名称", "量化", "最小下载", "上下文", "状态", "许可", "特性"]]
244
263
  for entry in load_catalog_file():
@@ -286,6 +305,7 @@ def _models_list() -> int:
286
305
 
287
306
 
288
307
  def _services_list(host: str) -> int:
308
+ _load_many("hosts", "command")
289
309
  dev = hosts.get_device(host)
290
310
  records = hosts.records(dev["id"])
291
311
  if not records:
@@ -305,6 +325,7 @@ def _services_list(host: str) -> int:
305
325
 
306
326
 
307
327
  def _recommend(target: str, *, refresh: bool = False, all_models: bool = False) -> int:
328
+ _load_many("app", "console", "gib", "recommend_cli", "command", "cat")
308
329
  dev_id, first_facts = _device(target)
309
330
  if first_facts is not None:
310
331
  print("首次登记已完成探测,以下读取已保存的硬件快照。")
@@ -391,6 +412,7 @@ def _recommend(target: str, *, refresh: bool = False, all_models: bool = False)
391
412
 
392
413
  def _deploy_board(plan: Plan) -> Board:
393
414
  """Single-model deploy as a one-row progress board (the stack's live view)."""
415
+ _load("Board")
394
416
  model = plan["model"]
395
417
  title = f"部署 {model['display_name']} {model['quant']}".rstrip()
396
418
  return Board([("model", plan["name"])], title)
@@ -420,6 +442,7 @@ def _deploy_events(board: Board) -> Callable[[str, ProgressEvent], None]:
420
442
 
421
443
  def _commands(args: argparse.Namespace, scope: list[str]) -> int:
422
444
  """``commands`` and ``stack commands``: the argument tree as text or JSON."""
445
+ _load_many("argument_parser", "cli_help", "command", "__version__")
423
446
  node = argument_parser()
424
447
  for name in scope:
425
448
  found = cli_help.subcommands(node)
@@ -437,6 +460,7 @@ def _commands(args: argparse.Namespace, scope: list[str]) -> int:
437
460
 
438
461
 
439
462
  def _completion(args: argparse.Namespace) -> int:
463
+ _load_many("argument_parser", "cli_help")
440
464
  tree = list(cli_help.walk(argument_parser()))
441
465
  sys.stdout.write(cli_help.completion(tree, "localmodels", args.shell))
442
466
  return 0
@@ -467,32 +491,13 @@ def _english_system_messages() -> Iterator[None]:
467
491
  def _stack(args: argparse.Namespace) -> int:
468
492
  with _english_system_messages():
469
493
  if args.stack_command == "install":
470
- return install.cli(args)
494
+ return int(_load("install").cli(args))
471
495
  if args.stack_command == "commands":
472
496
  return _commands(args, ["stack"])
473
- return stack_cli.cli(args)
497
+ return int(_load("stack_cli").cli(args))
474
498
 
475
499
 
476
- def _run(args: argparse.Namespace) -> int:
477
- commands: dict[str, Callable[[argparse.Namespace], int]] = {
478
- "guard": guard.cli,
479
- "stack": _stack,
480
- "memcalc": memcalc_cli.cli,
481
- "sizecalc": sizecalc_cli.cli,
482
- "catalog": catalog_add.cli,
483
- "install": install.cli,
484
- "harness": runtime_cli.cli,
485
- "setup": setup_inspection.cli,
486
- "foundations": services_cli.cli,
487
- "library": library_cli.cli,
488
- "speech": speech_cli.cli,
489
- "tts": tts_cli.cli,
490
- "debug": debug_cli.cli,
491
- "commands": lambda parsed: _commands(parsed, list(parsed.path)),
492
- "completion": _completion,
493
- }
494
- if args.command in commands:
495
- return commands[args.command](args)
500
+ def _run_inline(args: argparse.Namespace) -> int:
496
501
  if args.command == "devices":
497
502
  return _devices_remove(args.id) if args.devices_command == "remove" else _devices_list()
498
503
  if args.command == "models":
@@ -500,7 +505,7 @@ def _run(args: argparse.Namespace) -> int:
500
505
  if args.command == "services":
501
506
  return _services_list(args.host)
502
507
  if args.command == "desktop-snapshot":
503
- desktop_result = desktop.snapshot(refresh=args.refresh)
508
+ desktop_result = _load("desktop").snapshot(refresh=args.refresh)
504
509
  _print(desktop_result)
505
510
  if not desktop_result["ok"] and desktop_result["observation"].get("state") == "unknown":
506
511
  print("提示:尚无本机快照;加 --refresh 运行一次只读本机探测。", file=sys.stderr)
@@ -508,6 +513,7 @@ def _run(args: argparse.Namespace) -> int:
508
513
  if args.command == "discover":
509
514
  return _discover()
510
515
  if args.command == "probe":
516
+ _load_many("console", "app")
511
517
  with console.status(f"探测 {args.host}…"):
512
518
  dev_id, fresh = _device(args.host)
513
519
  if args.measure_bandwidth:
@@ -518,7 +524,7 @@ def _run(args: argparse.Namespace) -> int:
518
524
  if args.command == "recommend":
519
525
  return _recommend(args.host, refresh=args.refresh, all_models=args.all_models)
520
526
  if args.command == "serve":
521
- app.serve(args.port)
527
+ _load("app").serve(args.port)
522
528
  return 0
523
529
  if args.command == "tui":
524
530
  from localmodels import tui
@@ -529,7 +535,20 @@ def _run(args: argparse.Namespace) -> int:
529
535
  return _plan_or_deploy(args)
530
536
 
531
537
 
538
+ def _run(args: argparse.Namespace) -> int:
539
+ if args.command == "stack":
540
+ return _stack(args)
541
+ if args.command == "commands":
542
+ return _commands(args, list(args.path))
543
+ if args.command == "completion":
544
+ return _completion(args)
545
+ if (mod_name := _MODULE_COMMANDS.get(args.command)) is not None:
546
+ return int(_load(mod_name).cli(args))
547
+ return _run_inline(args)
548
+
549
+
532
550
  def _service(args: argparse.Namespace) -> int:
551
+ _load_many("app", "stack_lifecycle")
533
552
  dev_id = _device(args.host)[0]
534
553
  if args.action != "remove":
535
554
  if args.purge or args.yes:
@@ -545,6 +564,17 @@ def _service(args: argparse.Namespace) -> int:
545
564
 
546
565
 
547
566
  def _plan_or_deploy(args: argparse.Namespace) -> int:
567
+ _load_many(
568
+ "load_catalog_file",
569
+ "hf_repo",
570
+ "deploy",
571
+ "app",
572
+ "catalog_license",
573
+ "hosts",
574
+ "approval",
575
+ "gib",
576
+ "command",
577
+ )
548
578
  entries = load_catalog_file()
549
579
  if (
550
580
  not any(args.model_id in (entry.id, entry.variants[-1].model_id) for entry in entries)
@@ -587,6 +617,7 @@ def _plan_or_deploy(args: argparse.Namespace) -> int:
587
617
 
588
618
  def _approve_command(args: argparse.Namespace, plan_id: str) -> str:
589
619
  """The deploy command that executes plan ``plan_id``, with the options it was planned with."""
620
+ _load_many("deploy", "command")
590
621
  flags = [
591
622
  f"--{name.replace('_', '-')} {value}"
592
623
  for name, default in (
@@ -604,6 +635,7 @@ def _approve_command(args: argparse.Namespace, plan_id: str) -> str:
604
635
 
605
636
  def _deploy_approved(args: argparse.Namespace, dev_id: str, options: deploy.PlanOptions) -> int:
606
637
  """Execute the saved plan ``--approve`` names, after the gate in approval.py."""
638
+ _load_many("approval", "app", "command")
607
639
  try:
608
640
  plan, saved = approval.load_deployment(dev_id, args.approve)
609
641
  except KeyError:
@@ -627,6 +659,7 @@ def _deploy_approved(args: argparse.Namespace, dev_id: str, options: deploy.Plan
627
659
 
628
660
 
629
661
  def _execute(dev_id: str, plan: Plan) -> int:
662
+ _load("app")
630
663
  board = _deploy_board(plan)
631
664
  with board:
632
665
  record = app.run_deploy(dev_id, plan, on_event=_deploy_events(board))
@@ -653,6 +686,78 @@ def owner_only_writes() -> None:
653
686
  os.umask(os.umask(0o022) | 0o022)
654
687
 
655
688
 
689
+ def _peek_cli(effective: Sequence[str]) -> tuple[str | None, str | None, bool]:
690
+ """Inspect top-level tokens before argparse so lightweight commands skip unrelated imports.
691
+
692
+ Returns ``(command_or_sentinel, subcommand, is_version_flag)``.
693
+ """
694
+ idx = 0
695
+ saw_help = False
696
+ while idx < len(effective):
697
+ tok = effective[idx]
698
+ if tok in ("-h", "--help"):
699
+ saw_help = True
700
+ idx += 1
701
+ continue
702
+ if tok == "--version":
703
+ if not saw_help:
704
+ return None, None, True
705
+ idx += 1
706
+ continue
707
+ if tok == "--region":
708
+ idx += 2
709
+ continue
710
+ if tok.startswith("--region="):
711
+ idx += 1
712
+ continue
713
+ if tok.startswith("-"):
714
+ return "__help__", None, False
715
+ if saw_help:
716
+ return "__help__", None, False
717
+ subcmd = effective[idx + 1] if idx + 1 < len(effective) else None
718
+ if subcmd is not None and subcmd.startswith("-"):
719
+ subcmd = None
720
+ return tok, subcmd, False
721
+ return "__help__", None, False
722
+
723
+
724
+ def _needs_debug_activate() -> bool:
725
+ """Fast stat/env pre-check so normal runs skip importing ``debug_mode`` and its deps."""
726
+ if "localmodels.debug_mode" in sys.modules or "debug_mode" in globals():
727
+ return True
728
+ if os.environ.get("LOCALMODELS_DEBUG", "").strip():
729
+ return True
730
+ state_root = os.path.expanduser(
731
+ os.environ.get("LOCALMODELS_STATE", "~/.local/state/localmodels")
732
+ )
733
+ if os.path.isfile(os.path.join(state_root, "debug.json")):
734
+ return True
735
+ if (
736
+ "PYTEST_CURRENT_TEST" not in os.environ
737
+ or os.environ.get("LOCALMODELS_DEBUG_USER_CONFIG") == "1"
738
+ ):
739
+ if sys.platform == "win32" and (appdata := os.environ.get("APPDATA", "").strip()):
740
+ user_cfg = os.path.join(appdata, "localmodels", "debug.json")
741
+ else:
742
+ xdg = os.environ.get("XDG_CONFIG_HOME", "").strip()
743
+ base = (
744
+ os.path.expanduser(xdg) if xdg else os.path.join(os.path.expanduser("~"), ".config")
745
+ )
746
+ user_cfg = os.path.join(base, "localmodels", "debug.json")
747
+ if os.path.isfile(user_cfg):
748
+ return True
749
+ return False
750
+
751
+
752
+ def _loaded_exc(module_name: str, attr: str) -> tuple[type[BaseException], ...]:
753
+ """Return ``(cls,)`` only when ``module_name`` is already imported (cannot raise otherwise)."""
754
+ mod = sys.modules.get(module_name)
755
+ if mod is None:
756
+ return ()
757
+ cls = getattr(mod, attr, None)
758
+ return (cls,) if isinstance(cls, type) and issubclass(cls, BaseException) else ()
759
+
760
+
656
761
  def main(argv: list[str] | None = None) -> int:
657
762
  owner_only_writes()
658
763
  if sys.platform == "win32" and "PYTHONIOENCODING" not in os.environ:
@@ -671,15 +776,28 @@ def main(argv: list[str] | None = None) -> int:
671
776
 
672
777
  if stack_view_tick.is_fast_live_tick(effective):
673
778
  return stack_view_tick.cli(effective)
674
- _load_cli_deps()
675
- args = argument_parser().parse_args(argv)
779
+ cmd, subcmd, is_version = _peek_cli(effective)
780
+ if is_version:
781
+ from localmodels import __version__ as pkg_version
782
+
783
+ print(f"localmodels {pkg_version}")
784
+ raise SystemExit(0)
785
+ if "argument_parser" in globals():
786
+ parser = globals()["argument_parser"]()
787
+ else:
788
+ from localmodels import cli_parser
789
+
790
+ only = cmd if (cmd == "__help__" or cmd in cli_parser.COMMAND_HELPS) else "__help__"
791
+ parser = cli_parser.argument_parser(only=only, subcommand=subcmd)
792
+ args = parser.parse_args(argv)
676
793
  if args.region: # resolved lazily by the first download (region.py)
677
794
  os.environ["SIMPLEX_REGION"] = args.region
678
- if args.command != "debug" and (args.command, getattr(args, "stack_command", None)) != (
679
- "stack",
680
- "mcp",
795
+ if (
796
+ args.command != "debug"
797
+ and (args.command, getattr(args, "stack_command", None)) != ("stack", "mcp")
798
+ and _needs_debug_activate()
681
799
  ):
682
- debug_mode.activate()
800
+ _load("debug_mode").activate()
683
801
  try:
684
802
  code = _reported(args)
685
803
  sys.stdout.flush() # a closed pipe surfaces here for buffered output, not at exit
@@ -716,9 +834,9 @@ def _reported(args: argparse.Namespace) -> int:
716
834
  return _fail(str(exc), hint=_host_hint(getattr(args, "host", "")))
717
835
  print(f"error: {given} file not found: {exc.filename}", file=sys.stderr)
718
836
  return 2
719
- except app.ProbeError as exc:
837
+ except _loaded_exc("localmodels.app", "ProbeError") as exc:
720
838
  return _fail(f"probe failed: {exc}", hint=_host_hint(getattr(args, "host", "")))
721
- except plan_envelope.PlanError as exc:
839
+ except _loaded_exc("localmodels.plan_envelope", "PlanError") as exc:
722
840
  hint = ""
723
841
  if "catalog has no model" in str(exc):
724
842
  hint = _model_hint(getattr(args, "model_id", ""))
@@ -727,7 +845,7 @@ def _reported(args: argparse.Namespace) -> int:
727
845
  return _fail(str(exc), hint=hint)
728
846
  except KeyError as exc:
729
847
  missing = str(exc.args[0]) if exc.args else str(exc)
730
- known = {d["id"] for d in hosts.devices()}
848
+ known = {d["id"] for d in _load("hosts").devices()}
731
849
  host = getattr(args, "host", "")
732
850
  hint = (
733
851
  _service_hint(host)
@@ -9,6 +9,7 @@ entitlements and reports ``basis: "none"``.
9
9
  from __future__ import annotations
10
10
 
11
11
  import ctypes
12
+ import math
12
13
  import re
13
14
  import struct
14
15
  import subprocess
@@ -122,9 +123,27 @@ def parse_swap_used_bytes(text: str) -> int | None:
122
123
 
123
124
  _CREATOR_RE = re.compile(r'"IOUserClientCreator"\s*=\s*"pid\s+(\d+),\s*([^"]+)"')
124
125
  _ALLOC_RE = re.compile(r'"(?:In use system memory|Alloc system memory|phys_footprint)"\s*=\s*(\d+)')
126
+ _PERF_STATS_BLOCK_RE = re.compile(r'"PerformanceStatistics"\s*=\s*\{([^}]*)\}')
127
+ _DEVICE_UTIL_RE = re.compile(r'"Device Utilization %"\s*=\s*(\d+(?:\.\d+)?)')
125
128
  _NODE_HEADER_MARKER = "+-o "
126
129
 
127
130
 
131
+ def parse_agx_device_utilization(text: str) -> float | None:
132
+ """Parse ``PerformanceStatistics["Device Utilization %"]`` from ``ioreg -r -c AGXAccelerator``."""
133
+ blocks = _PERF_STATS_BLOCK_RE.findall(text)
134
+ haystacks = blocks if blocks else [text]
135
+ found: list[float] = []
136
+ for chunk in haystacks:
137
+ for raw in _DEVICE_UTIL_RE.findall(chunk):
138
+ try:
139
+ val = float(raw)
140
+ except ValueError:
141
+ continue
142
+ if math.isfinite(val) and 0.0 <= val <= 100.0:
143
+ found.append(val)
144
+ return round(max(found), 1) if found else None
145
+
146
+
128
147
  def _ioreg_indent(line: str) -> int:
129
148
  idx = 0
130
149
  while idx < len(line) and line[idx] in " |":
@@ -418,6 +437,10 @@ def read_telemetry(*, exclude_pids: set[int] | None = None) -> AppleTelemetry:
418
437
  matches = [int(m) for m in re.findall(r'"In use system memory"\s*=\s*(\d+)', agx_text)]
419
438
  in_use = max(matches) if matches else None
420
439
  holders = parse_ioaccelerator_holders(agx_text, exclude_pids=exclude_pids)
440
+ if gpu_util["basis"] != "live":
441
+ agx_util = parse_agx_device_utilization(agx_text)
442
+ if agx_util is not None:
443
+ gpu_util = _live(agx_util, "IOAccelerator AGXAccelerator Device Utilization %")
421
444
  return {
422
445
  "gpu_util_pct": gpu_util,
423
446
  "power_w": power_w,
@@ -36,6 +36,13 @@ VOLATILE = frozenset(
36
36
  # What a deployment plan does on the host; timestamps and warning text may differ on a rebuild.
37
37
  DEPLOYMENT_SECTIONS = ("model", "files", "engine", "placement", "launch", "service", "endpoint")
38
38
  STACK_SECTIONS = (*stack_events.STACK_PLAN_SECTIONS, "update")
39
+ # Probe paths plan.endpoint states since 0.1.0.dev105. Each follows from sections that stay bound
40
+ # (the engine, its argv and env, the recipe's health path), and plans saved before then lack them:
41
+ # a deployment's id and its comparison leave them out, so upgrading keeps every approval valid,
42
+ # replaces nothing and re-plans an unchanged service as the same one.
43
+ DERIVED_ENDPOINT_KEYS = frozenset(
44
+ {"health_path", "slots_path", "metrics_path", "metrics_requires_auth"}
45
+ )
39
46
  # Stack budget figures an earlier, partial run of the same plan shrinks: by placing its files,
40
47
  # and by starting parts whose memory is then running rather than still to be allocated.
41
48
  PROGRESS = ("download_bytes", "disk_needed_bytes", "ram_needed_bytes")
@@ -87,9 +94,23 @@ def digest(doc: Mapping[str, object]) -> str:
87
94
  ).hexdigest()
88
95
 
89
96
 
97
+ def bound_endpoint(endpoint: object) -> object:
98
+ """``endpoint`` without ``DERIVED_ENDPOINT_KEYS``: what a deployment's id binds of it."""
99
+ if not isinstance(endpoint, Mapping):
100
+ return endpoint
101
+ return {k: v for k, v in endpoint.items() if k not in DERIVED_ENDPOINT_KEYS}
102
+
103
+
104
+ def _bound_deployment(plan: Mapping[str, object]) -> dict[str, object]:
105
+ doc = dict(plan)
106
+ if "endpoint" in doc:
107
+ doc["endpoint"] = bound_endpoint(doc["endpoint"])
108
+ return doc
109
+
110
+
90
111
  def deployment_id(plan: Plan) -> str:
91
112
  """A deployment plan's id: its device, name and every section it binds."""
92
- doc = dict(plan)
113
+ doc = _bound_deployment(plan)
93
114
  return digest({k: doc.get(k) for k in ("host", "name", *DEPLOYMENT_SECTIONS)})
94
115
 
95
116
 
@@ -99,7 +120,7 @@ def _differs(approved: Mapping[str, object], fresh: Mapping[str, object], key: s
99
120
 
100
121
  def deployment_changes(approved: Plan, fresh: Plan) -> list[str]:
101
122
  """The sections of an approved deployment plan that a plan built now differs in."""
102
- old, new = dict(approved), dict(fresh)
123
+ old, new = _bound_deployment(approved), _bound_deployment(fresh)
103
124
  return [k for k in DEPLOYMENT_SECTIONS if _differs(old, new, k)]
104
125
 
105
126
 
@@ -158,6 +179,8 @@ def stack_changes(saved: Mapping[str, object], fresh: Mapping[str, object]) -> l
158
179
  parts += _parts({"aux": list(deferred.values())})
159
180
  for part in parts:
160
181
  part.pop("warnings", None)
182
+ if "endpoint" in part:
183
+ part["endpoint"] = bound_endpoint(part["endpoint"])
161
184
  kept = {
162
185
  k: v
163
186
  for k, v in figures(stable).items()