@simplexai/localmodels-linux-x64 0.1.0-dev.43 → 0.1.0-dev.45

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/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +76 -79
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +0 -1
  5. package/modules/localmodels/auth_proxy.py +285 -82
  6. package/modules/localmodels/bifrost_checks.py +3 -127
  7. package/modules/localmodels/bifrost_clients.py +1 -1
  8. package/modules/localmodels/bifrost_config.py +2 -2
  9. package/modules/localmodels/bifrost_models.py +9 -2
  10. package/modules/localmodels/bifrost_pi.py +1 -1
  11. package/modules/localmodels/bifrost_provider.py +42 -7
  12. package/modules/localmodels/budget.py +16 -1
  13. package/modules/localmodels/catalog.json +15 -50
  14. package/modules/localmodels/catalog_recipes.py +1 -1
  15. package/modules/localmodels/debug_mode.py +2 -18
  16. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +41 -1
  17. package/modules/localmodels/engines.py +19 -6
  18. package/modules/localmodels/gateway.py +50 -15
  19. package/modules/localmodels/gateway_accept.py +8 -5
  20. package/modules/localmodels/gateway_bifrost.py +23 -13
  21. package/modules/localmodels/gateway_cli.py +5 -2
  22. package/modules/localmodels/gateway_requests.py +9 -2
  23. package/modules/localmodels/harness.py +41 -12
  24. package/modules/localmodels/harness_gateway.py +1 -1
  25. package/modules/localmodels/hosts.py +7 -20
  26. package/modules/localmodels/library_convert.py +491 -57
  27. package/modules/localmodels/library_gateway.py +27 -16
  28. package/modules/localmodels/library_pricing.py +155 -31
  29. package/modules/localmodels/library_status.py +29 -4
  30. package/modules/localmodels/npm_transport.py +62 -54
  31. package/modules/localmodels/probe.py +42 -9
  32. package/modules/localmodels/recommend.py +1 -1
  33. package/modules/localmodels/recommend_cli.py +2 -2
  34. package/modules/localmodels/remote_ops.py +14 -6
  35. package/modules/localmodels/remote_ops_download.py +1 -1
  36. package/modules/localmodels/remote_ops_verify.py +0 -33
  37. package/modules/localmodels/runtime_args.py +2 -1
  38. package/modules/localmodels/runtime_auth.py +75 -25
  39. package/modules/localmodels/runtime_cli.py +9 -9
  40. package/modules/localmodels/runtime_install.py +57 -23
  41. package/modules/localmodels/runtime_io.py +224 -243
  42. package/modules/localmodels/runtime_process.py +15 -7
  43. package/modules/localmodels/runtime_windows_acl.py +196 -0
  44. package/modules/localmodels/source_byok.py +122 -33
  45. package/modules/localmodels/source_byok_probe.py +57 -141
  46. package/modules/localmodels/source_cli.py +19 -18
  47. package/modules/localmodels/stack.py +13 -6
  48. package/modules/localmodels/stack_args.py +6 -8
  49. package/modules/localmodels/stack_binding.py +3 -3
  50. package/modules/localmodels/stack_client_settings.py +8 -1
  51. package/modules/localmodels/stack_compose.py +4 -8
  52. package/modules/localmodels/stack_events.py +2 -1
  53. package/modules/localmodels/stack_plan.py +1 -4
  54. package/modules/localmodels/stack_ports.py +0 -1
  55. package/modules/localmodels/stack_route.py +1 -5
  56. package/modules/localmodels/stack_run.py +15 -30
  57. package/modules/localmodels/stack_suite.py +23 -46
  58. package/modules/localmodels/stack_summary.py +0 -1
  59. package/modules/localmodels/stack_try.py +3 -92
  60. package/modules/localmodels/stack_up.py +27 -4
  61. package/modules/localmodels/stack_update.py +5 -5
  62. package/modules/localmodels/stack_view_apply.py +1 -1
  63. package/modules/localmodels/stack_view_sandbox.py +0 -2
  64. package/modules/localmodels/stack_view_text.py +0 -1
  65. package/modules/localmodels/stack_view_words.py +0 -1
  66. package/modules/localmodels/suite.py +4 -7
  67. package/modules/localmodels/tui_dialogs.py +0 -1
  68. package/modules/localmodels/vision.py +2 -1
  69. package/modules/localmodels/web/view/view.css +1 -4
  70. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/METADATA +1 -1
  71. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/RECORD +73 -76
  72. package/package.json +1 -1
  73. package/tool.json +1 -1
  74. package/modules/localmodels/bifrost_search.py +0 -66
  75. package/modules/localmodels/gateway_search.py +0 -223
  76. package/modules/localmodels/search-ddgs-9.16.1.txt +0 -222
  77. package/modules/localmodels/search_server.py +0 -474
  78. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/WHEEL +0 -0
  79. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/entry_points.txt +0 -0
  80. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/NOTICE +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -1,40 +1,55 @@
