@simplexai/localmodels-darwin-x64 0.1.0-dev.58 → 0.1.0-dev.60

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 (113) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +105 -98
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +104 -43
  5. package/modules/localmodels/app.py +1 -1
  6. package/modules/localmodels/apple_sensors.py +431 -0
  7. package/modules/localmodels/bifrost_admin.py +83 -8
  8. package/modules/localmodels/bifrost_checks.py +2 -2
  9. package/modules/localmodels/bifrost_config.py +235 -13
  10. package/modules/localmodels/bifrost_log.py +166 -0
  11. package/modules/localmodels/bifrost_models.py +1 -1
  12. package/modules/localmodels/budget.py +1 -1
  13. package/modules/localmodels/catalog.json +192 -77
  14. package/modules/localmodels/catalog.py +20 -3
  15. package/modules/localmodels/catalog_add.py +42 -11
  16. package/modules/localmodels/custom_hub.py +983 -0
  17. package/modules/localmodels/custom_hub_http.py +579 -0
  18. package/modules/localmodels/custom_probe.py +451 -0
  19. package/modules/localmodels/deploy.py +27 -5
  20. package/modules/localmodels/deploy_steps.py +5 -0
  21. package/modules/localmodels/download-mirrors.json +8 -0
  22. package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
  23. package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
  24. package/modules/localmodels/engines.py +38 -8
  25. package/modules/localmodels/estimator.py +60 -7
  26. package/modules/localmodels/frontend.py +26 -21
  27. package/modules/localmodels/gateway.py +48 -3
  28. package/modules/localmodels/gateway_app_bifrost.py +4 -4
  29. package/modules/localmodels/gateway_bifrost.py +128 -21
  30. package/modules/localmodels/gguf.py +6 -0
  31. package/modules/localmodels/host_sensors.py +704 -0
  32. package/modules/localmodels/hosts.py +99 -12
  33. package/modules/localmodels/library_cli.py +181 -3
  34. package/modules/localmodels/library_convert.py +34 -0
  35. package/modules/localmodels/library_custom.py +831 -0
  36. package/modules/localmodels/library_elastic.py +182 -127
  37. package/modules/localmodels/library_gateway.py +193 -40
  38. package/modules/localmodels/library_jobs.py +92 -18
  39. package/modules/localmodels/library_kept.py +50 -6
  40. package/modules/localmodels/library_model.py +254 -2
  41. package/modules/localmodels/library_pricing.py +97 -8
  42. package/modules/localmodels/library_serve.py +196 -66
  43. package/modules/localmodels/library_smoke.py +315 -0
  44. package/modules/localmodels/library_state.py +81 -2
  45. package/modules/localmodels/library_status.py +144 -8
  46. package/modules/localmodels/metal.py +1 -1
  47. package/modules/localmodels/metal_probe.py +4 -4
  48. package/modules/localmodels/nvml_ctypes.py +431 -0
  49. package/modules/localmodels/plan_envelope.py +18 -7
  50. package/modules/localmodels/process_identity_linux.py +39 -0
  51. package/modules/localmodels/records.py +1 -0
  52. package/modules/localmodels/remote_ops.py +57 -8
  53. package/modules/localmodels/remote_ops_download.py +205 -53
  54. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  55. package/modules/localmodels/remote_ops_ranges.py +2 -5
  56. package/modules/localmodels/remote_ops_service.py +95 -37
  57. package/modules/localmodels/remote_ops_verify.py +22 -5
  58. package/modules/localmodels/runtime-lock.json +19 -19
  59. package/modules/localmodels/runtime_auth.py +4 -1
  60. package/modules/localmodels/service_control.py +32 -1
  61. package/modules/localmodels/service_wiring.py +237 -12
  62. package/modules/localmodels/service_worker.py +6 -2
  63. package/modules/localmodels/services_cli.py +35 -27
  64. package/modules/localmodels/setup_inspection.py +47 -70
  65. package/modules/localmodels/setup_inspection_harness.py +159 -15
  66. package/modules/localmodels/setup_text.py +14 -0
  67. package/modules/localmodels/setup_upgrade.py +1 -1
  68. package/modules/localmodels/source_byok.py +9 -7
  69. package/modules/localmodels/source_byok_probe.py +6 -1
  70. package/modules/localmodels/stack.py +9 -1
  71. package/modules/localmodels/stack_binding.py +3 -35
  72. package/modules/localmodels/stack_cleanup.py +4 -0
  73. package/modules/localmodels/stack_compose.py +18 -2
  74. package/modules/localmodels/stack_lifecycle.py +26 -3
  75. package/modules/localmodels/stack_memory.py +1 -0
  76. package/modules/localmodels/stack_plan.py +6 -2
  77. package/modules/localmodels/stack_ports.py +2 -0
  78. package/modules/localmodels/stack_remove.py +10 -1
  79. package/modules/localmodels/stack_up.py +33 -7
  80. package/modules/localmodels/stack_update.py +3 -1
  81. package/modules/localmodels/stack_view.py +77 -53
  82. package/modules/localmodels/stack_view_demo.py +36 -5
  83. package/modules/localmodels/stack_view_events.py +147 -12
  84. package/modules/localmodels/stack_view_gpu.py +97 -17
  85. package/modules/localmodels/stack_view_llm.py +15 -0
  86. package/modules/localmodels/stack_view_measure.py +4 -1
  87. package/modules/localmodels/stack_view_schema.py +54 -8
  88. package/modules/localmodels/stack_view_serve.py +40 -3
  89. package/modules/localmodels/stack_view_slots.py +89 -10
  90. package/modules/localmodels/stack_view_telemetry.py +163 -0
  91. package/modules/localmodels/stack_view_text.py +5 -2
  92. package/modules/localmodels/stack_view_tick.py +658 -0
  93. package/modules/localmodels/stack_view_words.py +4 -0
  94. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
  95. package/modules/localmodels/suite.py +45 -27
  96. package/modules/localmodels/telemetry_math.py +538 -0
  97. package/modules/localmodels/transport.py +13 -2
  98. package/modules/localmodels/web/view/view.js +1 -1
  99. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/METADATA +1 -1
  100. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/RECORD +102 -95
  101. package/package.json +1 -1
  102. package/tool.json +1 -1
  103. package/modules/localmodels/bifrost_datasheet.py +0 -53
  104. package/modules/localmodels/bifrost_provider.py +0 -88
  105. package/modules/localmodels/bifrost_unit.py +0 -99
  106. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  107. package/modules/localmodels/gateway_switch.py +0 -51
  108. package/modules/localmodels/library_floor.py +0 -78
  109. package/modules/localmodels/service_stop.py +0 -52
  110. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/WHEEL +0 -0
  111. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/entry_points.txt +0 -0
  112. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/NOTICE +0 -0
  113. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev60.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -25,9 +25,8 @@ from typing import Any
