@simplexai/localmodels-linux-x64 0.1.0-dev.32.build.git0f60eee490864cf83e343f8db13a335676a19dd8 → 0.1.0-dev.35

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 (140) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +138 -97
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +4 -0
  5. package/modules/localmodels/app.py +7 -2
  6. package/modules/localmodels/approval.py +4 -4
  7. package/modules/localmodels/bifrost_checks.py +121 -3
  8. package/modules/localmodels/bifrost_provider.py +53 -0
  9. package/modules/localmodels/bifrost_unit.py +32 -1
  10. package/modules/localmodels/budget.py +5 -1
  11. package/modules/localmodels/catalog.json +51 -10
  12. package/modules/localmodels/catalog.py +30 -29
  13. package/modules/localmodels/catalog_add.py +1 -0
  14. package/modules/localmodels/cli_parser.py +10 -2
  15. package/modules/localmodels/component.py +7 -1
  16. package/modules/localmodels/decode_calibration.json +6 -0
  17. package/modules/localmodels/decode_calibration.py +104 -0
  18. package/modules/localmodels/deploy.py +44 -7
  19. package/modules/localmodels/deploy_steps.py +10 -1
  20. package/modules/localmodels/engines-strata-0.1.49.2.json +31 -0
  21. package/modules/localmodels/engines.json +57 -1
  22. package/modules/localmodels/engines.py +6 -2
  23. package/modules/localmodels/estimator.py +21 -7
  24. package/modules/localmodels/frontend.py +4 -4
  25. package/modules/localmodels/gateway.py +14 -4
  26. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  27. package/modules/localmodels/gateway_bifrost.py +70 -57
  28. package/modules/localmodels/gateway_probe.py +3 -4
  29. package/modules/localmodels/gguf.py +7 -0
  30. package/modules/localmodels/harness.py +24 -25
  31. package/modules/localmodels/harness_gateway.py +19 -10
  32. package/modules/localmodels/harness_probe.py +33 -6
  33. package/modules/localmodels/hosts.py +73 -9
  34. package/modules/localmodels/install.py +36 -6
  35. package/modules/localmodels/library_cli.py +179 -0
  36. package/modules/localmodels/library_convert.py +132 -0
  37. package/modules/localmodels/library_gateway.py +471 -0
  38. package/modules/localmodels/library_jobs.py +314 -0
  39. package/modules/localmodels/library_model.py +246 -0
  40. package/modules/localmodels/library_pricing.py +347 -0
  41. package/modules/localmodels/library_serve.py +348 -0
  42. package/modules/localmodels/library_state.py +373 -0
  43. package/modules/localmodels/library_status.py +349 -0
  44. package/modules/localmodels/llm_rank.py +16 -2
  45. package/modules/localmodels/memcalc.py +7 -30
  46. package/modules/localmodels/metal.py +26 -0
  47. package/modules/localmodels/plan_envelope.py +4 -1
  48. package/modules/localmodels/preparation.py +49 -0
  49. package/modules/localmodels/probe.py +8 -8
  50. package/modules/localmodels/process_identity.py +536 -9
  51. package/modules/localmodels/quant_formats.py +123 -0
  52. package/modules/localmodels/recommend_cli.py +8 -4
  53. package/modules/localmodels/records.py +1 -0
  54. package/modules/localmodels/remote_ops.py +104 -6
  55. package/modules/localmodels/remote_ops_download.py +17 -2
  56. package/modules/localmodels/remote_ops_prepare.py +406 -0
  57. package/modules/localmodels/remote_ops_remove.py +40 -7
  58. package/modules/localmodels/remote_ops_service.py +110 -8
  59. package/modules/localmodels/remote_ops_verify.py +15 -2
  60. package/modules/localmodels/runtime_auth.py +31 -1
  61. package/modules/localmodels/runtime_cli.py +3 -4
  62. package/modules/localmodels/runtime_io.py +50 -6
  63. package/modules/localmodels/service_autostart.py +45 -1
  64. package/modules/localmodels/service_control.py +13 -0
  65. package/modules/localmodels/service_deployment.py +12 -3
  66. package/modules/localmodels/service_jobs.py +33 -4
  67. package/modules/localmodels/service_probe.py +67 -13
  68. package/modules/localmodels/service_stop.py +152 -0
  69. package/modules/localmodels/service_worker.py +9 -1
  70. package/modules/localmodels/services_cli.py +50 -6
  71. package/modules/localmodels/setup_inspection.py +34 -25
  72. package/modules/localmodels/setup_text.py +118 -0
  73. package/modules/localmodels/sizecalc.py +625 -0
  74. package/modules/localmodels/sizecalc_cli.py +249 -0
  75. package/modules/localmodels/stack.py +69 -17
  76. package/modules/localmodels/stack_args.py +91 -19
  77. package/modules/localmodels/stack_auto.py +78 -0
  78. package/modules/localmodels/stack_binding.py +23 -35
  79. package/modules/localmodels/stack_card.py +195 -0
  80. package/modules/localmodels/stack_cleanup.py +379 -0
  81. package/modules/localmodels/stack_clients.py +4 -1
  82. package/modules/localmodels/stack_compose.py +150 -194
  83. package/modules/localmodels/stack_console.py +2 -0
  84. package/modules/localmodels/stack_decision.py +3 -2
  85. package/modules/localmodels/stack_down.py +189 -0
  86. package/modules/localmodels/stack_events.py +54 -0
  87. package/modules/localmodels/stack_hardware.py +22 -23
  88. package/modules/localmodels/stack_journal.py +29 -8
  89. package/modules/localmodels/stack_ledger.py +411 -0
  90. package/modules/localmodels/stack_lifecycle.py +162 -167
  91. package/modules/localmodels/stack_llm_ram.py +57 -5
  92. package/modules/localmodels/stack_memory.py +721 -0
  93. package/modules/localmodels/stack_picks.py +139 -0
  94. package/modules/localmodels/stack_plan.py +140 -22
  95. package/modules/localmodels/stack_ports.py +22 -0
  96. package/modules/localmodels/stack_preflight.py +699 -0
  97. package/modules/localmodels/stack_review.py +123 -5
  98. package/modules/localmodels/stack_rollback.py +2 -0
  99. package/modules/localmodels/stack_route.py +256 -0
  100. package/modules/localmodels/stack_run.py +11 -0
  101. package/modules/localmodels/stack_suite.py +102 -17
  102. package/modules/localmodels/stack_summary.py +65 -4
  103. package/modules/localmodels/stack_try.py +354 -0
  104. package/modules/localmodels/stack_try_client.py +194 -0
  105. package/modules/localmodels/stack_try_docs.py +139 -0
  106. package/modules/localmodels/stack_up.py +8 -1
  107. package/modules/localmodels/stack_update.py +29 -4
  108. package/modules/localmodels/stack_verify.py +3 -1
  109. package/modules/localmodels/stack_view.py +10 -11
  110. package/modules/localmodels/stack_view_apply.py +4 -2
  111. package/modules/localmodels/stack_view_events.py +2 -1
  112. package/modules/localmodels/stack_view_serve.py +3 -0
  113. package/modules/localmodels/stack_view_text.py +1 -1
  114. package/modules/localmodels/stack_view_words.py +4 -1
  115. package/modules/localmodels/stack_warm.py +574 -0
  116. package/modules/localmodels/stack_whatif.py +558 -0
  117. package/modules/localmodels/suite.py +48 -39
  118. package/modules/localmodels/tool_archive.py +40 -0
  119. package/modules/localmodels/tools.json +8 -0
  120. package/modules/localmodels/transport.py +1 -0
  121. package/modules/localmodels/vision.py +8 -1
  122. package/modules/localmodels/web/sizecalc/app.js +431 -0
  123. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  124. package/modules/localmodels/web/sizecalc/page.html +362 -0
  125. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  126. package/modules/localmodels/web/view/i18n.js +1 -1
  127. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  128. package/modules/localmodels/web/view/logo-codex.png +0 -0
  129. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  130. package/modules/localmodels/web/view/view.css +4 -0
  131. package/modules/localmodels/web/view/view.js +15 -6
  132. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/METADATA +1 -1
  133. package/modules/simplex_localmodels-0.1.0.dev35.dist-info/RECORD +241 -0
  134. package/package.json +1 -1
  135. package/tool.json +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  137. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/WHEEL +0 -0
  138. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/entry_points.txt +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/NOTICE +0 -0
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev35.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -11,14 +11,16 @@ import json
11
11
  import os