1
- """Adopt a Quick Install stack's LLM into the library, once.
1
+ """Adopt a Quick Install stack's LLMs into the library and keep them in step with ``stack apply``.
2
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.
3
+ The first library command on a computer adopts the LLMs of the stack ``stack apply`` last accepted:
4
+ each becomes a library model in state ``loaded`` with the stack's own gateway wiring recorded as
5
+ its registration, and a marker records that stack's plan and attempt ids. When a later
6
+ ``stack apply`` (or ``stack rollback`` / ``stack up``) installs, restarts or replaces the stack's
7
+ LLM, both the stack command (when the library has already been used) and the next library command
8
+ re-sync: the live stack LLM becomes ``loaded`` under its new deployment plan and any replaced
9
+ stack LLM is demoted back to an ordinary library model so it no longer claims
10
+ ``localmodels/localmodels-agent`` or masks the live server.
8
11
  """
9
12
 
10
13
  from __future__ import annotations
11
14
 
15
+ import datetime as dt
12
16
  import json
13
17
  from pathlib import Path
14
18
  from typing import Any
15
19
 
16
20
  from localmodels import (
21
+ approval,
17
22
  gateway_bifrost,
18
23
  harness,
19
24
  hosts,
20
25
  library_gateway,
21
26
  library_pricing,
22
27
  library_state,
28
+ library_status,
29
+ stack_run,
23
30
  stack_up,
24
31
  )
25
32
  from localmodels.contracts import decode
26
33
  from localmodels.library_model import library_id
27
- from localmodels.library_state import Registration
34
+ from localmodels.library_state import Record, Registration
28
35
  from localmodels.plan_envelope import utc_now
36
+ from localmodels.records import Plan
37
+ from localmodels.stack_plan import StackPlan
29
38
 
30
39
  MARKER = "converted.json"
31
40
  STACK_LLMS = {"llm": harness.LLM_PROVIDER, "llm_fast": gateway_bifrost.FAST_PROVIDER}
41
+ STACK_PROVIDERS = frozenset(STACK_LLMS.values())
32
42
 
33
43
 
34
44
  def _record_files() -> list[Path]:
35
45
  return sorted((library_state.root() / "models").glob("*.json"))
36
46
 
37
47
 
48
+ def initialized() -> bool:
49
+ """Whether the model library has recorded state on this computer yet."""
50
+ return (library_state.root() / MARKER).is_file() or bool(_record_files())
51
+
52
+
38
53
  def _older(path: Path) -> dict[str, Any] | None:
39
54
  """The record at ``path`` when an earlier schema saved it."""
40
55
  try:
@@ -73,60 +88,479 @@ def upgrade() -> list[str]:
73
88
  return upgraded
74
89
 
75
90
 
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():
91
+ def _read_marker(path: Path) -> dict[str, Any] | None:
92
+ try:
93
+ value = json.loads(path.read_text(encoding="utf-8"))
94
+ except (OSError, ValueError):
95
+ return None
96
+ return value if isinstance(value, dict) else None
97
+
98
+
99
+ def _parse_ts(value: object) -> dt.datetime | None:
100
+ if not isinstance(value, str) or not value:
101
+ return None
102
+ try:
103
+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
104
+ except ValueError:
105
+ return None
106
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=dt.timezone.utc)
107
+
108
+
109
+ def _is_newer(candidate: object, baseline: object) -> bool:
110
+ first, second = _parse_ts(candidate), _parse_ts(baseline)
111
+ return first is not None and second is not None and first > second
112
+
113
+
114
+ def _latest_accepted_run() -> tuple[StackPlan, str | None, str | None] | None:
115
+ """The newest stack apply on disk when it passed acceptance: ``(plan, attempt_id, finished)``."""
116
+ for run, saved in reversed(hosts.stack_runs()):
117
+ view = stack_run.project(run, saved)
118
+ if view is None or not view["ok"] or saved is None:
119
+ return None
120
+ try:
121
+ plan = decode(saved, StackPlan)
122
+ except ValueError:
123
+ return None
124
+ if approval.digest(plan) == plan["plan_id"] == view["plan_id"]:
125
+ return plan, view["attempt_id"] or None, view["finished_at"]
126
+ return None
127
+ return None
128
+
129
+
130
+ def _planned_stack_llms(plan: StackPlan | None) -> dict[str, str]:
131
+ """``library_id -> stack_provider`` for every LLM declared by ``plan`` (running or unloaded)."""
132
+ if plan is None:
133
+ return {}
134
+ from localmodels import stack_verify
135
+
136
+ found: dict[str, str] = {}
137
+ for component, part in stack_verify.parts(plan):
138
+ if component not in STACK_LLMS:
139
+ continue
140
+ spec = part["model"]
141
+ found[library_id(spec["id"], spec["quant"])] = STACK_LLMS[component]
142
+ return found
143
+
144
+
145
+ def _active_stack_llms(plan: StackPlan | None) -> dict[str, tuple[str, Plan]]:
146
+ """Accepted stack LLM deployments still present and ok on disk: ``library_id -> (provider, plan)``."""
147
+ if plan is None:
148
+ return {}
149
+ from localmodels import stack_verify
150
+
151
+ found: dict[str, tuple[str, Plan]] = {}
152
+ for component, part in stack_verify.parts(plan):
153
+ if component not in STACK_LLMS:
154
+ continue
155
+ try:
156
+ dep = hosts.record(hosts.LOCAL_ID, part["name"])
157
+ except KeyError:
158
+ continue
159
+ if not dep.get("ok"):
160
+ continue
161
+ deployed = dep["plan"]
162
+ spec = deployed["model"]
163
+ found[library_id(spec["id"], spec["quant"])] = (STACK_LLMS[component], deployed)
164
+ return found
165
+
166
+
167
+ def _is_stack_record(record: Record) -> bool:
168
+ reg = record.get("registration")
169
+ return bool(
170
+ record.get("converted")
171
+ or record.get("stack_provider") in STACK_PROVIDERS
172
+ or (
173
+ reg is not None
174
+ and (reg.get("kind") in ("stack", "agent") or reg.get("provider") in STACK_PROVIDERS)
175
+ )
176
+ or record.get("pi_model") == gateway_bifrost.PI_MODEL
177
+ )
178
+
179
+
180
+ def _record_stack_provider(record: Record) -> str | None:
181
+ reg = record.get("registration")
182
+ provider = record.get("stack_provider") or (reg.get("provider") if reg is not None else None)
183
+ if provider in STACK_PROVIDERS:
184
+ return str(provider)
185
+ if record.get("converted") or record.get("pi_model") == gateway_bifrost.PI_MODEL:
186
+ return harness.LLM_PROVIDER
187
+ return None
188
+
189
+
190
+ def _stack_registration(provider: str) -> Registration:
191
+ return {
192
+ "kind": "stack",
193
+ "provider": provider,
194
+ "model": gateway_bifrost.AGENT_MODEL,
195
+ "pi_provider": gateway_bifrost.PI_PROVIDER,
196
+ "pi_model": gateway_bifrost.PI_MODEL,
197
+ }
198
+
199
+
200
+ def _stale_still_running(
201
+ active: dict[str, tuple[str, Plan]],
202
+ *,
203
+ keep: frozenset[str] = frozenset(),
204
+ providers: frozenset[str] | None = None,
205
+ ) -> set[str]:
206
+ """Stale stack records whose own deployment still exists on a distinct port and answers.
207
+
208
+ Probed before taking ``library_state.locked()`` so the lock never waits on HTTP timeouts.
209
+ """
210
+ active_names = {deployed["name"] for _, deployed in active.values()}
211
+ active_ports = {deployed["service"]["port"] for _, deployed in active.values()}
212
+ running: set[str] = set()
213
+ for record in library_state.records():
214
+ if record["id"] in active or record["id"] in keep or not _is_stack_record(record):
215
+ continue
216
+ if providers is not None and _record_stack_provider(record) not in providers:
217
+ continue
218
+ old_name = record["plan"]["name"]
219
+ old_port = record["plan"]["service"]["port"]
220
+ if old_name in active_names or old_port in active_ports:
221
+ continue
222
+ try:
223
+ hosts.record(hosts.LOCAL_ID, old_name)
224
+ except KeyError:
225
+ continue
226
+ if library_status.answering(str(record["plan"]["endpoint"]["base_url"])):
227
+ running.add(record["id"])
228
+ return running
229
+
230
+
231
+ def _demote_stale(
232
+ active: dict[str, tuple[str, Plan]],
233
+ still_running: set[str],
234
+ *,
235
+ keep: frozenset[str] = frozenset(),
236
+ providers: frozenset[str] | None = None,
237
+ ) -> None:
238
+ """Under ``locked()``: detach replaced stack records so they no longer claim stack routing."""
239
+ for record in library_state.records():
240
+ model = record["id"]
241
+ if (
242
+ model in active
243
+ or model in keep
244
+ or not _is_stack_record(record)
245
+ or library_state.job_alive(model)
246
+ ):
247
+ continue
248
+ if providers is not None and _record_stack_provider(record) not in providers:
249
+ continue
250
+ record.pop("converted", None)
251
+ record.pop("stack_provider", None)
252
+ record.pop("error", None)
253
+ record.pop("note", None)
254
+ reg = record.get("registration")
255
+ if reg is not None and (
256
+ reg.get("kind") in ("stack", "agent") or reg.get("provider") in STACK_PROVIDERS
257
+ ):
258
+ record.pop("registration", None)
259
+ record["pi_model"] = library_gateway.pi_model(
260
+ model, str(record["plan"]["endpoint"]["model"]), converted=False
261
+ )
262
+ if model in still_running:
263
+ record["state"] = "failed"
264
+ record["error"] = {
265
+ "code": "ENGINE_START_FAILED",
266
+ "detail": "replaced by a newer Quick Install stack; unload or load it again",
267
+ }
268
+ else:
269
+ record["state"] = "idle"
270
+ job = library_state.read_job(model)
271
+ if job is not None and job["kind"] != "download":
272
+ library_state.clear_job(model)
273
+ library_state.save(record)
274
+
275
+
276
+ def _adopt_record(model: str, provider: str, deployed: Plan, base_dir: str | None) -> bool:
277
+ """Under ``locked()``: create or refresh one library record for a live stack LLM."""
278
+ if library_state.job_alive(model):
279
+ return False
280
+ spec = deployed["model"]
281
+ pool = library_pricing.pool_of(deployed)
282
+ existing = library_state.load(model)
283
+ prev_deploy_dir = existing["plan"]["service"]["deploy_dir"] if existing is not None else None
284
+ if existing is None:
285
+ record = library_state.new_record(
286
+ model, spec["id"], spec["quant"], pool, deployed, gateway_bifrost.PI_MODEL
287
+ )
288
+ else:
289
+ record = existing
290
+ same_launch = (
291
+ record["plan"]["model"] == deployed["model"]
292
+ and record["plan"]["launch"] == deployed["launch"]
293
+ )
294
+ if not same_launch:
295
+ record.pop("tokens_per_second", None)
296
+ record.pop("prompt_tokens_per_second", None)
297
+ record["schema"] = library_state.RECORD_SCHEMA
298
+ record["catalog_id"] = spec["id"]
299
+ record["quant"] = spec["quant"]
300
+ record["pool"] = pool
301
+ record["plan"] = deployed
302
+ record["pi_model"] = gateway_bifrost.PI_MODEL
303
+ record["state"] = "loaded"
304
+ record["converted"] = True
305
+ record["stack_provider"] = provider
306
+ record["memory_bytes"] = library_pricing.memory_bytes(deployed)
307
+ if base_dir is not None:
308
+ record["base_dir"] = base_dir
309
+ elif prev_deploy_dir != deployed["service"]["deploy_dir"]:
310
+ record.pop("base_dir", None)
311
+ record.pop("error", None)
312
+ record.pop("note", None)
313
+ record["registration"] = _stack_registration(provider)
314
+ if library_state.read_job(model) is not None and not library_state.job_alive(model):
315
+ library_state.clear_job(model)
316
+ library_state.save(record)
317
+ return True
318
+
319
+
320
+ def _write_marker(
321
+ marker: Path, plan_id: str | None, attempt_id: str | None, adopted: list[str]
322
+ ) -> None:
323
+ doc: dict[str, Any] = {
324
+ "schema": "localmodels.library-conversion/v1",
325
+ "converted_at": utc_now(),
326
+ "plan_id": plan_id,
327
+ "adopted": adopted,
328
+ }
329
+ if attempt_id is not None:
330
+ doc["attempt_id"] = attempt_id
331
+ hosts.save_private(marker, doc)
332
+
333
+
334
+ def _plan_base_dir(plan: StackPlan | None) -> str | None:
335
+ if not isinstance(plan, dict):
336
+ return None
337
+ options = plan.get("options")
338
+ raw = options.get("base_dir") if isinstance(options, dict) else None
339
+ return raw if isinstance(raw, str) and raw else None
340
+
341
+
342
+ def _sync_with_plan(
343
+ plan: StackPlan | None, attempt_id: str | None, *, require_active: bool = False
344
+ ) -> list[str]:
345
+ active = _active_stack_llms(plan)
346
+ if require_active and plan is not None and not active:
82
347
  return []
348
+ planned = frozenset(_planned_stack_llms(plan))
349
+ still_running = _stale_still_running(active, keep=planned) if active else set()
350
+ marker = library_state.root() / MARKER
351
+ base_dir = _plan_base_dir(plan)
83
352
  with library_state.locked():
84
- if marker.is_file():
353
+ active = _active_stack_llms(plan)
354
+ if require_active and plan is not None and not active:
85
355
  return []
86
- adopted: list[str] = []
87
- plan = stack_up.accepted()
88
- from localmodels import stack_verify
356
+ if active:
357
+ _demote_stale(active, still_running, keep=planned)
358
+ adopted = [
359
+ model
360
+ for model, (provider, deployed) in active.items()
361
+ if _adopt_record(model, provider, deployed, base_dir)
362
+ ]
363
+ _write_marker(marker, plan["plan_id"] if plan is not None else None, attempt_id, adopted)
364
+ return adopted
89
365
 
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:
366
+
367
+ def sync_stack(
368
+ plan: StackPlan, *, attempt_id: str | None = None, if_initialized: bool = False
369
+ ) -> list[str]:
370
+ """Synchronize library records with an accepted stack plan's live LLM deployments."""
371
+ upgrade()
372
+ if if_initialized and not initialized():
373
+ return []
374
+ return _sync_with_plan(plan, attempt_id, require_active=True)
375
+
376
+
377
+ def _desynced_with_plan(plan: StackPlan) -> bool:
378
+ """Whether an accepted plan's live LLM deployments disagree with the library's records."""
379
+ active = _active_stack_llms(plan)
380
+ if not active:
381
+ return False
382
+ planned = _planned_stack_llms(plan)
383
+ for record in library_state.records():
384
+ if record["id"] not in planned and _is_stack_record(record):
385
+ return True
386
+ for model, (provider, deployed) in active.items():
387
+ if library_state.read_job(model) is not None:
388
+ continue
389
+ existing = library_state.load(model)
390
+ reg = existing.get("registration") if existing is not None else None
391
+ out_of_step = (
392
+ existing is None
393
+ or existing["state"] != "loaded"
394
+ or reg is None
395
+ or reg.get("provider") != provider
396
+ or existing["plan"]["service"]["port"] != deployed["service"]["port"]
397
+ or not existing.get("converted")
398
+ )
399
+ if out_of_step and library_status.answering(str(deployed["endpoint"]["base_url"])):
400
+ return True
401
+ return False
402
+
403
+
404
+ def _needs_resync(
405
+ marker: dict[str, Any] | None,
406
+ plan: StackPlan,
407
+ attempt_id: str | None,
408
+ finished_at: str | None,
409
+ ) -> bool:
410
+ if marker is None or marker.get("plan_id") != plan["plan_id"]:
411
+ return True
412
+ saved_attempt = marker.get("attempt_id")
413
+ if saved_attempt is not None and attempt_id is not None and saved_attempt != attempt_id:
414
+ return True
415
+ if saved_attempt is None and _is_newer(finished_at, marker.get("converted_at")):
416
+ return True
417
+ return _desynced_with_plan(plan)
418
+
419
+
420
+ def _bifrost_provider_matches(provider_doc: object, base_url: str, served_model: str) -> bool:
421
+ if not isinstance(provider_doc, dict):
422
+ return False
423
+ net = provider_doc.get("network_config")
424
+ if not isinstance(net, dict) or net.get("base_url") != gateway_bifrost.origin(base_url):
425
+ return False
426
+ keys = provider_doc.get("keys")
427
+ if not isinstance(keys, list):
428
+ return False
429
+ return any(
430
+ isinstance(key, dict)
431
+ and isinstance(key.get("models"), list)
432
+ and served_model in key["models"]
433
+ for key in keys
434
+ )
435
+
436
+
437
+ def _record_endpoint(record: Record) -> tuple[str, str] | None:
438
+ plan = record.get("plan")
439
+ if not isinstance(plan, dict):
440
+ return None
441
+ endpoint = plan.get("endpoint")
442
+ if not isinstance(endpoint, dict) or not endpoint.get("base_url") or not endpoint.get("model"):
443
+ return None
444
+ return str(endpoint["base_url"]), str(endpoint["model"])
445
+
446
+
447
+ def _bifrost_candidates() -> list[tuple[str, Plan]]:
448
+ """Candidate ``(library_id, plan)`` pairs: live deployment records first, then library records."""
449
+ found: list[tuple[str, Plan]] = []
450
+ seen: set[tuple[str, str]] = set()
451
+ for dep in hosts.records(hosts.LOCAL_ID):
452
+ if not dep.get("ok"):
453
+ continue
454
+ plan = dep["plan"]
455
+ spec = plan["model"]
456
+ model = library_id(spec["id"], spec["quant"])
457
+ key = (model, str(plan["endpoint"]["base_url"]))
458
+ if key not in seen:
459
+ seen.add(key)
460
+ found.append((model, plan))
461
+ for record in library_state.records():
462
+ ep = _record_endpoint(record)
463
+ if ep is None:
464
+ continue
465
+ key = (record["id"], ep[0])
466
+ if key not in seen:
467
+ seen.add(key)
468
+ found.append((record["id"], record["plan"]))
469
+ return found
470
+
471
+
472
+ def _reconcile_live_bifrost() -> list[str]:
473
+ """Recover a live Quick Install LLM routed by Bifrost when no newer stack run was seen."""
474
+ instance = library_gateway.ensure_instance(None)
475
+ if instance is None:
476
+ return []
477
+ providers = gateway_bifrost.read_config(Path(instance["app_dir"])).get("providers")
478
+ if not isinstance(providers, dict):
479
+ return []
480
+ stack_providers = {pid: pdoc for pid in STACK_LLMS.values() if (pdoc := providers.get(pid))}
481
+ if not stack_providers:
482
+ return []
483
+ records = {r["id"]: r for r in library_state.records()}
484
+ candidates = _bifrost_candidates()
485
+ recovered: dict[str, tuple[str, Plan]] = {}
486
+ for pid, pdoc in stack_providers.items():
487
+ if any(
488
+ r["state"] == "loaded"
489
+ and (reg := r.get("registration")) is not None
490
+ and reg.get("provider") == pid
491
+ and (ep := _record_endpoint(r)) is not None
492
+ and _bifrost_provider_matches(pdoc, ep[0], ep[1])
493
+ for r in records.values()
494
+ ):
495
+ continue
496
+ for model, plan in candidates:
497
+ if library_state.read_job(model) is not None:
100
498
  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