25
25
  from localmodels import (
26
26
  bifrost_admin,
27
27
  bifrost_config,
28
- bifrost_datasheet,
28
+ bifrost_log,
29
29
  bifrost_models,
30
- bifrost_unit,
31
30
  gateway_bifrost,
32
31
  gateway_home,
33
32
  harness,
@@ -136,9 +135,9 @@ def _install(facts: HostFacts, event: runtime_io.Event = lambda _: None) -> host
136
135
  }
137
136
  }
138
137
  config = gateway_bifrost.render_config({}, governance, app)
139
- config["framework"] = bifrost_datasheet.framework(app)
138
+ config["framework"] = bifrost_config.framework(app)
140
139
  gateway_bifrost._write_config(
141
- app, config, {bifrost_datasheet.DATASHEET: {}, bifrost_datasheet.PARAMETERS: {}}
140
+ app, config, {bifrost_config.DATASHEET: {}, bifrost_config.PARAMETERS: {}}
142
141
  )
143
142
  return record
144
143
 
@@ -157,12 +156,85 @@ def ensure_instance(
157
156
  def read_sheet(app: Path) -> dict[str, Any]:
158
157
  """Read the current model datasheet of ``app``, or an empty mapping when absent."""
159
158
  try:
160
- value = json.loads((app / bifrost_datasheet.DATASHEET).read_text(encoding="utf-8"))
159
+ value = json.loads((app / bifrost_config.DATASHEET).read_text(encoding="utf-8"))
161
160
  except (OSError, ValueError):
162
161
  return {}
163
162
  return value if isinstance(value, dict) else {}
164
163
 
165
164
 
165
+ def _is_healthy(record: hosts.OwnedBifrost) -> bool:
166
+ return gateway_bifrost._healthy_owned(record)
167
+
168
+
169
+ def _stop_for_store_change(record: hosts.OwnedBifrost, app: Path) -> None:
170
+ # A change drops the config store, which Windows cannot delete while Bifrost holds it
171
+ # open (WinError 32 on unload, homewin): stop it first; it restarts on the change.
172
+ if STOP_BEFORE_CONFIG_CHANGE and record["how"] != "unit":
173
+ gateway_bifrost._stop_serve(app)
174
+
175
+
176
+ def _start_and_await(record: hosts.OwnedBifrost, app: Path, *, restart: bool) -> None:
177
+ 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
+
181
+
182
+ def _reconcile_store_cold(record: hosts.OwnedBifrost, config: dict[str, Any]) -> None:
183
+ """Converge a running Bifrost's derived SQLite store with ``config.json`` via cold restart
184
+ (or stop it when ``config.json`` has no providers left)."""
185
+ app = Path(record["app_dir"])
186
+ if not config.get("providers"):
187
+ _stop(record)
188
+ bifrost_config.clear_store(app)
189
+ return
190
+ _stop_for_store_change(record, app)
191
+ bifrost_config.clear_store(app)
192
+ _start_and_await(record, app, restart=True)
193
+
194
+
195
+ def _cleanup_orphaned_provider(
196
+ record: hosts.OwnedBifrost,
197
+ config: dict[str, Any],
198
+ pid: str,
199
+ *,
200
+ sync_rules: bool = False,
201
+ ) -> None:
202
+ """Remove a provider left in live Bifrost or ``config.db`` by a hot-reload that failed, was
203
+ interrupted, or was killed before ``config.json`` was written."""
204
+ app = Path(record["app_dir"])
205
+ prefix = pid + "/"
206
+ before_sheet = read_sheet(app)
207
+ sheet = {k: v for k, v in before_sheet.items() if not k.startswith(prefix)}
208
+ sheet_pruned = sheet != before_sheet
209
+ params = {bifrost_config.DATASHEET: sheet, bifrost_config.PARAMETERS: {}}
210
+ if _is_healthy(record):
211
+ desired_rules: list[dict[str, Any]] | None = None
212
+ if sync_rules:
213
+ gov = config.get("governance")
214
+ raw_rules = gov.get("routing_rules") if isinstance(gov, dict) else None
215
+ desired_rules = (
216
+ [r for r in raw_rules if isinstance(r, dict)] if isinstance(raw_rules, list) else []
217
+ )
218
+ try:
219
+ removed = bifrost_admin.drop_live_provider(record, pid, desired_rules=desired_rules)
220
+ except bifrost_admin.AdminError:
221
+ if sheet_pruned:
222
+ bifrost_config.write_config(app, config, params, drop_store=False)
223
+ _reconcile_store_cold(record, config)
224
+ return
225
+ if sheet_pruned:
226
+ bifrost_config.write_config(app, config, params, drop_store=False)
227
+ if removed and not config.get("providers"):
228
+ _stop(record)
229
+ bifrost_config.clear_store(app)
230
+ return
231
+ if gateway_bifrost.owned_listener(record):
232
+ _stop(record)
233
+ if sheet_pruned:
234
+ bifrost_config.write_config(app, config, params)
235
+ bifrost_config.clear_store(app)
236
+
237
+
166
238
  def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict[str, Any]) -> None:
167
239
  """Apply updated config and datasheet to the gateway.
168
240
 
@@ -175,7 +247,7 @@ def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict
175
247
  its LLM, decision model or foundation services) serves nobody: it is stopped instead, its
176
248
  record and config kept, and the next load starts it again."""
177
249
  app = Path(record["app_dir"])
178
- params = {bifrost_datasheet.DATASHEET: sheet, bifrost_datasheet.PARAMETERS: {}}
250
+ params = {bifrost_config.DATASHEET: sheet, bifrost_config.PARAMETERS: {}}
179
251
  if config.get("providers") and bifrost_config.differs(app, config, params):
180
252
  before = gateway_bifrost.read_config(app)
181
253
  before_sheet = read_sheet(app)
@@ -191,28 +263,21 @@ def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict
191
263
  return
192
264
  except bifrost_admin.AdminError:
193
265
  pass # fall back to cold restart so config.json and config.db converge cleanly
194
- if (
195
- STOP_BEFORE_CONFIG_CHANGE
196
- and record["how"] != "unit"
197
- and bifrost_config.differs(app, config, params)
198
- ):
199
- # A change drops the config store, which Windows cannot delete while Bifrost holds it
200
- # open (WinError 32 on unload, homewin): stop it first; it restarts on the change.
201
- gateway_bifrost._stop_serve(app)
266
+ if bifrost_config.differs(app, config, params):
267
+ _stop_for_store_change(record, app)
202
268
  changed = gateway_bifrost._write_config(app, config, params)
203
269
  if not config.get("providers"):
204
270
  _stop(record)
205
271
  return
206
- if changed or not gateway_bifrost._healthy_owned(record):
207
- gateway_bifrost._start(record, restart=changed)
208
- gateway_bifrost._await(record["addr"], record=record)
272
+ if changed or not _is_healthy(record):
273
+ _start_and_await(record, app, restart=changed)
209
274
 
210
275
 
211
276
  def _stop(record: hosts.OwnedBifrost) -> None:
212
277
  """Stop the instance through what proves it ours: its systemd --user unit (disabled too, so
213
278
  an empty gateway does not come back at login) or its process identity receipt."""