12
12
  import re
13
13
  import threading
14
+ import time
14
15
  from collections.abc import Callable, Iterator
15
16
  from contextlib import contextmanager
16
17
  from pathlib import Path
17
- from typing import Literal, TypedDict, TypeVar
18
+ from typing import Any, Literal, TypedDict, TypeVar
18
19
 
19
20
  from localmodels.contracts import decode
20
21
  from localmodels.probe import HostFacts
21
22
  from localmodels.records import Device, FinishedRecord, Plan
23
+ from localmodels.remote_ops import StrataPreparation
22
24
  from localmodels.transport import Executor
23
25
 
24
26
  LOCAL_ID = "local"
@@ -88,16 +90,44 @@ class LockedError(RuntimeError):
88
90
  """Another process holds the lock."""
89
91
 
90
92
 
93
+ def _lock_file(lock: Any, blocking: bool) -> None:
94
+ """An exclusive advisory lock on an open file, held until it is closed: flock on POSIX,
95
+ a one-byte msvcrt lock on Windows. BlockingIOError when ``blocking`` is False and another
96
+ process holds it."""
97
+ if os.name == "nt":
98
+ import msvcrt
99
+
100
+ lock.seek(0)
101
+ while True:
102
+ try:
103
+ msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
104
+ return
105
+ except OSError as exc:
106
+ if not blocking:
107
+ raise BlockingIOError(str(exc)) from exc
108
+ time.sleep(0.2)
109
+ import fcntl
110
+
111
+ fcntl.flock(lock, fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB))
112
+
113
+
114
+ @contextmanager
115
+ def file_lock(path: Path) -> Iterator[None]:
116
+ """Hold an exclusive lock on ``path`` (created if missing), waiting for another holder."""
117
+ path.parent.mkdir(parents=True, exist_ok=True)
118
+ with path.open("a+") as lock:
119
+ _lock_file(lock, blocking=True)
120
+ yield
121
+
122
+
91
123
  @contextmanager
