@simplexai/localmodels-linux-x64 0.1.0-dev.32.build.git9f03dd7a81cec1338df8eaf613ec9e3013365c9c → 0.1.0-dev.36

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 (143) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +141 -99
  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 +7 -1
  11. package/modules/localmodels/catalog.json +286 -12
  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-strata-0.1.59.1.json +31 -0
  22. package/modules/localmodels/engines.json +57 -1
  23. package/modules/localmodels/engines.py +6 -2
  24. package/modules/localmodels/estimator.py +21 -7
  25. package/modules/localmodels/frontend.py +4 -4
  26. package/modules/localmodels/gateway.py +14 -4
  27. package/modules/localmodels/gateway_app_bifrost.py +4 -3
  28. package/modules/localmodels/gateway_bifrost.py +70 -57
  29. package/modules/localmodels/gateway_probe.py +3 -4
  30. package/modules/localmodels/gguf.py +7 -0
  31. package/modules/localmodels/harness.py +24 -25
  32. package/modules/localmodels/harness_gateway.py +19 -10
  33. package/modules/localmodels/harness_probe.py +33 -6
  34. package/modules/localmodels/hosts.py +73 -9
  35. package/modules/localmodels/install.py +36 -6
  36. package/modules/localmodels/library_cli.py +179 -0
  37. package/modules/localmodels/library_convert.py +132 -0
  38. package/modules/localmodels/library_gateway.py +471 -0
  39. package/modules/localmodels/library_jobs.py +314 -0
  40. package/modules/localmodels/library_model.py +246 -0
  41. package/modules/localmodels/library_pricing.py +347 -0
  42. package/modules/localmodels/library_serve.py +348 -0
  43. package/modules/localmodels/library_state.py +373 -0
  44. package/modules/localmodels/library_status.py +349 -0
  45. package/modules/localmodels/llm_rank.py +77 -8
  46. package/modules/localmodels/memcalc.py +7 -30
  47. package/modules/localmodels/metal.py +26 -0
  48. package/modules/localmodels/metal_probe.py +11 -7
  49. package/modules/localmodels/plan_envelope.py +4 -1
  50. package/modules/localmodels/preparation.py +49 -0
  51. package/modules/localmodels/probe.py +8 -8
  52. package/modules/localmodels/process_identity.py +536 -9
  53. package/modules/localmodels/quant_formats.py +123 -0
  54. package/modules/localmodels/recommend.py +32 -3
  55. package/modules/localmodels/recommend_cli.py +8 -4
  56. package/modules/localmodels/records.py +1 -0
  57. package/modules/localmodels/remote_ops.py +104 -6
  58. package/modules/localmodels/remote_ops_download.py +17 -2
  59. package/modules/localmodels/remote_ops_prepare.py +425 -0
  60. package/modules/localmodels/remote_ops_remove.py +40 -7
  61. package/modules/localmodels/remote_ops_service.py +110 -8
  62. package/modules/localmodels/remote_ops_verify.py +15 -2
  63. package/modules/localmodels/runtime_auth.py +31 -1
  64. package/modules/localmodels/runtime_cli.py +3 -4
  65. package/modules/localmodels/runtime_io.py +50 -6
  66. package/modules/localmodels/service_autostart.py +45 -1
  67. package/modules/localmodels/service_control.py +13 -0
  68. package/modules/localmodels/service_deployment.py +12 -3
  69. package/modules/localmodels/service_jobs.py +33 -4
  70. package/modules/localmodels/service_probe.py +67 -13
  71. package/modules/localmodels/service_stop.py +152 -0
  72. package/modules/localmodels/service_worker.py +9 -1
  73. package/modules/localmodels/services_cli.py +50 -6
  74. package/modules/localmodels/setup_inspection.py +34 -25
  75. package/modules/localmodels/setup_text.py +118 -0
  76. package/modules/localmodels/sizecalc.py +625 -0
  77. package/modules/localmodels/sizecalc_cli.py +249 -0
  78. package/modules/localmodels/stack.py +69 -17
  79. package/modules/localmodels/stack_args.py +91 -19
  80. package/modules/localmodels/stack_auto.py +78 -0
  81. package/modules/localmodels/stack_binding.py +23 -35
  82. package/modules/localmodels/stack_card.py +195 -0
  83. package/modules/localmodels/stack_cleanup.py +379 -0
  84. package/modules/localmodels/stack_clients.py +4 -1
  85. package/modules/localmodels/stack_compose.py +173 -206
  86. package/modules/localmodels/stack_console.py +2 -0
  87. package/modules/localmodels/stack_decision.py +3 -2
  88. package/modules/localmodels/stack_down.py +189 -0
  89. package/modules/localmodels/stack_events.py +54 -0
  90. package/modules/localmodels/stack_hardware.py +30 -34
  91. package/modules/localmodels/stack_journal.py +29 -8
  92. package/modules/localmodels/stack_ledger.py +411 -0
  93. package/modules/localmodels/stack_lifecycle.py +162 -167
  94. package/modules/localmodels/stack_llm_ram.py +57 -5
  95. package/modules/localmodels/stack_memory.py +721 -0
  96. package/modules/localmodels/stack_picks.py +147 -0
  97. package/modules/localmodels/stack_plan.py +143 -25
  98. package/modules/localmodels/stack_ports.py +22 -0
  99. package/modules/localmodels/stack_preflight.py +699 -0
  100. package/modules/localmodels/stack_review.py +123 -5
  101. package/modules/localmodels/stack_rollback.py +2 -0
  102. package/modules/localmodels/stack_route.py +256 -0
  103. package/modules/localmodels/stack_run.py +11 -0
  104. package/modules/localmodels/stack_suite.py +107 -20
  105. package/modules/localmodels/stack_summary.py +65 -4
  106. package/modules/localmodels/stack_try.py +354 -0
  107. package/modules/localmodels/stack_try_client.py +194 -0
  108. package/modules/localmodels/stack_try_docs.py +139 -0
  109. package/modules/localmodels/stack_up.py +8 -1
  110. package/modules/localmodels/stack_update.py +29 -4
  111. package/modules/localmodels/stack_verify.py +3 -1
  112. package/modules/localmodels/stack_view.py +10 -11
  113. package/modules/localmodels/stack_view_apply.py +4 -2
  114. package/modules/localmodels/stack_view_events.py +2 -1
  115. package/modules/localmodels/stack_view_serve.py +3 -0
  116. package/modules/localmodels/stack_view_text.py +1 -1
  117. package/modules/localmodels/stack_view_words.py +4 -1
  118. package/modules/localmodels/stack_warm.py +574 -0
  119. package/modules/localmodels/stack_whatif.py +558 -0
  120. package/modules/localmodels/suite.py +48 -39
  121. package/modules/localmodels/tool_archive.py +40 -0
  122. package/modules/localmodels/tools.json +8 -0
  123. package/modules/localmodels/transport.py +1 -0
  124. package/modules/localmodels/vision.py +8 -1
  125. package/modules/localmodels/web/sizecalc/app.js +431 -0
  126. package/modules/localmodels/web/sizecalc/calc.js +269 -0
  127. package/modules/localmodels/web/sizecalc/page.html +362 -0
  128. package/modules/localmodels/web/view/ASSET-SOURCES.md +11 -0
  129. package/modules/localmodels/web/view/i18n.js +1 -1
  130. package/modules/localmodels/web/view/logo-claude.svg +3 -0
  131. package/modules/localmodels/web/view/logo-codex.png +0 -0
  132. package/modules/localmodels/web/view/logo-pi.svg +6 -0
  133. package/modules/localmodels/web/view/view.css +4 -0
  134. package/modules/localmodels/web/view/view.js +15 -6
  135. package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/METADATA +1 -1
  136. package/modules/simplex_localmodels-0.1.0.dev36.dist-info/RECORD +242 -0
  137. package/package.json +1 -1
  138. package/tool.json +1 -1
  139. package/modules/simplex_localmodels-0.1.0.dev32.dist-info/RECORD +0 -200
  140. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/WHEEL +0 -0
  141. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/entry_points.txt +0 -0
  142. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/NOTICE +0 -0
  143. /package/modules/{simplex_localmodels-0.1.0.dev32.dist-info → simplex_localmodels-0.1.0.dev36.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,314 @@
1
+ """``library download`` and ``library cancel``, and what the library commands share: the host
2
+ probe, the executor and the weights on disk.
3
+
4
+ A download runs the stack's own engine and download steps (remote_ops: mirrors, parallel
5
+ ranges, resume of a ``.part``, SHA256 against the catalog pin) for the plan priced on the pool
6
+ it picks, and records that pool. Then it loads the model when the pool has room, unless told
7
+ not to; a pool without room leaves it ``idle`` with the note ``NO_ROOM_TO_LOAD``. A cancel
8
+ signals the job's process group through its receipt and deletes what the download wrote.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import signal
15
+ import time
16
+ from collections.abc import Callable
17
+ from pathlib import Path
18
+
19
+ from localmodels import (
20
+ app,
21
+ deploy_steps,
22
+ hosts,
23
+ library_gateway,
24
+ library_pricing,
25
+ library_state,
26
+ library_status,
27
+ plan_envelope,
28
+ remote_ops_download,
29
+ )
30
+ from localmodels.deploy_steps import Action
31
+ from localmodels.library_model import (
32
+ NO_ROOM_TO_LOAD,
33
+ LibraryError,
34
+ Row,
35
+ progress,
36
+ )
37
+ from localmodels.library_pricing import Model
38
+ from localmodels.library_state import JobHandle, Record
39
+ from localmodels.probe import HostFacts
40
+ from localmodels.records import Plan
41
+ from localmodels.transport import Executor
42
+
43
+
44
+ def probe() -> HostFacts:
45
+ return app.probe(hosts.LOCAL_ID)
46
+
47
+
48
+ def executor() -> Executor:
49
+ return hosts.executor(hosts.get_device(hosts.LOCAL_ID))
50
+
51
+
52
+ def cancel_on_sigterm() -> None:
53
+ """A cancel's SIGTERM ends this job like Ctrl+C, so its cleanup runs."""
54
+ signal.signal(signal.SIGTERM, signal.default_int_handler)
55
+
56
+
57
+ def dests(plan: Plan) -> list[str]:
58
+ return [os.path.expanduser(f["dest"]) for f in plan["files"]]
59
+
60
+
61
+ def in_use(skip: str) -> set[str]:
62
+ """Model files another library model, another live job (one it writes, or one it verified
63
+ and will record), or a deployment this tool runs outside the library still needs."""
64
+ used: set[str] = set(claimed_elsewhere(skip))
65
+ for other, (job, alive) in library_state.jobs().items():
66
+ if other != skip and alive:
67
+ used.update(os.path.realpath(f) for f in job.get("needs", []))
68
+ for record in library_state.records():
69
+ if record["id"] != skip:
70
+ used.update(dests(record["plan"]))
71
+ library_names = {r["plan"]["name"] for r in library_state.records()}
72
+ for name, owned in hosts.load_owned()["deployments"].items():
73
+ if name not in library_names and not owned["removed"]:
74
+ used.update(os.path.expanduser(f) for f in owned["files"])
75
+ return used
76
+
77
+
78
+ def delete_weights(files: list[str], keep: set[str]) -> list[str]:
79
+ """Delete each file (with its partial download and SHA256 receipt) unless ``keep`` has it."""
80
+ deleted = []
81
+ for path in files:
82
+ if os.path.realpath(path) in {os.path.realpath(k) for k in keep}:
83
+ continue
84
+ remote_ops_download.discard(path + ".part")
85
+ for name in (path, path + ".sha256"):
86
+ if os.path.lexists(name):
87
+ os.remove(name)
88
+ deleted.append(name)
89
+ return deleted
90
+
91
+
92
+ def _code(message: str) -> str:
93
+ text = message.lower()
94
+ if "sha256 mismatch" in text:
95
+ return "CHECKSUM_MISMATCH"
96
+ if "low disk space" in text or "no space left" in text:
97
+ return "DISK_INSUFFICIENT"
98
+ network = ("urlopen", "name or service", "timed out", "connection", "network", "resolve")
99
+ if any(word in text for word in network):
100
+ return "NETWORK_UNAVAILABLE"
101
+ return "DOWNLOAD_FAILED"
102
+
103
+
104
+ class _Counter:
105
+ """Bytes of the whole model: the files already verified count as done; each progress event
106
+ moves its file's counter for the phase it reports."""
107
+
108
+ def __init__(self, model: str, plan: Plan, handle: JobHandle) -> None:
109
+ self.model, self.handle = model, handle
110
+ self.sizes = {os.path.basename(f["dest"]): f["size_bytes"] for f in plan["files"]}
111
+ self.done = {
112
+ os.path.basename(f["dest"]): f["size_bytes"]
113
+ for f in plan["files"]
114
+ if plan_envelope.verified_in_place(f)
115
+ }
116
+
117
+ @property
118
+ def total(self) -> int:
119
+ return sum(self.sizes.values())
120
+
121
+ def __call__(self, event: dict[str, object]) -> None:
122
+ label = str(event.get("file") or "")
123
+ if event.get("event") != "progress" or label not in self.sizes:
124
+ return
125
+ phase = "verify" if event.get("phase") == "verify" else "download"
126
+ done = event.get("done")
127
+ speed = event.get("bytes_per_s")
128
+ self.done[label] = int(done) if isinstance(done, int) else 0
129
+ finished = sum(min(n, self.sizes[k]) for k, n in self.done.items())
130
+ rate = int(speed) if isinstance(speed, int) and phase == "download" else 0
131
+ self.handle.update(phase, finished, self.total, rate)
132
+ progress(self.model, phase, finished, self.total, rate) # type: ignore[arg-type]
133
+
134
+
135
+ def fetch(
136
+ model: str,
137
+ plan: Plan,
138
+ handle: JobHandle,
139
+ run: Executor,
140
+ only: set[str] | None = None,
141
+ *,
142
+ engine: bool = True,
143
+ ) -> None:
144
+ """The plan's engine (when it is a pinned release) and weights, as stack apply fetches them;
145
+ ``only`` limits the weights to the files this job claims. Progress counts the whole model."""
146
+ counter = _Counter(model, plan, handle)
147
+ progress(model, "download", sum(counter.done.values()), counter.total)
148
+ files = [f for f in plan["files"] if only is None or os.path.expanduser(f["dest"]) in only]
149
+ steps: tuple[Action, ...] = ("download",) if files else ()
150
+ if engine and plan["engine"]["source"] == "release":
151
+ steps = ("engine", *steps)
152
+ mine: Plan = {**plan, "files": files}
153
+ for step in steps:
154
+ on_event = counter if step == "download" else None
155
+ outcome, result = run.run_action(
156
+ step, deploy_steps.step_params(mine, step, ""), on_event=on_event or (lambda _e: None)
157
+ )
158
+ if result.returncode != 0 or outcome.get("event") != "result":
159
+ message = str(outcome.get("message") or result.stderr.strip()[-500:] or "failed")
160
+ raise LibraryError(_code(message), message, failed=True)
161
+ progress(model, "verify", counter.total, counter.total)
162
+
163
+
164
+ WAIT_S = 2.0 # how often a download looks at a file another download is fetching
165
+
166
+
167
+ def claimed_elsewhere(model: str) -> set[str]:
168
+ """Files other live jobs claim (a download fetching them): nobody else deletes or writes
169
+ their partial files."""
170
+ found: set[str] = set()
171
+ for other, (job, alive) in library_state.jobs().items():
172
+ if other != model and alive:
173
+ found.update(os.path.realpath(f) for f in job["files"])
174
+ return found
175
+
176
+
177
+ def pause() -> None:
178
+ time.sleep(WAIT_S)
179
+
180
+
181
+ def _shared(model: str, plan: Plan, handle: JobHandle, run: Executor, waiting: list[str]) -> None:
182
+ """Files another live download claimed when this one started: wait until they are in place,
183
+ or claim and fetch one when its download ended without it."""
184
+ by_dest = {os.path.expanduser(f["dest"]): f for f in plan["files"]}
185
+ while waiting:
186
+ for dest in list(waiting):
187
+ if plan_envelope.verified_in_place(by_dest[dest]):
188
+ waiting.remove(dest)
189
+ continue
190
+ with library_state.locked():
191
+ take = os.path.realpath(dest) not in claimed_elsewhere(model)
192
+ if take:
193
+ handle.job["files"].append(dest)
194
+ hosts.save_private(library_state.job_path(model), handle.job)
195
+ if take:
196
+ fetch(model, plan, handle, run, {dest}, engine=False)
197
+ waiting.remove(dest)
198
+ if waiting:
199
+ pause()
200
+
201
+
202
+ def _refuse_download(lib: library_status.Library, model: Model) -> library_pricing.Priced:
203
+ if (problem := library_pricing.platform_problem(lib.facts)) is not None:
204
+ raise LibraryError("PLATFORM_UNSUPPORTED", problem)
205
+ job, alive = lib.jobs.get(model.id, (None, False))
206
+ if job is not None and alive:
207
+ raise LibraryError("JOB_RUNNING", f"{model.id} already has a running {job['kind']}")
208
+ if model.id in lib.records:
209
+ raise LibraryError("INVALID_STATE", f"{model.id} is already downloaded")
210
+ priced = lib.judge(model)
211
+ reason = library_pricing.download_reason(
212
+ lib.facts, priced, library_pricing.base_free(lib.base_dir)
213
+ )
214
+ if reason is not None:
215
+ error = LibraryError(reason["code"], f"{model.id} cannot be downloaded here")
216
+ if "need_bytes" in reason:
217
+ error.fields = {"need_bytes": reason["need_bytes"], "have_bytes": reason["have_bytes"]}
218
+ raise error
219
+ return priced
220
+
221
+
222
+ def download(
223
+ model_id: str,
224
+ base_dir: str,
225
+ *,
226
+ autoload: bool,
227
+ load: Callable[[str, str, list[str]], Row],
228
+ ) -> Row:
229
+ """Fetch the model into ``base_dir``, record it, then load it when its pool has room."""
230
+ from localmodels import library_convert
231
+
232
+ library_convert.convert_once()
233
+ lib = library_status.Library.read(probe(), base_dir)
234
+ model = library_pricing.find(model_id, lib.catalog)
235
+ priced = _refuse_download(lib, model)
236
+ assert priced.plan is not None
237
+ plan, files = priced.plan, dests(priced.plan)
238
+ memory = library_pricing.memory_bytes(plan)
239
+ cancel_on_sigterm()
240
+ with library_state.locked(): # validated again with the claim, as one step
241
+ library_state.refuse_busy(model.id, "download")
242
+ if library_state.load(model.id) is not None:
243
+ raise LibraryError("INVALID_STATE", f"{model.id} is already downloaded")
244
+ others = claimed_elsewhere(model.id)
245
+ mine = [f for f in files if os.path.realpath(f) not in others]
246
+ job = library_state.acquire("download", model.id, priced.pool, memory, mine, files)
247
+ with library_state.held([job]):
248
+ handle = library_state.JobHandle(job)
249
+ try:
250
+ fetch(model.id, plan, handle, executor(), set(mine))
251
+ _shared(model.id, plan, handle, executor(), [f for f in files if f not in mine])
252
+ except KeyboardInterrupt: # what it claimed, unless something else needs it now
253
+ with library_state.locked():
254
+ delete_weights(handle.job["files"], in_use(model.id))
255
+ raise LibraryError("CANCELLED", "the download was cancelled") from None
256
+ selector = library_gateway.pi_model(model.id, str(plan["endpoint"]["model"]))
257
+ record: Record = library_state.new_record(
258
+ model.id, model.entry.id, model.variant.quant, priced.pool, plan, selector
259
+ )
260
+ record["memory_bytes"] = memory
261
+ record["base_dir"] = base_dir
262
+ with library_state.locked(): # commit only as this job, and only if not cancelled
263
+ found = library_state.read_job(model.id)
264
+ if found is None or found.get("id") != job["id"] or library_state.cancelled(job):
265
+ delete_weights(handle.job["files"], in_use(model.id))
266
+ raise LibraryError("CANCELLED", "the download was cancelled")
267
+ # The record and the end of this download are one step: from here the files are
268
+ # the record's, and no download job is left for a cancel to act on.
269
+ library_state.save(record)
270
+ library_state.clear_job(model.id)
271
+ if not autoload:
272
+ return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
273
+ try:
274
+ return load(model.id, base_dir, [])
275
+ except LibraryError as exc:
276
+ if exc.code != "LOAD_NO_ROOM":
277
+ raise
278
+ record_ = library_state.load(model.id)
279
+ if record_ is not None:
280
+ record_["note"] = {"code": NO_ROOM_TO_LOAD}
281
+ library_state.save(record_)
282
+ return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
283
+
284
+
285
+ def cancel(model_id: str, base_dir: str) -> Row:
286
+ """Stop the model's running download and delete what it wrote."""
287
+ model = library_pricing.find(model_id, library_pricing.entries())
288
+ with library_state.locked(): # this download, by its id: never a job that replaces it
289
+ job = library_state.read_job(model.id)
290
+ if job is None or job["kind"] != "download":
291
+ raise LibraryError("INVALID_STATE", f"{model.id} has no running download")
292
+ if library_state.load(model.id) is not None: # committed: the files are the record's
293
+ if not library_state.job_alive(model.id):
294
+ library_state.clear_job(model.id) # a leftover of a process that died
295
+ raise LibraryError("INVALID_STATE", f"{model.id} is already downloaded")
296
+ identity = library_state.receipt(model.id)
297
+ # Marking is idempotent for this job: after a stop that failed, cancel runs again
298
+ # against the same captured process instead of refusing a download it already marked.
299
+ library_state.mark_cancelled(job) # it can no longer commit a record
300
+ if identity is not None:
301
+ try:
302
+ library_state.stop_process(identity) # exactly that process, its receipt captured
303
+ except (OSError, RuntimeError) as exc:
304
+ raise LibraryError("INVALID_STATE", f"cannot stop the download: {exc}") from None
305
+ with library_state.locked(): # it ended without cleaning up after itself (killed)
306
+ committed = library_state.load(model.id) is not None
307
+ if library_state.current(job) and not library_state.job_alive(model.id) and not committed:
308
+ delete_weights(job["files"], in_use(model.id))
309
+ library_state.clear_job(model.id)
310
+ return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
311
+
312
+
313
+ def files_missing(plan: Plan) -> list[str]:
314
+ return [Path(f["dest"]).name for f in plan["files"] if not plan_envelope.verified_in_place(f)]
@@ -0,0 +1,246 @@
1
+ """The ``library`` documents: the status object, its model rows and pools, the JSONL events,
2
+ and the closed set of error codes with their exit statuses (Linger installer contract v2).
3
+
4
+ Everything here is data. The library's state lives in library_state, the prices in
5
+ library_pricing, and the commands in library_jobs and library_serve.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import sys
12
+ from typing import Literal, TypedDict
13
+
14
+ STATUS_SCHEMA = "localmodels.library-status/v1"
15
+ EVENT_SCHEMA = "localmodels.library-event/v1"
16
+
17
+ ModelState = Literal["absent", "downloading", "idle", "loading", "loaded", "failed"]
18
+ Fit = Literal["gpu", "unified", "system", "none"]
19
+ Phase = Literal["download", "verify", "load", "warm"]
20
+
21
+ # Extend only together with the contract (contracts/linger-installer/library-v2.schema.json).
22
+ ERROR_CODES = (
23
+ "MODEL_UNKNOWN",
24
+ "INVALID_STATE",
25
+ "JOB_RUNNING",
26
+ "MEMORY_INSUFFICIENT",
27
+ "DISK_INSUFFICIENT",
28
+ "PLATFORM_UNSUPPORTED",
29
+ "LOAD_NO_ROOM",
30
+ "DOWNLOAD_FAILED",
31
+ "CHECKSUM_MISMATCH",
32
+ "NETWORK_UNAVAILABLE",
33
+ "ENGINE_START_FAILED",
34
+ "HEALTH_CHECK_FAILED",
35
+ "OUT_OF_MEMORY",
36
+ "MODEL_FILES_MISSING",
37
+ "GATEWAY_REGISTRATION_FAILED",
38
+ "CANCELLED",
39
+ )
40
+ # Refusals: validation or a precondition, decided before anything changed.
41
+ REFUSALS = frozenset(
42
+ (
43
+ "MODEL_UNKNOWN",
44
+ "INVALID_STATE",
45
+ "JOB_RUNNING",
46
+ "MEMORY_INSUFFICIENT",
47
+ "DISK_INSUFFICIENT",
48
+ "PLATFORM_UNSUPPORTED",
49
+ "LOAD_NO_ROOM",
50
+ "MODEL_FILES_MISSING",
51
+ )
52
+ )
53
+ EXIT_OK, EXIT_FAILED, EXIT_REFUSED, EXIT_CANCELLED = 0, 1, 2, 130
54
+ NO_ROOM_TO_LOAD = "NO_ROOM_TO_LOAD"
55
+ DETAIL_LIMIT = 500 # diagnostic text only; consumers never match on it
56
+
57
+
58
+ class LibraryError(Exception):
59
+ """One contract error: its code, a diagnostic detail and the structured fields it carries
60
+ (``pool``, ``need_bytes``, ``free_bytes``, ``have_bytes``). ``failed`` marks one raised
61
+ after the command changed something: it exits 1 whatever its code."""
62
+
63
+ def __init__(
64
+ self, code: str, detail: str, *, failed: bool = False, **fields: str | int
65
+ ) -> None:
66
+ if code not in ERROR_CODES:
67
+ raise ValueError(f"unknown library error code {code}")
68
+ super().__init__(detail)
69
+ self.code = code
70
+ self.detail = detail[-DETAIL_LIMIT:]
71
+ self.failed = failed
72
+ self.fields = fields
73
+
74
+ @property
75
+ def exit_code(self) -> int:
76
+ if self.code == "CANCELLED":
77
+ return EXIT_CANCELLED
78
+ return EXIT_REFUSED if self.code in REFUSALS and not self.failed else EXIT_FAILED
79
+
80
+
81
+ class Gpu(TypedDict):
82
+ index: int
83
+ uuid: str
84
+ name: str
85
+ total_bytes: int
86
+ free_bytes: int
87
+
88
+
89
+ class Host(TypedDict):
90
+ platform: str # linux | darwin | windows
91
+ arch: str # x86_64 | arm64
92
+ os_label: str
93
+ engine_label: str
94
+ ram_total_bytes: int
95
+ disk_free_bytes: int
96
+ gpus: list[Gpu]
97
+
98
+
99
+ class Holder(TypedDict):
100
+ kind: Literal["model", "component"]
101
+ id: str
102
+ name: str
103
+ bytes: int
104
+
105
+
106
+ class Pool(TypedDict):
107
+ id: str # gpu:N | system | unified
108
+ total_bytes: int
109
+ used_bytes: int
110
+ holders: list[Holder]
111
+
112
+
113
+ class _Reason(TypedDict):
114
+ code: str # MEMORY_INSUFFICIENT | DISK_INSUFFICIENT | PLATFORM_UNSUPPORTED
115
+
116
+
117
+ class Reason(_Reason, total=False):
118
+ need_bytes: int
119
+ have_bytes: int
120
+
121
+
122
+ class _Availability(TypedDict):
123
+ downloadable: bool
124
+
125
+
126
+ class Availability(_Availability, total=False):
127
+ reason: Reason # only when not downloadable
128
+
129
+
130
+ class Download(TypedDict):
131
+ step: Literal["download", "verify"]
132
+ done_bytes: int
133
+ total_bytes: int
134
+ bytes_per_second: int
135
+
136
+
137
+ class Endpoint(TypedDict):
138
+ base_url: str
139
+ gateway_model: str
140
+
141
+
142
+ class Problem(TypedDict):
143
+ code: str
144
+ detail: str
145
+
146
+
147
+ class Note(TypedDict):
148
+ code: str
149
+
150
+
151
+ class _Row(TypedDict):
152
+ id: str
153
+ name: str
154
+ description: str
155
+ quant: str
156
+ context_tokens: int
157
+ vision: bool
158
+ download_bytes: int
159
+ memory_bytes: int
160
+ fit: Fit
161
+ recommended: bool
162
+ availability: Availability
163
+ pool: str
164
+ state: ModelState
165
+
166
+
167
+ class Row(_Row, total=False):
168
+ download: Download # downloading only
169
+ endpoint: Endpoint # loaded only
170
+ pi_model: str # every model not absent: <pi provider>/<pi model id> once it is loaded
171
+ tokens_per_second: float # the last measured warm speed; absent when unknown
172
+ error: Problem # failed only
173
+ note: Note # idle only, when autoload was skipped
174
+
175
+
176
+ class Status(TypedDict):
177
+ schema: str
178
+ tool_version: str
179
+ observed_at: str
180
+ host: Host
181
+ pools: list[Pool]
182
+ models: list[Row]
183
+
184
+
185
+ def library_id(catalog_id: str, quant: str) -> str:
186
+ """The stable library id: the catalog id and its variant."""
187
+ return f"{catalog_id}:{quant}"
188
+
189
+
190
+ def display_name(model: str, quant: str) -> str:
191
+ """What a person reads: the model's name and its variant, so no two rows share one (two
192
+ catalog ids can share a display name, and one id has a row per variant)."""
193
+ return f"{model} ({quant})"
194
+
195
+
196
+ def split_id(value: str) -> tuple[str, str]:
197
+ """(catalog id, quant); a bare catalog id has an empty quant (its last variant)."""
198
+ catalog_id, _, quant = value.partition(":")
199
+ return catalog_id, quant
200
+
201
+
202
+ def _line(doc: object) -> None:
203
+ sys.stdout.write(json.dumps(doc, ensure_ascii=False, separators=(",", ":")) + "\n")
204
+ sys.stdout.flush()
205
+
206
+
207
+ def progress(model: str, phase: Phase, done: int, total: int, bytes_per_second: int = 0) -> None:
208
+ """One JSONL progress line; counters are clamped to 0 <= done <= total."""
209
+ total = max(0, int(total))
210
+ _line(
211
+ {
212
+ "schema": EVENT_SCHEMA,
213
+ "event": "progress",
214
+ "model": model,
215
+ "phase": phase,
216
+ "done": min(max(0, int(done)), total),
217
+ "total": total,
218
+ "bytes_per_second": max(0, int(bytes_per_second)),
219
+ }
220
+ )
221
+
222
+
223
+ def result_doc(row: Row) -> dict[str, object]:
224
+ return {"schema": EVENT_SCHEMA, "event": "result", "ok": True, "model": row}
225
+
226
+
227
+ def error_doc(error: LibraryError, model: str | None = None) -> dict[str, object]:
228
+ doc: dict[str, object] = {
229
+ "schema": EVENT_SCHEMA,
230
+ "event": "error",
231
+ "ok": False,
232
+ "code": error.code,
233
+ "detail": error.detail,
234
+ }
235
+ if model is not None:
236
+ doc["model"] = model
237
+ doc.update(error.fields)
238
+ return doc
239
+
240
+
241
+ def emit_final(doc: dict[str, object], *, jsonl: bool) -> None:
242
+ """The final line of a JSONL command, or the one document of a JSON command."""
243
+ if jsonl:
244
+ _line(doc)
245
+ else:
246
+ print(json.dumps(doc, ensure_ascii=False, indent=1))