@simplexai/localmodels-linux-arm64 0.1.0-dev.62 → 0.1.0-dev.63

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 (57) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +56 -54
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/bifrost_checks.py +19 -13
  5. package/modules/localmodels/bifrost_clients.py +38 -36
  6. package/modules/localmodels/bifrost_config.py +19 -6
  7. package/modules/localmodels/bifrost_log.py +3 -3
  8. package/modules/localmodels/bifrost_models.py +9 -8
  9. package/modules/localmodels/bifrost_pi.py +27 -72
  10. package/modules/localmodels/catalog.json +51 -58
  11. package/modules/localmodels/custom_hub.py +10 -1
  12. package/modules/localmodels/custom_hub_http.py +14 -3
  13. package/modules/localmodels/debug_mode.py +3 -3
  14. package/modules/localmodels/gateway.py +56 -55
  15. package/modules/localmodels/gateway_bifrost.py +70 -83
  16. package/modules/localmodels/gateway_clients.py +33 -116
  17. package/modules/localmodels/gateway_home.py +5 -5
  18. package/modules/localmodels/gateway_keys.py +8 -6
  19. package/modules/localmodels/gateway_probe.py +4 -4
  20. package/modules/localmodels/gateway_server.py +4 -4
  21. package/modules/localmodels/gateway_speed.py +2 -2
  22. package/modules/localmodels/harness.py +185 -401
  23. package/modules/localmodels/harness_core.py +409 -0
  24. package/modules/localmodels/harness_gateway.py +75 -73
  25. package/modules/localmodels/harness_probe.py +19 -216
  26. package/modules/localmodels/library_custom.py +51 -16
  27. package/modules/localmodels/library_elastic.py +1 -1
  28. package/modules/localmodels/library_gateway.py +59 -176
  29. package/modules/localmodels/library_model.py +23 -0
  30. package/modules/localmodels/library_pricing.py +2 -2
  31. package/modules/localmodels/library_serve.py +5 -3
  32. package/modules/localmodels/library_smoke.py +33 -21
  33. package/modules/localmodels/library_status.py +330 -2
  34. package/modules/localmodels/llm_rank.py +14 -5
  35. package/modules/localmodels/magpie_setup.py +5 -4
  36. package/modules/localmodels/magpie_windows.py +1 -1
  37. package/modules/localmodels/pi_profile.py +384 -0
  38. package/modules/localmodels/process_identity.py +3 -3
  39. package/modules/localmodels/runtime_cli.py +32 -46
  40. package/modules/localmodels/runtime_pi.py +1 -1
  41. package/modules/localmodels/source_byok.py +9 -16
  42. package/modules/localmodels/stack_binding.py +9 -7
  43. package/modules/localmodels/stack_clients.py +137 -21
  44. package/modules/localmodels/stack_doctor.py +6 -3
  45. package/modules/localmodels/stack_hardware.py +18 -0
  46. package/modules/localmodels/stack_lifecycle.py +3 -2
  47. package/modules/localmodels/stack_remove.py +2 -1
  48. package/modules/localmodels/stack_verify.py +2 -2
  49. package/modules/localmodels/stack_view_events.py +2 -2
  50. package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/METADATA +1 -1
  51. package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/RECORD +53 -51
  52. package/package.json +1 -1
  53. package/tool.json +1 -1
  54. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/WHEEL +0 -0
  55. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/entry_points.txt +0 -0
  56. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/NOTICE +0 -0
  57. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev63.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -24,12 +24,16 @@ from typing import Any
24
24
 