92
124
  def stack_apply_lock() -> Iterator[None]:
93
125
  """Hold the one ``stack apply`` lock; LockedError when another apply holds it."""
94
- import fcntl
95
-
96
126
  path = stacks_dir() / ".apply.lock"
97
127
  path.parent.mkdir(parents=True, exist_ok=True)
98
- with path.open("a") as lock:
128
+ with path.open("a+") as lock:
99
129
  try:
100
- fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
130
+ _lock_file(lock, blocking=False)
101
131
  except BlockingIOError as exc:
102
132
  raise LockedError(str(path)) from exc
103
133
  yield
@@ -270,7 +300,11 @@ def delete_record(dev_id: str, name: str, *, purged: bool = False) -> None:
270
300
  OWNED_SCHEMA = "localmodels.owned/v1"
271
301
 
272
302
 
273
- class OwnedDeployment(TypedDict):
303
+ class _OwnedPreparation(TypedDict, total=False):
304
+ preparation_dir: str
305
+
306
+
307
+ class OwnedDeployment(_OwnedPreparation):
274
308
  service: str # the systemd --user unit or nohup service name
275
309
  kind: str # systemd-user | nohup
276
310
  deploy_dir: str
@@ -348,7 +382,7 @@ class Owned(_OwnedClients):
348
382
 
349
383
  schema: str
350
384
  tools: list[OwnedTool]
351
- archives: list[str] # downloads and decision-front venvs; only --purge deletes them
385
+ archives: list[str] # downloads and decision-front venvs; stack remove deletes them
352
386
  deployments: dict[str, OwnedDeployment] # by deployment (record) name