- },
499
+ url, served = str(plan["endpoint"]["base_url"]), str(plan["endpoint"]["model"])
500
+ if _bifrost_provider_matches(pdoc, url, served) and library_status.answering(url):
501
+ recovered[model] = (pid, plan)
502
+ break
503
+ if not recovered:
504
+ return []
505
+ taken_providers = frozenset(pid for pid, _ in recovered.values())
506
+ still_running = _stale_still_running(recovered, providers=taken_providers)
507
+ adopted: list[str] = []
508
+ with library_state.locked():
509
+ live_recovered = {
510
+ model: pair
511
+ for model, pair in recovered.items()
512
+ if library_state.read_job(model) is None
513
+ }
514
+ if not live_recovered:
515
+ return []
516
+ _demote_stale(
517
+ live_recovered,
518
+ still_running,
519
+ providers=frozenset(pid for pid, _ in live_recovered.values()),
131
520
  )
521
+ for model, (pid, plan) in live_recovered.items():
522
+ if _adopt_record(model, pid, plan, None):
523
+ adopted.append(model)
132
524
  return adopted
525
+
526
+
527
+ def _stamp_attempt(marker: Path, attempt_id: str) -> None:
528
+ with library_state.locked():
529
+ current = _read_marker(marker)
530
+ if current is not None and current.get("attempt_id") is None:
531
+ current["attempt_id"] = attempt_id
532
+ hosts.save_private(marker, current)
533
+
534
+
535
+ def convert_once() -> list[str]:
536
+ """Adopt the accepted Quick Install stack's LLMs and re-sync when a newer stack apply ran.
537
+
538
+ Every library command calls it first, which also upgrades records an earlier version saved.
539
+ """
540
+ upgrade()
541
+ marker = library_state.root() / MARKER
542
+ if not marker.is_file():
543
+ accepted = _latest_accepted_run()
544
+ plan: StackPlan | None = None
545
+ attempt_id: str | None = None
546
+ if accepted is not None:
547
+ plan, attempt_id, _ = accepted
548
+ elif not hosts.stack_runs():
549
+ plan = stack_up.accepted()
550
+ adopted = _sync_with_plan(plan, attempt_id)
551
+ return adopted or _reconcile_live_bifrost()
552
+ marker_doc = _read_marker(marker)
553
+ if hosts.stack_runs():
554
+ accepted = _latest_accepted_run()
555
+ if accepted is not None:
556
+ plan, attempt_id, finished_at = accepted
557
+ if _needs_resync(marker_doc, plan, attempt_id, finished_at):
558
+ if synced := _sync_with_plan(plan, attempt_id, require_active=True):
559
+ return synced
560
+ elif (
561
+ marker_doc is not None
562
+ and marker_doc.get("attempt_id") is None
563
+ and attempt_id is not None
564
+ ):
565
+ _stamp_attempt(marker, attempt_id)
566
+ return _reconcile_live_bifrost()
@@ -33,6 +33,8 @@ from localmodels import (
33
33
  harness_probe,
34
34
  hosts,
35
35
  library_state,
36
+ runtime_io,
37
+ vision,
36
38
  )