214
279
  if record["how"] == "unit":
215
- name = bifrost_unit.unit(record)
280
+ name = gateway_bifrost.unit(record)
216
281
  if gateway_bifrost._systemctl("disable", "--now", f"{name}.service").returncode != 0:
217
282
  raise _fail(f"stopping {name} failed")
218
283
  return
@@ -220,9 +285,7 @@ def _stop(record: hosts.OwnedBifrost) -> None:
220
285
 
221
286
 
222
287
  def _provider(base_url: str, model: str, key: str, pid: str) -> dict[str, Any]:
223
- from localmodels import bifrost_provider
224
-
225
- entry = bifrost_provider.render("llm", base_url, model, key, pid)
288
+ entry = bifrost_config.render_provider("llm", base_url, model, key, pid)
226
289
  first = entry["keys"][0]
227
290
  first["models"] = [model] # no alias for the stack's agent group: only this model
228
291
  first.pop("aliases", None)
@@ -257,6 +320,15 @@ def _ours_marker(provider: str) -> Path:
257
320
  return library_state.root() / f"pi-provider{suffix}"
258
321
 
259
322
 
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
+ }
330
+
331
+
260
332
  def _pi_add(provider: str, entry: dict[str, Any], base: str) -> None:
261
333
  path = pi_profile() / "models.json"
262
334
  models = _read(path)
@@ -270,12 +342,7 @@ def _pi_add(provider: str, entry: dict[str, Any], base: str) -> None:
270
342
  marker.parent.mkdir(parents=True, exist_ok=True)
271
343
  marker.write_text(str(path) + "\n", encoding="utf-8")
272
344
  kept = [m for m in (current or {}).get("models", []) if m.get("id") != entry["id"]]
273
- providers[provider] = {
274
- "baseUrl": f"{base}/v1",
275
- "api": "openai-completions",
276
- "apiKey": gateway_bifrost.CALLER_KEY,
277
- "models": [*kept, entry],
278
- }
345
+ providers[provider] = _pi_provider_doc(base, [*kept, entry])
279
346
  _write(path, models)
280
347
 
281
348
 
@@ -294,6 +361,74 @@ def _marker_for_other_file(marker: Path, path: Path) -> bool:
294
361
  return False
295
362
 
296
363
 
364
+ def _agent_target(config: dict[str, Any]) -> str | None:
365
+ rules = (config.get("governance") or {}).get("routing_rules") or []
366
+ agent = next(
367
+ (r for r in rules if isinstance(r, dict) and r.get("id") == gateway_bifrost.AGENT_RULE),
368
+ None,
369
+ )
370
+ targets = (agent or {}).get("targets") or []
371
+ target = targets[0].get("provider") if targets and isinstance(targets[0], dict) else None
372
+ return str(target) if isinstance(target, str) and target else None
373
+
374
+
375
+ def _pi_sync_shared(
376
+ provider: str, model_id: str, context: int, base: str, *, entry: dict[str, Any] | None = None
377
+ ) -> None:
378
+ """Sync ``contextWindow``/``maxTokens`` on an owned pi provider entry without changing
379
+ stack ownership or clobbering a user-defined provider (different ``baseUrl``)."""
380
+ if context <= 0:
381
+ return
382
+ path = pi_profile() / "models.json"
383
+ 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)
417
+
418
+
419
+ def _sheet_context(sheet: dict[str, Any], provider: str) -> int | None:
420
+ prefix = provider + "/"
421
+ for key in (
422
+ f"{prefix}{gateway_bifrost.AGENT_MODEL}",
423
+ *(k for k in sheet if k.startswith(prefix)),
424
+ ):
425
+ doc = sheet.get(key)
426
+ ctx = doc.get("context_length") if isinstance(doc, dict) else None
427
+ if isinstance(ctx, int) and not isinstance(ctx, bool) and ctx > 0:
428
+ return ctx
429
+ return None
430
+
431
+
297
432
  def _pi_drop(provider: str, model_id: str) -> None:
298
433
  marker = _ours_marker(provider)
299
434
  if not marker.is_file():
@@ -360,7 +495,7 @@ def _agent_rule(provider: str, served: str) -> dict[str, Any]:
360
495
  "description": "local agent turns sent to the local LLM",
361
496
  "cel_expression": f"model == '{gateway_bifrost.AGENT_MODEL}'",
362
497
  "targets": [{"provider": provider, "model": served, "weight": 1}],
363
- "priority": 1,
498
+ "priority": bifrost_config.AGENT_RULE_PRIORITY,
364
499
  }
365
500
 
366
501
 