25
25
  from localmodels import (
26
26
  bifrost_admin,
27
+ bifrost_clients,
27
28
  bifrost_config,
28
29
  bifrost_log,
29
30
  bifrost_models,
31
+ bifrost_pi,
32
+ gateway,
30
33
  gateway_bifrost,
31
34
  gateway_home,
32
- harness,
35
+ harness_cleanup,
36
+ harness_core,
33
37
  harness_probe,
34
38
  hosts,
35
39
  library_state,
@@ -37,6 +41,7 @@ from localmodels import (
37
41
  vision,
38
42
  )
39
43
  from localmodels import catalog as cat
44
+ from localmodels import pi_profile as pi_store
40
45
  from localmodels.library_model import LibraryError, display_name, split_id
41
46
  from localmodels.library_state import Registration
42
47
  from localmodels.probe import HostFacts
@@ -63,10 +68,7 @@ def provider_id(model: str) -> str:
63
68
  def pi_profile() -> Path:
64
69
  """pi's directory: the one the daemon gives pi (PI_CODING_AGENT_DIR), else the stack's
65
70
  private client context that ``setup binding`` hands to Linger."""
66
- given = os.environ.get("PI_CODING_AGENT_DIR")
67
- if given:
68
- return Path(given).expanduser()
69
- return Path(harness_probe.client_environment(hosts.tools_dir())["PI_CODING_AGENT_DIR"])
71
+ return pi_store.library_pi_dir()
70
72
 
71
73
 
72
74
  def _gateway_error(exc: Exception) -> LibraryError:
@@ -89,7 +91,7 @@ def _fail(detail: str) -> LibraryError:
89
91
  def _install(facts: HostFacts, event: runtime_io.Event = lambda _: None) -> hosts.OwnedBifrost:
90
92
  """This tool's Bifrost where none is recorded: the pinned binary, its record, an empty
91
93
  config with management authentication, then the instance itself."""
92
- addr = harness.bifrost_addr()
94
+ addr = harness_core.bifrost_addr()
93
95
  state: Any = {
94
96
  "bifrost_addr": addr,
95
97
  "bifrost_listeners": sorted(harness_probe.listener_uids(addr)),
@@ -98,7 +100,7 @@ def _install(facts: HostFacts, event: runtime_io.Event = lambda _: None) -> host
98
100
  systemd = facts["service_manager"]["kind"] == "systemd-user"
99
101
  tools_root = hosts.tools_dir()
100
102
  actions, _ = gateway_bifrost.plan_tools(state, platform, facts["arch"], systemd, tools_root)
101
- plan: harness.ToolPlan = {
103
+ plan: harness_core.ToolPlan = {
102
104
  "tools_dir": tools_root,
103
105
  "tools": actions,
104
106
  "download_bytes": 0,
@@ -107,14 +109,14 @@ def _install(facts: HostFacts, event: runtime_io.Event = lambda _: None) -> host
107
109
  tools = Path(os.path.expanduser(tools_root))
108
110
  binary = next(a for a in actions if a["tool"] == "bifrost")
109
111
  if binary["action"] == "install":
110
- harness.own_downloads(tools, binary["artifacts"])
112
+ harness_core.own_downloads(tools, binary["artifacts"])
111
113
  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)]
114
+ fetched = [f for a in binary["artifacts"] for f in harness_core.archive_files(tools, a)]
113
115
 
114
116
  def own(doc: hosts.Owned) -> None:
115
117
  if made:
116
118
  doc["tools"] = sorted(
117
- [*doc["tools"], {"path": made, "sha256": harness.digest(made)}],
119
+ [*doc["tools"], {"path": made, "sha256": harness_cleanup.digest(made)}],
118
120
  key=lambda t: t["path"],
119
121
  )
120
122
  doc["archives"] = sorted(set(doc["archives"]) | set(fetched))
@@ -136,7 +138,7 @@ def _install(facts: HostFacts, event: runtime_io.Event = lambda _: None) -> host
136
138
  }
137
139
  config = gateway_bifrost.render_config({}, governance, app)
138
140
  config["framework"] = bifrost_config.framework(app)
139
- gateway_bifrost._write_config(
141
+ gateway_bifrost.write_config(
140
142
  app, config, {bifrost_config.DATASHEET: {}, bifrost_config.PARAMETERS: {}}
141
143
  )
142
144
  return record
@@ -163,20 +165,20 @@ def read_sheet(app: Path) -> dict[str, Any]:
163
165
 
164
166
 
165
167
  def _is_healthy(record: hosts.OwnedBifrost) -> bool:
166
- return gateway_bifrost._healthy_owned(record)
168
+ return gateway_bifrost.healthy_owned(record)
167
169
 
168
170
 
169
171
  def _stop_for_store_change(record: hosts.OwnedBifrost, app: Path) -> None:
170
172
  # A change drops the config store, which Windows cannot delete while Bifrost holds it
171
173
  # open (WinError 32 on unload, homewin): stop it first; it restarts on the change.
172
174
  if STOP_BEFORE_CONFIG_CHANGE and record["how"] != "unit":
173
- gateway_bifrost._stop_serve(app)
175
+ gateway_bifrost.stop_serve(app)
174
176
 
175
177
 
176
178
  def _start_and_await(record: hosts.OwnedBifrost, app: Path, *, restart: bool) -> None:
177
179
  log_offset = bifrost_log.log_size(app)
178
- gateway_bifrost._start(record, restart=restart)
179
- gateway_bifrost._await(record["addr"], record=record, log_offset=log_offset)
180
+ gateway_bifrost.start(record, restart=restart)
181
+ gateway_bifrost.await_ready(record["addr"], record=record, log_offset=log_offset)
180
182
 
181
183
 
182
184
  def _reconcile_store_cold(record: hosts.OwnedBifrost, config: dict[str, Any]) -> None:
@@ -251,7 +253,7 @@ def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict
251
253
  if config.get("providers") and bifrost_config.differs(app, config, params):
252
254
  before = gateway_bifrost.read_config(app)
253
255
  before_sheet = read_sheet(app)
254
- if gateway_bifrost._healthy_owned(record) and bifrost_admin.can_hot_reload(before, config):
256
+ if gateway_bifrost.healthy_owned(record) and bifrost_admin.can_hot_reload(before, config):
255
257
  try:
256
258
  bifrost_admin.sync_live(
257
259
  record,
@@ -265,7 +267,7 @@ def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict
265
267
  pass # fall back to cold restart so config.json and config.db converge cleanly
266
268
  if bifrost_config.differs(app, config, params):
267
269
  _stop_for_store_change(record, app)
268
- changed = gateway_bifrost._write_config(app, config, params)
270
+ changed = gateway_bifrost.write_config(app, config, params)
269
271
  if not config.get("providers"):
270
272
  _stop(record)
271
273
  return
@@ -278,10 +280,10 @@ def _stop(record: hosts.OwnedBifrost) -> None:
278
280
  an empty gateway does not come back at login) or its process identity receipt."""
279
281
  if record["how"] == "unit":
280
282
  name = gateway_bifrost.unit(record)
281
- if gateway_bifrost._systemctl("disable", "--now", f"{name}.service").returncode != 0:
283
+ if gateway_bifrost.systemctl("disable", "--now", f"{name}.service").returncode != 0:
282
284
  raise _fail(f"stopping {name} failed")
283
285
  return
284
- gateway_bifrost._stop_serve(Path(record["app_dir"]))
286
+ gateway_bifrost.stop_serve(Path(record["app_dir"]))
285
287
 
286
288
 
287
289
  def _provider(base_url: str, model: str, key: str, pid: str) -> dict[str, Any]:
@@ -295,70 +297,24 @@ def _provider(base_url: str, model: str, key: str, pid: str) -> dict[str, Any]:
295
297
  # ---------------------------------------------------------------------------- pi
296
298
 
297
299
 
298
- def _read(path: Path) -> dict[str, Any]:
299
- try:
300
- value = json.loads(path.read_text(encoding="utf-8"))
301
- except FileNotFoundError:
302
- return {}
303
- except (OSError, ValueError) as exc:
304
- raise _fail(f"cannot read {path.name}: {exc}") from None
305
- if not isinstance(value, dict):
306
- raise _fail(f"{path.name} is not a JSON object; left as is")
307
- return value
308
-
309
-
310
- def _write(path: Path, value: dict[str, Any]) -> None:
311
- path.parent.mkdir(parents=True, exist_ok=True)
312
- tmp = path.with_name(path.name + ".tmp")
313
- tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
314
- os.replace(tmp, path)
315
-
316
-
317
300
  def _ours_marker(provider: str) -> Path:
318
301
  """Proof that this tool added ``provider`` to pi's models.json."""
319
302
  suffix = "" if provider == PI_PROVIDER else f"-{provider}"
320
303
  return library_state.root() / f"pi-provider{suffix}"
321
304
 
322
305
 
323
- def _pi_provider_doc(base: str, models: list[dict[str, Any]]) -> dict[str, Any]:
324
- return {
325
- "baseUrl": f"{base}/v1",
326
- "api": "openai-completions",
327
- "apiKey": gateway_bifrost.CALLER_KEY,
328
- "models": models,
329
- }
306
+ def _pi_store(profile: Path | None = None) -> pi_store.PiProfileStore:
307
+ return pi_store.PiProfileStore(pi_profile() if profile is None else profile)
330
308
 
331
309
 
332
- def _pi_add(provider: str, entry: dict[str, Any], base: str) -> None:
333
- path = pi_profile() / "models.json"
334
- models = _read(path)
335
- providers = models.setdefault("providers", {})
336
- if not isinstance(providers, dict):
337
- raise _fail("providers in pi's models.json is not an object; left as is")
338
- marker = _ours_marker(provider)
339
- current = providers.get(provider)
340
- if current is not None and not marker.is_file():
341
- raise _fail(f"pi already has a provider {provider} this tool did not add")
342
- marker.parent.mkdir(parents=True, exist_ok=True)
343
- marker.write_text(str(path) + "\n", encoding="utf-8")
344
- kept = [m for m in (current or {}).get("models", []) if m.get("id") != entry["id"]]
345
- providers[provider] = _pi_provider_doc(base, [*kept, entry])
346
- _write(path, models)
347
-
348
-
349
- def _marker_for_other_file(marker: Path, path: Path) -> bool:
350
- """Whether ``marker`` records ownership of a different existing ``models.json``."""
310
+ def pi_add(provider: str, entry: dict[str, Any], base: str) -> None:
311
+ """Add or update a model entry under an owned provider in pi's models.json."""
351
312
  try:
352
- recorded = marker.read_text(encoding="utf-8").strip()
353
- except OSError:
354
- return False
355
- if not recorded:
356
- return False
357
- other = Path(recorded)
358
- try:
359
- return other.resolve() != path.resolve() and other.is_file()
360
- except OSError:
361
- return False
313
+ _pi_store().upsert_provider_model(
314
+ provider, entry, base, gateway_bifrost.CALLER_KEY, marker=_ours_marker(provider)
315
+ )
316
+ except pi_store.PiProfileError as exc:
317
+ raise _fail(str(exc)) from None
362
318
 
363
319
 
364
320
  def _agent_target(config: dict[str, Any]) -> str | None:
@@ -377,43 +333,12 @@ def _pi_sync_shared(
377
333
  ) -> None:
378
334
  """Sync ``contextWindow``/``maxTokens`` on an owned pi provider entry without changing
379
335
  stack ownership or clobbering a user-defined provider (different ``baseUrl``)."""
380
- if context <= 0:
381
- return
382
- path = pi_profile() / "models.json"
383
336
  try:
384
- models = _read(path)
385
- except LibraryError:
386
- if entry is not None:
387
- raise
388
- return
389
- providers = models.setdefault("providers", {})
390
- if not isinstance(providers, dict):
391
- if entry is not None:
392
- raise _fail("providers in pi's models.json is not an object; left as is")
393
- return
394
- current = providers.get(provider)
395
- if current is None:
396
- if entry is not None:
397
- providers[provider] = _pi_provider_doc(base, [entry])
398
- _write(path, models)
399
- return
400
- if not isinstance(current, dict) or not str(current.get("baseUrl", "")).startswith(f"{base}/"):
401
- return
402
- items = current.get("models")
403
- if not isinstance(items, list):
404
- return
405
- max_tokens = min(32768, max(4096, context // 4))
406
- matched = [m for m in items if isinstance(m, dict) and m.get("id") == model_id]
407
- changed = False
408
- for item in matched:
409
- if item.get("contextWindow") != context or item.get("maxTokens") != max_tokens:
410
- item["contextWindow"], item["maxTokens"] = context, max_tokens
411
- changed = True
412
- if not matched and entry is not None:
413
- items.append(entry)
414
- changed = True
415
- if changed:
416
- _write(path, models)
337
+ _pi_store().sync_shared_model(
338
+ provider, model_id, context, base, gateway_bifrost.CALLER_KEY, entry=entry
339
+ )
340
+ except pi_store.PiProfileError as exc:
341
+ raise _fail(str(exc)) from None
417
342
 
418
343
 
419
344
  def _sheet_context(sheet: dict[str, Any], provider: str) -> int | None:
@@ -429,26 +354,12 @@ def _sheet_context(sheet: dict[str, Any], provider: str) -> int | None:
429
354
  return None
430
355
 
431
356
 
432
- def _pi_drop(provider: str, model_id: str) -> None:
433
- marker = _ours_marker(provider)
434
- if not marker.is_file():
435
- return
436
- path = pi_profile() / "models.json"
437
- models = _read(path)
438
- providers = models.get("providers")
439
- current = providers.get(provider) if isinstance(providers, dict) else None
440
- if not isinstance(providers, dict) or not isinstance(current, dict):
441
- if not _marker_for_other_file(marker, path):
442
- marker.unlink(missing_ok=True)
443
- return
444
- kept = [m for m in current.get("models", []) if m.get("id") != model_id]
445
- if kept:
446
- current["models"] = kept
447
- else:
448
- del providers[provider]
449
- _write(path, models) # committed first: a failed write keeps the proof of ownership
450
- if not kept:
451
- marker.unlink(missing_ok=True)
357
+ def pi_drop(provider: str, model_id: str) -> None:
358
+ """Remove a model entry from an owned provider in pi's models.json."""
359
+ try:
360
+ _pi_store().drop_provider_model(provider, model_id, marker=_ours_marker(provider))
361
+ except pi_store.PiProfileError as exc:
362
+ raise _fail(str(exc)) from None
452
363
 
453
364
 
454
365
  # ---------------------------------------------------------------------------- the model
@@ -499,7 +410,7 @@ def _agent_rule(provider: str, served: str) -> dict[str, Any]:
499
410
  }
500
411
 
501
412
 
502
- STACK_PROVIDERS = (harness.LLM_PROVIDER, gateway_bifrost.FAST_PROVIDER)
413
+ STACK_PROVIDERS = (harness_core.LLM_PROVIDER, gateway_bifrost.FAST_PROVIDER)
503
414
 
504
415
 
505
416
  def _route_agent(config: dict[str, Any]) -> None:
@@ -553,9 +464,10 @@ def planned(model: str, plan: Plan, *, stack_provider: str | None = None) -> Reg
553
464
 
554
465
  def _pi_free(provider: str) -> None:
555
466
  """Refuse, before anything changes, a pi provider of that name this tool did not add."""
556
- current = _read(pi_profile() / "models.json").get("providers")
557
- if isinstance(current, dict) and provider in current and not _ours_marker(provider).is_file():
558
- raise _fail(f"pi already has a provider {provider} this tool did not add")
467
+ try:
468
+ _pi_store().ensure_provider_free(provider, marker=_ours_marker(provider))
469
+ except pi_store.PiProfileError as exc:
470
+ raise _fail(str(exc)) from None
559
471
 
560
472
 
561
473
  def model_facts(model: str, entry: cat.CatalogEntry, plan: Plan) -> bifrost_models.LlmFacts:
@@ -571,19 +483,6 @@ def model_facts(model: str, entry: cat.CatalogEntry, plan: Plan) -> bifrost_mode
571
483
  }
572
484
 
573
485
 
574
- def _pi_drop_magpie_provider(profile: Path) -> None:
575
- """Remove a dead legacy ``magpie`` provider from ``models.json`` in our private profile."""
576
- path = profile / "models.json"
577
- try:
578
- models = _read(path)
579
- except LibraryError:
580
- return
581
- providers = models.get("providers")
582
- if isinstance(providers, dict) and "magpie" in providers:
583
- del providers["magpie"]
584
- _write(path, models)
585
-
586
-
587
486
  def _clear_legacy_magpie_pi_record(tools_dir: str) -> None:
588
487
  """Drop an orphaned ``magpie/...`` pi ownership entry when transitioning to Bifrost."""
589
488
 
@@ -604,8 +503,6 @@ def _retire_legacy_magpie(tools_dir: str) -> bool:
604
503
  is unavailable, ``leave_magpie`` cannot invoke the Magpie CLI; we still proceed so Bifrost
605
504
  registration and pi recovery succeed rather than leaving the user stuck on a dead port.
606
505
  """
607
- from localmodels import bifrost_clients, gateway
608
-
609
506
  doc = hosts.load_owned(tools_dir)
610
507
  had_magpie = bool(
611
508
  bifrost_clients.magpie_wired(doc)
@@ -616,7 +513,7 @@ def _retire_legacy_magpie(tools_dir: str) -> bool:
616
513
  return False
617
514
  try:
618
515
  gateway.leave_magpie(tools_dir)
619
- except (harness.HarnessError, OSError, ValueError):
516
+ except (harness_core.HarnessError, OSError, ValueError):
620
517
  _clear_legacy_magpie_pi_record(tools_dir)
621
518
  return True
622
519
 
@@ -632,24 +529,12 @@ def _sync_pi_default(
632
529
  """Keep pi's ``settings.json`` off a dead legacy ``magpie`` default (and restore the
633
530
  Quick Install default when an adopted stack LLM is reloaded after ``unpoint_pi``).
634
531
  Never overwrites a user-chosen non-magpie default."""
635
- settings_path = profile / "settings.json"
636
- try:
637
- settings = _read(settings_path)
638
- except LibraryError:
639
- return
640
- current_provider = settings.get("defaultProvider")
641
- current_model = settings.get("defaultModel")
642
- was_magpie = current_provider == "magpie" or (
643
- not current_provider
644
- and isinstance(current_model, str)
645
- and current_model.startswith("magpie/")
532
+ _pi_store(profile).sync_default_off_magpie(
533
+ pi_provider,
534
+ gateway_model,
535
+ stack_provider=stack_provider,
536
+ retired_magpie=retired_magpie,
646
537
  )
647
- if was_magpie or (stack_provider is not None and not current_model):
648
- settings["defaultProvider"] = pi_provider
649
- settings["defaultModel"] = gateway_model
650
- _write(settings_path, settings)
651
- if was_magpie or retired_magpie:
652
- _pi_drop_magpie_provider(profile)
653
538
 
654
539
 
655
540
  def reconcile_pi_default(registration: Registration) -> None:
@@ -719,7 +604,7 @@ def _register(
719
604
  base = f"http://{record['addr']}"
720
605
  pi_entry = bifrost_models.pi_provider(facts_, gateway_model, base)["models"][0]
721
606
  if not shared: # the stack's own pi entry already names localmodels-agent
722
- _pi_add(pi_provider, pi_entry, base)
607
+ pi_add(pi_provider, pi_entry, base)
723
608
  elif _agent_target(config) == pid:
724
609
  _pi_sync_shared(pi_provider, gateway_model, facts_["context"], base, entry=pi_entry)
725
610
  _sync_pi_default(
@@ -730,12 +615,12 @@ def _register(
730
615
  retired_magpie=retired_magpie,
731
616
  )
732
617
  except BaseException: # roll the gateway back to what it was before this call
733
- with contextlib.suppress(harness.HarnessError, OSError, ValueError, LibraryError):
618
+ with contextlib.suppress(harness_core.HarnessError, OSError, ValueError, LibraryError):
734
619
  apply_config(record, before, before_sheet)
735
620
  raise
736
621
  except LibraryError:
737
622
  raise
738
- except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
623
+ except (harness_core.HarnessError, OSError, ValueError, KeyError) as exc:
739
624
  raise _gateway_error(exc) from None
740
625
  return added
741
626
 
@@ -745,7 +630,7 @@ def _unregister(registration: Registration) -> None:
745
630
  if registration["kind"] in ("stack", "agent"):
746
631
  _unwire_member(registration)
747
632
  return
748
- _pi_drop(registration.get("pi_provider", PI_PROVIDER), registration["model"])
633
+ pi_drop(registration.get("pi_provider", PI_PROVIDER), registration["model"])
749
634
  record = ensure_instance(None)
750
635
  if record is None:
751
636
  return
@@ -760,7 +645,7 @@ def _unregister(registration: Registration) -> None:
760
645
  prefix = registration["provider"] + "/"
761
646
  sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
762
647
  apply_config(record, config, sheet)
763
- except (harness.HarnessError, OSError, ValueError, KeyError) as exc:
648
+ except (harness_core.HarnessError, OSError, ValueError, KeyError) as exc:
764
649
  raise _gateway_error(exc) from None
765
650
 
766
651
 
@@ -775,8 +660,6 @@ def _unwire_member(registration: Registration) -> None:
775
660
  route moves to the other stack LLM when one is still served. The native clients and pi get
776
661
  back what they had only when the last stack LLM leaves (stack remove's own steps), and the
777
662
  gateway stops only when nothing at all is left for it to serve."""
778
- from localmodels import bifrost_clients, bifrost_pi
779
-
780
663
  record = ensure_instance(None)
781
664
  app = Path(record["app_dir"]) if record else None
782
665
  config = gateway_bifrost.read_config(app) if app else {}
@@ -785,14 +668,14 @@ def _unwire_member(registration: Registration) -> None:
785
668
  providers.pop(registration["provider"], None)
786
669
  if not any(p in providers for p in STACK_PROVIDERS): # the last stack LLM
787
670
  tools_root = hosts.tools_dir()
788
- environment = {**os.environ, **harness_probe.client_environment(tools_root)}
671
+ environment = {**os.environ, **pi_store.client_environment(tools_root)}
789
672
  pi_environment = {**environment, "PI_CODING_AGENT_DIR": str(pi_profile())}
790
673
  checks = bifrost_clients.unwire(tools_root, environment=environment)
791
674
  checks += bifrost_pi.unpoint_pi(tools_root, environment=pi_environment)
792
675
  failed = [c["detail"] for c in checks if not c["ok"]]
793
676
  if failed:
794
677
  raise _fail("; ".join(failed))
795
- _pi_drop(gateway_bifrost.PI_PROVIDER, gateway_bifrost.AGENT_MODEL)
678
+ pi_drop(gateway_bifrost.PI_PROVIDER, gateway_bifrost.AGENT_MODEL)
796
679
  if record is None or app is None:
797
680
  return
798
681
  _route_agent(config)
@@ -145,9 +145,31 @@ class Host(_Host, total=False):
145
145
  gpu_in_use_bytes: int
146
146
  wired_headroom_bytes: int
147
147
  inactive_anon_bytes: int
148
+ models_dir: str
149
+ models_dir_exists: bool
148
150
  supported_formats: list[str]
149
151
 
150
152
 
153
+ StorageFileRole = Literal["weights", "mmproj", "other"]
154
+
155
+
156
+ class StorageFile(TypedDict):
157
+ path: str
158
+ role: StorageFileRole
159
+ size_bytes: int
160
+ present: bool
161
+ shared: bool
162
+
163
+
164
+ class Storage(TypedDict):
165
+ dir: str
166
+ primary_path: str
167
+ dedicated_dir: bool
168
+ disk_bytes: int
169
+ files_present: bool
170
+ files: list[StorageFile]
171
+
172
+
151
173
  class Holder(TypedDict):
152
174
  kind: Literal["model", "component"]
153
175
  id: str
@@ -367,6 +389,7 @@ class Row(_Row, total=False):
367
389
  origin: ModelOrigin # curated | custom (absent means curated)
368
390
  custom: CustomRowMeta # present on custom hub models only
369
391
  verification: VerificationMeta # present on custom hub models only
392
+ storage: Storage # on-disk file locations; absent when state is absent or no destinations exist
370
393
  error: Problem # failed only
371
394
  note: Note # idle only, when autoload was skipped
372
395
 
@@ -586,8 +586,8 @@ def judge(
586
586
 
587
587
 
588
588
  def base_free(base_dir: str) -> int:
589
- """Free bytes on the filesystem that will hold ``base_dir``."""
590
- path = Path(base_dir).expanduser()
589
+ """Free bytes on the filesystem that will hold ``<base_dir>/models``."""
590
+ path = Path(base_dir).expanduser() / "models"
591
591
  while not path.exists() and path != path.parent:
592
592
  path = path.parent
593
593
  try:
@@ -295,11 +295,13 @@ def _port(facts: HostFacts) -> int:
295
295
  raise LibraryError("ENGINE_START_FAILED", str(exc)) from None
296
296
 
297
297
 
298
- def _start_code(finished: FinishedRecord) -> str:
298
+ def _start_code(finished: FinishedRecord, *, custom: bool = False) -> str:
299
299
  failed = next((s for s in finished["steps"] if not s["ok"]), None)
300
300
  text = " ".join(str(x) for x in (finished.get("error"), failed and failed.get("stderr")) if x)
301
301
  kind, code = classify_failure_text(text)
302
- if kind != "unknown":
302
+ if kind == "oom":
303
+ return code
304
+ if custom and kind != "unknown":
303
305
  return code
304
306
  if failed is not None and failed["step"] == "verify":
305
307
  return "HEALTH_CHECK_FAILED"
@@ -579,7 +581,7 @@ def _start(
579
581
  finished = app.run_deploy(hosts.LOCAL_ID, plan, on_event=seen)
580
582
  if finished["ok"]:
581
583
  break
582
- code = _start_code(finished)
584
+ code = _start_code(finished, custom=record.get("custom") is not None)
583
585
  error = LibraryError(code, str(finished.get("error") or "start failed"))
584
586
  try:
585
587
  _remove_service(plan, run)
@@ -208,6 +208,14 @@ def _run_attempt(
208
208
  _cleanup_smoke_plan(smoke_plan)
209
209
 
210
210
 
211
+ def _restore_verification(model_id: str, prior: VerificationRecord | None) -> None:
212
+ with library_state.locked():
213
+ current = library_state.load(model_id)
214
+ if current is not None:
215
+ current["verification"] = prior if prior is not None else {"status": "untested"}
216
+ library_state.save(current)
217
+
218
+
211
219
  def smoke_test(model_id: str, base_dir: str, *, ctx: int = 4096) -> Row:
212
220
  """Run an isolated ephemeral smoke-test at ``ctx`` tokens and persist ``verification``."""
213
221
  if isinstance(ctx, bool) or ctx <= 0:
@@ -235,6 +243,7 @@ def smoke_test(model_id: str, base_dir: str, *, ctx: int = 4096) -> Row:
235
243
  library_state.save(record)
236
244
  job = library_state.acquire("smoke_test", model.id, record["pool"], 0, [], port=port)
237
245
 
246
+ library_jobs.cancel_on_sigterm()
238
247
  record_base = record.get("base_dir") or base_dir
239
248
  custom_meta = record.get("custom")
240
249
  use_jinja = (
@@ -243,30 +252,33 @@ def smoke_test(model_id: str, base_dir: str, *, ctx: int = 4096) -> Row:
243
252
  progress(model.id, "smoke_test", 0, 3)
244
253
  with library_state.held([job]):
245
254
  try:
246
- smoke_plan = _build_smoke_plan(
247
- record, facts, record_base, port, ctx, use_jinja=use_jinja
248
- )
249
- finished, server_log = _run_attempt(model.id, smoke_plan)
250
- jinja_fallback = False
251
- if not finished["ok"] and use_jinja:
252
- diag = _diagnostic_text(finished, server_log)
253
- if _is_template_error(diag):
254
- jinja_fallback = True
255
- retry_plan = _build_smoke_plan(
256
- record, facts, record_base, port, ctx, use_jinja=False
257
- )
258
- finished, server_log = _run_attempt(model.id, retry_plan)
255
+ with library_jobs.watch_cancel(job):
256
+ smoke_plan = _build_smoke_plan(
257
+ record, facts, record_base, port, ctx, use_jinja=use_jinja
258
+ )
259
+ finished, server_log = _run_attempt(model.id, smoke_plan)
260
+ jinja_fallback = False
261
+ if not finished["ok"] and use_jinja and not library_state.cancelled(job):
262
+ diag = _diagnostic_text(finished, server_log)
263
+ if _is_template_error(diag):
264
+ jinja_fallback = True
265
+ retry_plan = _build_smoke_plan(
266
+ record, facts, record_base, port, ctx, use_jinja=False
267
+ )
268
+ finished, server_log = _run_attempt(model.id, retry_plan)
269
+ except KeyboardInterrupt:
270
+ _restore_verification(model.id, prior_verification)
271
+ raise LibraryError("CANCELLED", "the smoke test was cancelled") from None
259
272
  except BaseException:
260
- with library_state.locked():
261
- current = library_state.load(model.id)
262
- if current is not None:
263
- if prior_verification is not None:
264
- current["verification"] = prior_verification
265
- else:
266
- current["verification"] = {"status": "untested"}
267
- library_state.save(current)
273
+ _restore_verification(model.id, prior_verification)
274
+ if library_state.cancelled(job):
275
+ raise LibraryError("CANCELLED", "the smoke test was cancelled") from None
268
276
  raise
269
277
 
278
+ if library_state.cancelled(job):
279
+ _restore_verification(model.id, prior_verification)
280
+ raise LibraryError("CANCELLED", "the smoke test was cancelled")
281
+
270
282
  now_iso = plan_envelope.utc_now()
271
283
  if finished["ok"]:
272
284
  progress(model.id, "smoke_test", 3, 3)