37
39
  from localmodels import catalog as cat
38
40
  from localmodels.library_model import LibraryError, display_name, split_id
@@ -84,7 +86,7 @@ def _fail(detail: str) -> LibraryError:
84
86
  # ---------------------------------------------------------------------------- Bifrost
85
87
 
86
88
 
87
- def _install(facts: HostFacts) -> hosts.OwnedBifrost:
89
+ def _install(facts: HostFacts, event: runtime_io.Event = lambda _: None) -> hosts.OwnedBifrost:
88
90
  """This tool's Bifrost where none is recorded: the pinned binary, its record, an empty
89
91
  config with management authentication, then the instance itself."""
90
92
  addr = harness.bifrost_addr()
@@ -105,8 +107,9 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
105
107
  tools = Path(os.path.expanduser(tools_root))
106
108
  binary = next(a for a in actions if a["tool"] == "bifrost")
107
109
  if binary["action"] == "install":
108
- made = gateway_bifrost.install_binary(tools, binary, lambda _line: None)
109
- fetched = [str(tools / ".archives" / a["name"]) for a in binary["artifacts"]]
110
+ harness.own_downloads(tools, binary["artifacts"])
111
+ made = gateway_bifrost.install_binary(tools, binary, lambda _line: None, event)
112
+ fetched = [f for a in binary["artifacts"] for f in harness.archive_files(tools, a)]
110
113
 