@@ -376,7 +511,7 @@ def _route_agent(config: dict[str, Any]) -> None:
376
511
  rules = [
377
512
  r
378
513
  for r in governance.get("routing_rules") or []
379
- if r.get("id") != gateway_bifrost.COMPLEX_RULE
514
+ if isinstance(r, dict) and r.get("id") != gateway_bifrost.COMPLEX_RULE
380
515
  ]
381
516
  governance.pop("complexity_analyzer_config", None)
382
517
  left = [p for p in STACK_PROVIDERS if p in providers]
@@ -390,6 +525,11 @@ def _route_agent(config: dict[str, Any]) -> None:
390
525
  served = (keys[0].get("models") or [gateway_bifrost.AGENT_MODEL])[0]
391
526
  rules.append(_agent_rule(left[0], served))
392
527
  governance["routing_rules"] = rules
528
+ bifrost_config.sanitize_governance(config)
529
+
530
+
531
+ def _normalize_existing_rules(config: dict[str, Any]) -> None:
532
+ bifrost_config.sanitize_governance(config)
393
533
 
394
534
 
395
535
  def planned(model: str, plan: Plan, *, stack_provider: str | None = None) -> Registration:
@@ -464,7 +604,7 @@ def _retire_legacy_magpie(tools_dir: str) -> bool:
464
604
  is unavailable, ``leave_magpie`` cannot invoke the Magpie CLI; we still proceed so Bifrost
465
605
  registration and pi recovery succeed rather than leaving the user stuck on a dead port.