353
387
  slices: list[str]
354
388
  gateway: OwnedGateway
@@ -411,6 +445,8 @@ def update_owned(change: Callable[[Owned], None], tools_dir: str | Path = TOOLS_
411
445
  flock is released splits the lock domain: a writer that already opened the old inode and
412
446
  a writer that recreates the pathname would both hold an "exclusive" lock and one archive
413
447
  entry would be lost (WHI-317). Nothing removes the tools directory itself."""
448
+ if os.name == "nt":
449
+ return _update_owned_windows(change, tools_dir)
414
450
  import fcntl
415
451
 
416
452
  path = owned_path(tools_dir)
@@ -428,6 +464,26 @@ def update_owned(change: Callable[[Owned], None], tools_dir: str | Path = TOOLS_
428
464
  return doc
429
465
 
430
466
 
467
+ def _update_owned_windows(change: Callable[[Owned], None], tools_dir: str | Path) -> Owned:
468
+ """``update_owned`` with Windows' one-byte msvcrt lock in place of flock. (Kept textually
469
+ apart from it: scripts/owned_manifest_check.py mutates update_owned's exact lines.)"""
470
+ manifest = owned_path(tools_dir)
471
+ manifest.parent.mkdir(parents=True, exist_ok=True)
472
+ with manifest.with_suffix(".lock").open("a+") as held:
473
+ _lock_file(held, blocking=True)
474
+ document = load_owned(tools_dir)
475
+ change(document)
476
+ if owns_nothing(document):
477
+ manifest.unlink(missing_ok=True)
478
+ return document
479
+ staged = manifest.with_suffix(".tmp")
480
+ staged.write_text(
481
+ json.dumps(document, ensure_ascii=False, indent=1) + "\n", encoding="utf-8"
482
+ )
483
+ os.replace(staged, manifest)
484
+ return document
485
+
486
+
431
487
  def own_gateway(
432
488
  tools_dir: str | Path,
433
489
  field: Literal["started", "group", "rule"],
@@ -476,8 +532,8 @@ def own_listed(
476
532
  update_owned(change, tools_dir)
477
533
 
478
534
 
479
- def own_deployment(plan: Plan, tools_dir: str | Path = TOOLS_DIR) -> None:
480
- """Record a deployment on this computer: its unit, slice, directory and model files."""
535
+ def owned_entry(plan: Plan) -> OwnedDeployment:
536
+ """What the manifest keeps of a deployment: its unit, slice, directory and model files."""
481
537
  svc = plan["service"]
482
538
  entry: OwnedDeployment = {
483
539
  "service": svc["name"],
@@ -491,6 +547,14 @@ def own_deployment(plan: Plan, tools_dir: str | Path = TOOLS_DIR) -> None:
491
547
  "files": [os.path.expanduser(f["dest"]) for f in plan["files"]],
492
548
  "removed": False,
493
549
  }
550
+ if raw := plan["launch"].get("preparation"):
551
+ entry["preparation_dir"] = os.path.expanduser(decode(raw, StrataPreparation)["model_dir"])
552
+ return entry
553
+
554
+
555
+ def own_deployment(plan: Plan, tools_dir: str | Path = TOOLS_DIR) -> None:
556
+ """Record a deployment on this computer (``owned_entry``)."""
557
+ entry = owned_entry(plan)
494
558
 
495
559
  def add(doc: Owned) -> None:
496
560
  doc["deployments"][plan["name"]] = entry
@@ -18,7 +18,7 @@ from __future__ import annotations
18
18
  import argparse
19
19
  import sys
20
20
 
21
- from localmodels import console, harness, stack, stack_args, stack_up, stack_update
21
+ from localmodels import console, harness, stack, stack_args, stack_picks, stack_up, stack_update
22
22
  from localmodels.plan_envelope import PlanError
23
23
  from localmodels.stack_console import Board
24
24
  from localmodels.stack_plan import StackError, command
@@ -62,7 +62,30 @@ def cli(args: argparse.Namespace) -> int:
62
62
  print(f"install: {exc}", file=sys.stderr)
63
63
  return 2
64
64
  print(styled(stack.summary(plan, path, apply_line=False)))
65
- if not (args.yes or _confirm()):
65
+ seen = plan.get("hardware")
66
+ offered = seen.get("picks", []) if seen else []
67
+ other = (
68
+ None
69
+ if plan.get("llm_fast")
70
+ else stack_picks.second(offered, str(plan["llm"]["model"]["id"]))
71
+ )
72
+ answer = "y" if args.yes else _confirm(other)
73
+ if other is not None and answer == OTHER:
74
+ # The second choice gets its own plan, shown in full: approval binds to what was shown.
75
+ options = options.copy()
76
+ options.pop("prefer", None) # absent means smartest, so plan ids stay the same
77
+ if other["role"] != "smartest":
78
+ options["prefer"] = other["role"]
79
+ try:
80
+ with console.status(f"Pricing the {other['role']} stack…"):
81
+ plan = stack.build(options)
82
+ path = stack.save(plan)
83
+ except _REFUSED as exc:
84
+ print(f"install: {exc}", file=sys.stderr)
85
+ return 2
86
+ print(styled(stack.summary(plan, path, apply_line=False)))
87
+ answer = _confirm(None)
88
+ if answer != "y":
66
89
  print(
67
90
  f"Not applied. Plan saved to {path}; run after approval: "
68
91
  f"{command()} stack apply {path} --approve {plan['plan_id']}"
@@ -78,15 +101,22 @@ def cli(args: argparse.Namespace) -> int:
78
101
  return stack.report(record, timing=board.timing())
79
102
 
80
103
 
81
- def _confirm() -> bool:
104
+ OTHER = "2" # the answer that asks for the second choice's plan
105
+
106
+
107
+ def _confirm(other: stack_picks.Pick | None) -> str:
108
+ """The operator's answer: "y", OTHER when a second choice is offered and asked for, else "n"."""
109
+ choice = f"/{OTHER}: see the {other['role']} plan instead" if other else ""
82
110
  try:
83
- answer = input("Apply this plan? [y/N] ").strip().lower()
111
+ answer = input(f"Apply this plan? [y/N{choice}] ").strip().lower()
84
112
  except (EOFError, KeyboardInterrupt):
85
113
  print()
86
- return False
114
+ return "n"
87
115
  if not sys.stdin.isatty(): # a piped answer is not echoed, so end the prompt's line
88
116
  print(answer)
89
- return answer in ("y", "yes")
117
+ if other and answer in (OTHER, other["role"]):
118
+ return OTHER
119
+ return "y" if answer in ("y", "yes") else "n"
90
120
 
91
121
 
92
122
  def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
@@ -0,0 +1,179 @@
1
+ """``localmodels library``: the per-model surface the Linger daemon drives (contract v2).
2
+
3
+ ``status`` prints one ``localmodels.library-status/v1`` object. ``download`` and ``load`` print
4
+ ``localmodels.library-event/v1`` progress lines and then one result or error line; ``unload``,
5
+ ``remove`` and ``cancel`` print one result or error object. Exit codes: 0 ok, 1 failed,
6
+ 2 refused (validation or a precondition), 130 cancelled.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ from localmodels import cli_help, deploy, library_jobs, library_serve, library_status
17
+ from localmodels.contracts import decode
18
+ from localmodels.library_model import (
19
+ EXIT_FAILED,
20
+ LibraryError,
21
+ emit_final,
22
+ error_doc,
23
+ result_doc,
24
+ )
25
+ from localmodels.probe import HostFacts
26
+
27
+ DESCRIPTION = (
28
+ "Each validated chat model on its own: download it (then load it when its memory pool has "
29
+ "room), load and unload it beside others, and remove its weights. A loaded model is "
30
+ "registered with this tool's Bifrost gateway and pi's models.json. Every command prints "
31
+ "JSON; downloads and loads print progress lines first. Model ids are CATALOG_ID:QUANT as "
32
+ "status lists them. Exit status: 0 ok, 1 failed, 2 refused, 130 cancelled."
33
+ )
34
+ # What an unexpected failure of each command reports; the contract's set of codes is closed.
35
+ FALLBACK = {
36
+ "download": "DOWNLOAD_FAILED",
37
+ "load": "ENGINE_START_FAILED",
38
+ "unload": "ENGINE_START_FAILED",
39
+ "remove": "INVALID_STATE",
40
+ "cancel": "INVALID_STATE",
41
+ }
42
+
43
+
44
+ def _base(p: argparse.ArgumentParser) -> None:
45
+ p.add_argument(
46
+ "--base-dir",
47
+ default=deploy.DEFAULT_BASE_DIR,
48
+ metavar="DIR",
49
+ help="where weights, engines and deployments live (the v1 calls' --base-dir)",
50
+ )
51
+
52
+
53
+ def _model(p: argparse.ArgumentParser) -> None:
54
+ p.add_argument("model", metavar="MODEL", help="a library model id, CATALOG_ID:QUANT")
55
+
56
+
57
+ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
58
+ parser = sub.add_parser("library", help="download, load, unload and remove single models")
59
+ verbs = parser.add_subparsers(dest="library_command", required=True, metavar="COMMAND")
60
+ status = verbs.add_parser("status", help="every model, its fit, state and pool (JSON)")
61
+ _base(status)
62
+ status.add_argument(
63
+ "--facts",
64
+ type=Path,
65
+ metavar="FILE",
66
+ help="price against saved host facts (probe JSON) instead of probing; read-only",
67
+ )
68
+ status.add_argument("--json", action="store_true", help="accepted; the output is JSON")
69
+ cli_help.document(
70
+ status,
71
+ "Print one localmodels.library-status/v1 object: the host, its memory pools and what "
72
+ "holds them, and every validated chat model with its fit, memory, state and endpoint. "
73
+ "Reads only, apart from adopting a Quick Install stack into the library once.",
74
+ examples=[("%(prog)s --base-dir /srv/models --json", "")],
75
+ )
76
+ download = verbs.add_parser("download", help="fetch a model, then load it if it fits now")
77
+ _model(download)
78
+ _base(download)
79
+ download.add_argument(
80
+ "--no-autoload", action="store_true", help="leave the model idle after the download"
81
+ )
82
+ download.add_argument("--jsonl", action="store_true", help="accepted; output is JSONL")
83
+ cli_help.document(
84
+ download,
85
+ "Download and verify the model's files into the pool it fits best, then load it when "
86
+ "that pool has room (else it stays idle with note NO_ROOM_TO_LOAD).",
87
+ examples=[("%(prog)s qwen3.8-27b-iq3s:UD-IQ3_S --jsonl", "")],
88
+ )
89
+ load = verbs.add_parser("load", help="start a downloaded model's server")
90
+ _model(load)
91
+ _base(load)
92
+ load.add_argument(
93
+ "--unload",
94
+ action="append",
95
+ default=[],
96
+ metavar="MODEL",
97
+ help="unload this model first (repeatable); refused before any unload without room",
98
+ )
99
+ load.add_argument("--jsonl", action="store_true", help="accepted; output is JSONL")
100
+ cli_help.document(
101
+ load,
102
+ "Start the model's server in its pool, measure its speed with two short requests and "
103
+ "register it with the gateway and pi.",
104
+ examples=[("%(prog)s qwen3.8-27b:UD-Q4_K_M --unload qwen3.8-27b-iq3s:UD-IQ3_S", "")],
105
+ )
106
+ for verb, text, note in (
107
+ ("unload", "stop a model's server; its weights stay", "unregister and stop the server"),
108
+ ("remove", "delete a model's weights (unloads it first)", "keeps files others use"),
109
+ ("cancel", "stop a running download and delete its files", "the download exits 130"),
110
+ ):
111
+ command = verbs.add_parser(verb, help=text)
112
+ _model(command)
113
+ _base(command)
114
+ command.add_argument("--json", action="store_true", help="accepted; the output is JSON")
115
+ cli_help.document(
116
+ command,
117
+ f"{text[0].upper()}{text[1:]}: {note}. Prints one result or error object.",
118
+ examples=[("%(prog)s qwen3.8-27b-iq3s:UD-IQ3_S --json", "")],
119
+ )
120
+ cli_help.document(
121
+ parser,
122
+ DESCRIPTION,
123
+ examples=[
124
+ ("%(prog)s status --json", "what fits and what is loaded"),
125
+ ("%(prog)s download qwen3.8-27b-iq3s:UD-IQ3_S --jsonl", ""),
126
+ ],
127
+ )
128
+
129
+
130
+ def _status(args: argparse.Namespace) -> int:
131
+ from localmodels import library_convert
132
+
133
+ try:
134
+ library_convert.convert_once()
135
+ if args.facts is not None:
136
+ facts = decode(json.loads(args.facts.read_text(encoding="utf-8")), HostFacts)
137
+ else:
138
+ facts = library_jobs.probe()
139
+ doc = library_status.build(library_status.Library.read(facts, args.base_dir))
140
+ except Exception as exc: # noqa: BLE001 - status has no error document: stderr, exit 1
141
+ print(f"error: library status failed: {exc}", file=sys.stderr)
142
+ return EXIT_FAILED
143
+ print(json.dumps(doc, ensure_ascii=False, indent=1))
144
+ return 0
145
+
146
+
147
+ def cli(args: argparse.Namespace) -> int:
148
+ verb = args.library_command
149
+ if verb == "status":
150
+ return _status(args)
151
+ jsonl = verb in ("download", "load")
152
+ try:
153
+ if verb == "download":
154
+ row = library_jobs.download(
155
+ args.model,
156
+ args.base_dir,
157
+ autoload=not args.no_autoload,
158
+ load=lambda m, b, u: library_serve.load(m, b, u),
159
+ )
160
+ elif verb == "load":
161
+ row = library_serve.load(args.model, args.base_dir, args.unload)
162
+ elif verb == "unload":
163
+ row = library_serve.unload(args.model, args.base_dir)
164
+ elif verb == "remove":
165
+ row = library_serve.remove(args.model, args.base_dir)
166
+ else:
167
+ row = library_jobs.cancel(args.model, args.base_dir)
168
+ except LibraryError as exc:
169
+ emit_final(error_doc(exc, args.model), jsonl=jsonl)
170
+ return exc.exit_code
171
+ except KeyboardInterrupt:
172
+ error = LibraryError("CANCELLED", f"the {verb} was interrupted")
173
+ emit_final(error_doc(error, args.model), jsonl=jsonl)
174
+ return error.exit_code
175
+ except Exception as exc: # noqa: BLE001 - every failure ends in one contract error line
176
+ emit_final(error_doc(LibraryError(FALLBACK[verb], str(exc)), args.model), jsonl=jsonl)
177
+ return EXIT_FAILED
178
+ emit_final(result_doc(row), jsonl=jsonl)
179
+ return 0
@@ -0,0 +1,132 @@
1
+ """Adopt a Quick Install stack's LLM into the library, once.
2
+
3
+ The first library command on a computer reads the stack ``stack apply`` last accepted: each
4
+ LLM it runs becomes a library model in state ``loaded`` with the stack's own gateway wiring
5
+ recorded as its registration. A marker then records the conversion, and the library reads
6
+ only its own records from then on; nothing reads the stack's state again for the library.
7
+ The stack's services, files and manifest entries are not touched by the conversion itself.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from localmodels import (
17
+ gateway_bifrost,
18
+ harness,
19
+ hosts,
20
+ library_gateway,
21
+ library_pricing,
22
+ library_state,
23
+ stack_up,
24
+ )
25
+ from localmodels.contracts import decode
26
+ from localmodels.library_model import library_id
27
+ from localmodels.library_state import Registration
28
+ from localmodels.plan_envelope import utc_now
29
+
30
+ MARKER = "converted.json"
31
+ STACK_LLMS = {"llm": harness.LLM_PROVIDER, "llm_fast": gateway_bifrost.FAST_PROVIDER}
32
+
33
+
34
+ def _record_files() -> list[Path]:
35
+ return sorted((library_state.root() / "models").glob("*.json"))
36
+
37
+
38
+ def _older(path: Path) -> dict[str, Any] | None:
39
+ """The record at ``path`` when an earlier schema saved it."""
40
+ try:
41
+ value = json.loads(path.read_text(encoding="utf-8"))
42
+ except (OSError, ValueError):
43
+ return None
44
+ if isinstance(value, dict) and value.get("schema") == library_state.RECORD_SCHEMA_V1:
45
+ return value
46
+ return None
47
+
48
+
49
+ def upgrade() -> list[str]:
50
+ """Rewrite each record an earlier version saved into the current schema, once: v1 records
51
+ gain ``pi_model`` (the selector the registration they hold names, else the one the gateway
52
+ would register) and an adopted LLM its ``stack_provider``. Nothing reads v1 afterwards."""
53
+ upgraded: list[str] = []
54
+ if not any(_older(p) is not None for p in _record_files()):
55
+ return upgraded # the usual case: no lock, nothing written
56
+ with library_state.locked():
57
+ for path in _record_files():
58
+ value = _older(path)
59
+ if value is None:
60
+ continue
61
+ registration = value.get("registration") or {}
62
+ converted = bool(value.get("converted"))
63
+ if converted and registration.get("provider") and not value.get("stack_provider"):
64
+ value["stack_provider"] = registration["provider"]
65
+ value["pi_model"] = registration.get("pi_model") or library_gateway.pi_model(
66
+ str(value["id"]),
67
+ str(value["plan"]["endpoint"]["model"]),
68
+ converted=converted,
69
+ )
70
+ value["schema"] = library_state.RECORD_SCHEMA
71
+ library_state.save(decode(value, library_state.Record))
72
+ upgraded.append(str(value["id"]))
73
+ return upgraded
74
+
75
+
76
+ def convert_once() -> list[str]:
77
+ """The library ids adopted now; empty when the conversion already ran. Every library
78
+ command calls it first, which also upgrades records an earlier version saved."""
79
+ upgrade()
80
+ marker = library_state.root() / MARKER
81
+ if marker.is_file():
82
+ return []
83
+ with library_state.locked():
84
+ if marker.is_file():
85
+ return []
86
+ adopted: list[str] = []
87
+ plan = stack_up.accepted()
88
+ from localmodels import stack_verify
89
+
90
+ for component, part in stack_verify.parts(plan) if plan is not None else []:
91
+ if component not in STACK_LLMS:
92
+ continue
93
+ try:
94
+ deployed = hosts.record(hosts.LOCAL_ID, part["name"])["plan"]
95
+ except KeyError:
96
+ continue
97
+ spec = deployed["model"]
98
+ model = library_id(spec["id"], spec["quant"])
99
+ if library_state.load(model) is not None:
100
+ continue
101
+ record = library_state.new_record(
102
+ model,
103
+ spec["id"],
104
+ spec["quant"],
105
+ library_pricing.pool_of(deployed),
106
+ deployed,
107
+ gateway_bifrost.PI_MODEL,
108
+ )
109
+ record["state"] = "loaded"
110
+ record["converted"] = True
111
+ record["stack_provider"] = STACK_LLMS[component]
112
+ record["memory_bytes"] = library_pricing.memory_bytes(deployed)
113
+ registration: Registration = {
114
+ "kind": "stack",
115
+ "provider": STACK_LLMS[component],
116
+ "model": gateway_bifrost.AGENT_MODEL,
117
+ "pi_provider": gateway_bifrost.PI_PROVIDER,
118
+ "pi_model": gateway_bifrost.PI_MODEL,
119
+ }
120
+ record["registration"] = registration
121
+ library_state.save(record)
122
+ adopted.append(model)
123
+ hosts.save_private(
124
+ marker,
125
+ {
126
+ "schema": "localmodels.library-conversion/v1",
127
+ "converted_at": utc_now(),
128
+ "plan_id": plan["plan_id"] if plan is not None else None,
129
+ "adopted": adopted,
130
+ },
131
+ )
132
+ return adopted