111
114
  def own(doc: hosts.Owned) -> None:
112
115
  if made:
@@ -114,9 +117,7 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
114
117
  [*doc["tools"], {"path": made, "sha256": harness.digest(made)}],
115
118
  key=lambda t: t["path"],
116
119
  )
117
- doc["archives"] = sorted(
118
- set(doc["archives"]) | {p + s for p in fetched for s in ("", ".sha256")}
119
- )
120
+ doc["archives"] = sorted(set(doc["archives"]) | set(fetched))
120
121
 
121
122
  hosts.update_owned(own)
122
123
  gateway_bifrost.ensure(plan)
@@ -141,11 +142,14 @@ def _install(facts: HostFacts) -> hosts.OwnedBifrost:
141
142
  return record
142
143
 
143
144
 
144
- def ensure_instance(facts: HostFacts | None) -> hosts.OwnedBifrost | None:
145
- """Return this tool's Bifrost record, installing it first when ``facts`` are supplied."""
145
+ def ensure_instance(
146
+ facts: HostFacts | None, event: runtime_io.Event = lambda _: None
147
+ ) -> hosts.OwnedBifrost | None:
148
+ """Return this tool's Bifrost record, installing it first when ``facts`` are supplied;
149
+ ``event`` receives the binary's download events."""
146
150
  record = hosts.load_owned()["gateway"].get("bifrost")