466
606
  """
467
- from localmodels import bifrost_clients, gateway_switch
607
+ from localmodels import bifrost_clients, gateway
468
608
 
469
609
  doc = hosts.load_owned(tools_dir)
470
610
  had_magpie = bool(
@@ -475,7 +615,7 @@ def _retire_legacy_magpie(tools_dir: str) -> bool:
475
615
  if not had_magpie:
476
616
  return False
477
617
  try:
478
- gateway_switch.leave_magpie(tools_dir)
618
+ gateway.leave_magpie(tools_dir)
479
619
  except (harness.HarnessError, OSError, ValueError):
480
620
  _clear_legacy_magpie_pi_record(tools_dir)
481
621
  return True
@@ -546,8 +686,6 @@ def _register(
546
686
  facts: HostFacts,
547
687
  stack_provider: str | None,
548
688
  ) -> Registration:
549
- from localmodels import bifrost_provider
550
-
551
689
  added = planned(model, plan, stack_provider=stack_provider)
552
690
  pid, gateway_model, pi_provider = added["provider"], added["model"], added["pi_provider"]
553
691
  name = str(plan["endpoint"]["model"])
@@ -563,17 +701,15 @@ def _register(
563
701
  before, before_sheet = copy.deepcopy(config), read_sheet(app)
564
702
  providers = config.setdefault("providers", {})
565
703
  if stack_provider is not None:
566
- providers[pid] = bifrost_provider.render("llm", url, name, key, pid)
704
+ providers[pid] = bifrost_config.render_provider("llm", url, name, key, pid)
567
705
  _route_agent(config)
568
706
  listed_as, names = f"{pid}/{gateway_model}", [name, gateway_model]
569
707
  else:
570
708
  providers[pid] = _provider(url, name, key, pid)
709
+ _normalize_existing_rules(config)
571
710
  listed_as, names = gateway_model, [name]
572
711
  context = int(str(plan["launch"].get("window") or 0)) or None
573
- sheet = (
574
- before_sheet
575
- | bifrost_datasheet.sheets(pid, names, context)[bifrost_datasheet.DATASHEET]
576
- )
712
+ sheet = before_sheet | bifrost_config.sheets(pid, names, context)[bifrost_config.DATASHEET]
577
713
  apply_config(record, config, sheet)
578
714
  try:
579
715
  if listed_as not in bifrost_models.listed(record["addr"]):
@@ -584,6 +720,8 @@ def _register(
584
720
  pi_entry = bifrost_models.pi_provider(facts_, gateway_model, base)["models"][0]
585
721
  if not shared: # the stack's own pi entry already names localmodels-agent
586
722
  _pi_add(pi_provider, pi_entry, base)
723
+ elif _agent_target(config) == pid:
724
+ _pi_sync_shared(pi_provider, gateway_model, facts_["context"], base, entry=pi_entry)
587
725
  _sync_pi_default(
588
726
  pi_profile(),
589
727
  pi_provider,
@@ -615,8 +753,10 @@ def _unregister(registration: Registration) -> None:
615
753
  config = gateway_bifrost.read_config(app)
616
754
  providers = config.get("providers")
617
755
  if not isinstance(providers, dict) or registration["provider"] not in providers:
756
+ _cleanup_orphaned_provider(record, config, registration["provider"])
618
757
  return
619
758
  del providers[registration["provider"]]
759
+ _normalize_existing_rules(config)
620
760
  prefix = registration["provider"] + "/"
621
761
  sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
622
762
  apply_config(record, config, sheet)
@@ -641,12 +781,14 @@ def _unwire_member(registration: Registration) -> None:
641
781
  app = Path(record["app_dir"]) if record else None
642
782
  config = gateway_bifrost.read_config(app) if app else {}
643
783
  providers = config.get("providers") or {}
784
+ was_on_disk = isinstance(providers, dict) and registration["provider"] in providers
644
785
  providers.pop(registration["provider"], None)
645
786
  if not any(p in providers for p in STACK_PROVIDERS): # the last stack LLM
646
787
  tools_root = hosts.tools_dir()
647
788
  environment = {**os.environ, **harness_probe.client_environment(tools_root)}
789
+ pi_environment = {**environment, "PI_CODING_AGENT_DIR": str(pi_profile())}
648
790
  checks = bifrost_clients.unwire(tools_root, environment=environment)
649
- checks += bifrost_pi.unpoint_pi(tools_root, environment=environment)
791
+ checks += bifrost_pi.unpoint_pi(tools_root, environment=pi_environment)
650
792
  failed = [c["detail"] for c in checks if not c["ok"]]
651
793
  if failed:
652
794
  raise _fail("; ".join(failed))
@@ -656,4 +798,15 @@ def _unwire_member(registration: Registration) -> None:
656
798
  _route_agent(config)
657
799
  prefix = registration["provider"] + "/"
658
800
  sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
659
- apply_config(record, config, sheet)
801
+ params = {bifrost_config.DATASHEET: sheet, bifrost_config.PARAMETERS: {}}
802
+ if was_on_disk or bifrost_config.differs(app, config, params):
803
+ apply_config(record, config, sheet)
804
+ else:
805
+ _cleanup_orphaned_provider(record, config, registration["provider"], sync_rules=True)
806
+ if (target := _agent_target(config)) and (ctx := _sheet_context(sheet, target)):
807
+ _pi_sync_shared(
808
+ gateway_bifrost.PI_PROVIDER,
809
+ gateway_bifrost.AGENT_MODEL,
810
+ ctx,
811
+ f"http://{record['addr']}",
812
+ )
@@ -30,6 +30,7 @@ from localmodels import (
30
30
  metal,
31
31
  plan_envelope,
32
32
  process_identity,
33
+ remote_ops,
33
34
  remote_ops_download,
34
35
  reuse,
35
36
  )
@@ -142,12 +143,33 @@ def delete_weights(files: list[str], keep: set[str]) -> list[str]:
142
143
  continue
143
144
  remote_ops_download.discard(path + ".part")
144
145
  for name in (path, path + ".sha256"):
145
- if os.path.lexists(name):
146
+ try:
146
147
  os.remove(name)
147
148
  deleted.append(name)
149
+ except FileNotFoundError:
150
+ pass
148
151
  return deleted
149
152
 
150
153
 
154
+ def prune_empty_custom_dirs(files: list[str], base_dir: str) -> None:
155
+ """Remove empty parent directories strictly under ``<base_dir>/models/custom``."""
156
+ custom_root = (Path(os.path.expanduser(base_dir)) / "models" / "custom").resolve()
157
+ if not custom_root.is_dir():
158
+ return
159
+ for raw in files:
160
+ parent = Path(os.path.expanduser(raw)).resolve().parent
161
+ while parent != custom_root:
162
+ try:
163
+ parent.relative_to(custom_root)
164
+ except ValueError:
165
+ break
166
+ try:
167
+ parent.rmdir()
168
+ except OSError:
169
+ break
170
+ parent = parent.parent
171
+
172
+
151
173
  KEEP_FAILED_DOWNLOAD_CODES = frozenset(
152
174
  ("DOWNLOAD_FAILED", "NETWORK_UNAVAILABLE", "DISK_INSUFFICIENT")
153
175
  )
@@ -183,8 +205,19 @@ class _Counter:
183
205
  the files already verified (or partially downloaded on disk) count as done; each progress
184
206
  event moves its file's counter for the phase it reports."""
185
207
 
186
- def __init__(self, model: str, plan: Plan, handle: JobHandle) -> None:
208
+ def __init__(
209
+ self,
210
+ model: str,
211
+ plan: Plan,
212
+ handle: JobHandle,
213
+ *,
214
+ shard_count: int | None = None,
215
+ ) -> None:
187
216
  self.model, self.handle = model, handle