147
151
  if record is None and facts is not None:
148
- record = _install(facts)
152
+ record = _install(facts, event)
149
153
  return record
150
154
 
151
155
 
@@ -376,6 +380,19 @@ def _pi_free(provider: str) -> None:
376
380
  raise _fail(f"pi already has a provider {provider} this tool did not add")
377
381
 
378
382
 
383
+ def model_facts(model: str, entry: cat.CatalogEntry, plan: Plan) -> bifrost_models.LlmFacts:
384
+ """The LLM facts pi's models.json needs for a library deployment plan."""
385
+ levels = list(entry.reasoning_efforts or cat.EFFORT_LEVELS)
386
+ context = int(str(plan["launch"].get("window") or 0)) or bifrost_models.DEFAULT_CONTEXT
387
+ return {
388
+ "display": display_name(entry.display_name, split_id(model)[1]),
389
+ "context": context,
390
+ "efforts": levels,
391
+ "defaultEffort": bifrost_models.default_effort(levels),
392
+ "vision": vision.reads_pictures(plan["launch"]),
393
+ }
394
+
395
+
379
396
  def _register(
380
397
  model: str,
381
398
  entry: cat.CatalogEntry,
@@ -416,13 +433,7 @@ def _register(
416
433
  try:
417
434
  if listed_as not in bifrost_models.listed(record["addr"]):
418
435
  raise _fail(f"Bifrost does not list {listed_as}")
419
- levels = list(entry.reasoning_efforts or cat.EFFORT_LEVELS)
420
- facts_: bifrost_models.LlmFacts = {
421
- "display": display_name(entry.display_name, split_id(model)[1]),
422
- "context": context or bifrost_models.DEFAULT_CONTEXT,
423
- "efforts": levels,
424
- "defaultEffort": bifrost_models.default_effort(levels),
425
- }
436
+ facts_ = model_facts(model, entry, plan)
426
437
  base = f"http://{record['addr']}"
427
438
  pi_entry = bifrost_models.pi_provider(facts_, gateway_model, base)["models"][0]
428
439
  if not shared: # the stack's own pi entry already names localmodels-agent