217
+ self.shard_count = shard_count if shard_count and shard_count >= 1 else None
218
+ self.file_order = {
219
+ os.path.basename(f["dest"]): idx + 1 for idx, f in enumerate(plan["files"])
220
+ }
188
221
  self.sizes = {os.path.basename(f["dest"]): f["size_bytes"] for f in plan["files"]}
189
222
  self.done = {
190
223
  os.path.basename(f["dest"]): (
@@ -250,8 +283,20 @@ class _Counter:
250
283
  finished += sum(min(n, self.engine_sizes[k]) for k, n in self.engine_done.items())
251
284
  rate = int(speed) if isinstance(speed, int) and phase == "download" else 0
252
285
  source, connections = _download_telemetry(phase, event)
286
+ shard_index: int | None = None
287
+ shard_count: int | None = None
288
+ if phase == "download" and self.shard_count is not None and label in self.file_order:
289
+ shard_count = self.shard_count
290
+ shard_index = min(self.file_order[label], self.shard_count)
253
291
  self.handle.update(
254
- phase, finished, self.total, rate, source=source, connections=connections
292
+ phase,
293
+ finished,
294
+ self.total,
295
+ rate,
296
+ source=source,
297
+ connections=connections,
298
+ shard_index=shard_index,
299
+ shard_count=shard_count,
255
300
  )
256
301
  progress(
257
302
  self.model,
@@ -261,6 +306,8 @@ class _Counter:
261
306
  rate,
262
307
  source=source,
263
308
  connections=connections,
309
+ shard_index=shard_index,
310
+ shard_count=shard_count,
264
311
  )
265
312
 
266
313
 
@@ -296,13 +343,29 @@ def fetch(
296
343
  only: set[str] | None = None,
297
344
  *,
298
345
  engine: bool = True,
346
+ auth_headers: dict[str, str] | None = None,
347
+ shard_count: int | None = None,
299
348
  ) -> None:
300
349
  """The plan's engine (when it is a pinned release) and weights, as stack apply fetches them;
301
350
  ``only`` limits the weights to the files this job claims. Progress counts the whole model."""
302
- counter = _Counter(model, plan, handle)
351
+ counter = _Counter(model, plan, handle, shard_count=shard_count)
303
352
  initial_done = sum(counter.done.values())
304
- handle.update("download", initial_done, counter.total)
305
- progress(model, "download", initial_done, counter.total)
353
+ init_shard_idx = 1 if counter.shard_count is not None else None
354
+ handle.update(
355
+ "download",
356
+ initial_done,
357
+ counter.total,
358
+ shard_index=init_shard_idx,
359
+ shard_count=counter.shard_count,
360
+ )
361
+ progress(
362
+ model,
363
+ "download",
364
+ initial_done,
365
+ counter.total,
366
+ shard_index=init_shard_idx,
367
+ shard_count=counter.shard_count,
368
+ )
306
369
  files = [f for f in plan["files"] if only is None or os.path.expanduser(f["dest"]) in only]
307
370
  steps: tuple[Action, ...] = ("download",) if files else ()
308
371
  if engine and plan["engine"]["source"] == "release":
@@ -310,11 +373,13 @@ def fetch(
310
373
  mine: Plan = {**plan, "files": _with_reuse(files) if files else files}
311
374
  for step in steps:
312
375
  on_event = counter if step in ("engine", "download") else None
313
- outcome, result = run.run_action(
314
- step, deploy_steps.step_params(mine, step, ""), on_event=on_event or (lambda _e: None)
315
- )
376
+ params = deploy_steps.step_params(mine, step, "")
377
+ if step == "download" and auth_headers:
378
+ params = {**params, "auth_headers": dict(auth_headers)} # type: ignore[assignment]
379
+ outcome, result = run.run_action(step, params, on_event=on_event or (lambda _e: None))
316
380
  if result.returncode != 0 or outcome.get("event") != "result":
317
- message = str(outcome.get("message") or result.stderr.strip()[-500:] or "failed")
381
+ raw_msg = str(outcome.get("message") or result.stderr.strip()[-500:] or "failed")
382
+ message = remote_ops.redact_text(raw_msg)
318
383
  raise LibraryError(_code(message), message, failed=True)
319
384
  if step == "engine":
320
385
  counter.finish_engine()
@@ -498,14 +563,21 @@ def download(
498
563
  _give_up(model.id, job, handle)
499
564
  raise LibraryError("CANCELLED", "the download was cancelled") from None
500
565
  except LibraryError as exc:
501
- if exc.code in KEEP_FAILED_DOWNLOAD_CODES:
502
- with library_state.locked():
503
- if library_state.load(model.id) is None and library_state.current(job):
504
- if library_state.cancelled(job):
505
- _give_up(model.id, job, handle)
506
- raise LibraryError("CANCELLED", "the download was cancelled") from None
566
+ with library_state.locked():
567
+ if library_state.load(model.id) is None and library_state.current(job):
568
+ if library_state.cancelled(job):
569
+ _give_up(model.id, job, handle)
570
+ raise LibraryError("CANCELLED", "the download was cancelled") from None
571
+ if exc.code in KEEP_FAILED_DOWNLOAD_CODES:
507
572
  library_state.fail_job(handle.job, {"code": exc.code, "detail": exc.detail})
508
573
  claims.clear()
574
+ else:
575
+ _give_up(model.id, job, handle)
576
+ raise
577
+ except Exception:
578
+ with library_state.locked():
579
+ if library_state.load(model.id) is None and library_state.current(job):
580
+ _give_up(model.id, job, handle)
509
581
  raise
510
582
  if not autoload:
511
583
  return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
@@ -550,9 +622,11 @@ def cancel(model_id: str, base_dir: str) -> Row:
550
622
  with library_state.locked(): # it ended without cleaning up after itself (killed)
551
623
  committed = library_state.load(model.id) is not None
552
624
  if library_state.current(job) and not library_state.job_alive(model.id) and not committed:
553
- delete_weights(leftovers(job), in_use(model.id))
625
+ gone = leftovers(job)
626
+ delete_weights(gone, in_use(model.id))
627
+ prune_empty_custom_dirs(gone, job.get("base_dir") or base_dir)
554
628
  library_state.clear_job(model.id)
555
- return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
629
+ return library_status.row(library_status.Library.read(probe(), base_dir), model)
556
630
 
557
631
 
558
632
  def files_missing(plan: Plan) -> list[str]:
@@ -99,17 +99,61 @@ def _retired(record: Record) -> tuple[cat.CatalogEntry, cat.QuantVariant]:
99
99
  return entry, variant
100
100
 
101
101
 
102
+ def _entry_from_snapshot(
103
+ raw: dict[str, object], quant: str
104
+ ) -> tuple[cat.CatalogEntry, cat.QuantVariant] | None:
105
+ try:
106
+ loaded = cat.load_catalog({"schema_version": 3, "models": [raw]})
107
+ except ValueError:
108
+ return None
109
+ if not loaded:
110
+ return None
111
+ entry = loaded[0]
112
+ variant = next((v for v in entry.variants if v.quant == quant), entry.variants[0])
113
+ return entry, variant
114
+
115
+
116
+ def _custom_from_record(record: Record) -> tuple[cat.CatalogEntry, cat.QuantVariant]:
117
+ raw_entry = record.get("catalog_entry")
118
+ if isinstance(raw_entry, dict):
119
+ if found := _entry_from_snapshot(raw_entry, record["quant"]):
120
+ return found
121
+ entry, variant = _retired(record)
122
+ return (
123
+ dataclasses.replace(
124
+ entry,
125
+ status="candidate",
126
+ engine=entry.engine or "b12588-mix-c0c3de8",
127
+ ),
128
+ variant,
129
+ )
130
+
131
+
132
+ def _custom_from_job(model_id: str) -> tuple[cat.CatalogEntry, cat.QuantVariant] | None:
133
+ job = library_state.read_job(model_id)
134
+ if job is None or job.get("custom") is None:
135
+ return None
136
+ raw_entry = job.get("catalog_entry")
137
+ if isinstance(raw_entry, dict):
138
+ quant = str(job["custom"].get("variant_id") or "")
139
+ if found := _entry_from_snapshot(raw_entry, quant):
140
+ return found
141
+ return None
142
+
143
+
102
144
  def find_entry(
103
145
  model_id: str, catalog: Iterable[cat.CatalogEntry]
104
146
  ) -> tuple[cat.CatalogEntry, cat.QuantVariant] | None:
105
147
  """The model a library record on disk names by its full ``id:QUANT``, or None."""
106
148
  record = library_state.load(model_id)
107
- if record is None or record["id"] != model_id:
108
- return None
109
- if (recipe := _recipe(record)) is not None:
110
- entry, variant = library_poly.as_entry(recipe)
111
- return (entry if recipe.get("display_name") else _named(entry, catalog)), variant
112
- return _retired(record)
149
+ if record is not None and record["id"] == model_id:
150
+ if record.get("custom") is not None:
151
+ return _custom_from_record(record)
152
+ if (recipe := _recipe(record)) is not None:
153
+ entry, variant = library_poly.as_entry(recipe)
154
+ return (entry if recipe.get("display_name") else _named(entry, catalog)), variant
155
+ return _retired(record)
156
+ return _custom_from_job(model_id)
113
157
 
114
158
 
115
159
  def retired(entry: cat.CatalogEntry) -> bool: