@simplexai/localmodels-win32-x64 0.1.0-dev.58 → 0.1.0-dev.59

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 (59) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +57 -56
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/app.py +1 -1
  5. package/modules/localmodels/bifrost_admin.py +53 -8
  6. package/modules/localmodels/bifrost_config.py +103 -4
  7. package/modules/localmodels/bifrost_log.py +166 -0
  8. package/modules/localmodels/budget.py +1 -1
  9. package/modules/localmodels/catalog.json +55 -32
  10. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +94 -0
  11. package/modules/localmodels/frontend.py +26 -21
  12. package/modules/localmodels/gateway_bifrost.py +30 -6
  13. package/modules/localmodels/hosts.py +99 -12
  14. package/modules/localmodels/library_convert.py +34 -0
  15. package/modules/localmodels/library_elastic.py +150 -123
  16. package/modules/localmodels/library_gateway.py +101 -10
  17. package/modules/localmodels/library_jobs.py +16 -7
  18. package/modules/localmodels/library_pricing.py +14 -4
  19. package/modules/localmodels/library_serve.py +84 -16
  20. package/modules/localmodels/library_state.py +4 -1
  21. package/modules/localmodels/library_status.py +18 -4
  22. package/modules/localmodels/metal.py +1 -1
  23. package/modules/localmodels/metal_probe.py +4 -4
  24. package/modules/localmodels/plan_envelope.py +4 -1
  25. package/modules/localmodels/process_identity_linux.py +39 -0
  26. package/modules/localmodels/remote_ops.py +4 -3
  27. package/modules/localmodels/remote_ops_download.py +37 -24
  28. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  29. package/modules/localmodels/remote_ops_service.py +93 -36
  30. package/modules/localmodels/runtime_auth.py +4 -1
  31. package/modules/localmodels/service_wiring.py +238 -12
  32. package/modules/localmodels/setup_inspection.py +47 -70
  33. package/modules/localmodels/setup_inspection_harness.py +159 -15
  34. package/modules/localmodels/setup_text.py +14 -0
  35. package/modules/localmodels/setup_upgrade.py +1 -1
  36. package/modules/localmodels/source_byok.py +6 -2
  37. package/modules/localmodels/source_byok_probe.py +6 -1
  38. package/modules/localmodels/stack.py +9 -1
  39. package/modules/localmodels/stack_binding.py +3 -35
  40. package/modules/localmodels/stack_cleanup.py +4 -0
  41. package/modules/localmodels/stack_compose.py +18 -2
  42. package/modules/localmodels/stack_lifecycle.py +24 -1
  43. package/modules/localmodels/stack_plan.py +6 -2
  44. package/modules/localmodels/stack_ports.py +2 -0
  45. package/modules/localmodels/stack_remove.py +10 -1
  46. package/modules/localmodels/stack_up.py +33 -7
  47. package/modules/localmodels/stack_update.py +3 -1
  48. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.5.txt} +1 -1
  49. package/modules/localmodels/suite.py +43 -27
  50. package/modules/localmodels/transport.py +13 -2
  51. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/METADATA +1 -1
  52. package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/RECORD +54 -53
  53. package/package.json +1 -1
  54. package/tool.json +1 -1
  55. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  56. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/WHEEL +0 -0
  57. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/entry_points.txt +0 -0
  58. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/NOTICE +0 -0
  59. /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -11,6 +11,7 @@ non-critical VM pressure, admission succeeds at the floor posture with a pressur
11
11
  from __future__ import annotations
12
12
 
13
13
  import copy
14
+ import math
14
15
  from dataclasses import dataclass, replace
15
16
  from typing import cast
16
17
 
@@ -181,6 +182,32 @@ def elastic_posture_ladder(
181
182
  return tuple(rungs)
182
183
 
183
184
 
185
+ def _project_cuda_uma(
186
+ facts: HostFacts, unified: int, target: int, *, bypass_working_set: bool
187
+ ) -> HostFacts:
188
+ seen = copy.deepcopy(facts)
189
+ need = target + AGENT_VRAM_RESERVE_BYTES
190
+ raw = int(math.ceil(need / (1 - budget._UMA_HEADROOM_FRACTION)))
191
+ while int(raw * (1 - budget._UMA_HEADROOM_FRACTION)) < need:
192
+ raw += 1
193
+ raw = raw if bypass_working_set else min(unified, raw)
194
+ if bypass_working_set and isinstance(cuda_pool := seen.get("cuda_pool"), dict):
195
+ cuda_pool["total_bytes"], cuda_pool["integrated"] = max(unified, raw), True
196
+ for gpu in seen.get("gpus") or []:
197
+ if gpu.get("vendor") == "nvidia" and gpu.get("mig_mode") != "enabled":
198
+ gpu["free_bytes"], gpu["used_bytes"] = 0, gpu["total_bytes"]
199
+ break
200
+ ram = seen["ram"]
201
+ if bypass_working_set:
202
+ ram["total_bytes"] = max(int(ram["total_bytes"]), raw)
203
+ if (cgroup := seen.get("cgroup_memory")) is not None:
204
+ if (limit := cgroup.get("limit_bytes")) is not None and limit < raw:
205
+ cgroup["limit_bytes"] = raw
206
+ cgroup["usage_bytes"] = 0
207
+ ram["available_bytes"] = min(int(ram["total_bytes"]), raw)
208
+ return seen
209
+
210
+
184
211
  def facts_for_budget(
185
212
  facts: HostFacts,
186
213
  pool: str,
@@ -201,16 +228,18 @@ def facts_for_budget(
201
228
  )
202
229
  ram["pressure_level"] = metal.PRESSURE_NORMAL
203
230
  ram.pop("pressure_kept_bytes", None)
204
- metal_doc = seen.get("metal")
205
- if isinstance(metal_doc, dict):
206
- if bypass_working_set:
207
- ceiling = max(metal.wired_ceiling_bytes(facts), target + METAL_VRAM_RESERVE_BYTES)
208
- elif wired_cap_bytes is not None:
209
- ceiling = max(0, wired_cap_bytes) + METAL_VRAM_RESERVE_BYTES
210
- else:
211
- ceiling = metal.wired_ceiling_bytes(facts)
231
+ if isinstance(metal_doc := seen.get("metal"), dict):
232
+ ceiling = (
233
+ max(0, wired_cap_bytes) + METAL_VRAM_RESERVE_BYTES
234
+ if wired_cap_bytes is not None
235
+ else max(metal.wired_ceiling_bytes(facts), target + METAL_VRAM_RESERVE_BYTES)
236
+ if bypass_working_set
237
+ else metal.wired_ceiling_bytes(facts)
238
+ )
212
239
  metal_doc["recommended_max_working_set_bytes"] = ceiling
213
240
  return seen
241
+ if pool == "unified" and (unified := budget.unified_pool_bytes(facts)) is not None:
242
+ return _project_cuda_uma(facts, unified, target, bypass_working_set=bypass_working_set)
214
243
  if (idx := library_pricing.gpu_index(pool)) is not None:
215
244
  seen = copy.deepcopy(facts)
216
245
  for gpu in seen.get("gpus") or []:
@@ -349,14 +378,19 @@ def validate_plan_bounds(
349
378
  raise deploy.AgentMemoryError(refused.message, refused, "system memory")
350
379
 
351
380
 
381
+ @dataclass(frozen=True)
382
+ class _PriceCtx:
383
+ facts: HostFacts
384
+ model: Model
385
+ pool: str
386
+ placement: str
387
+ base_dir: str
388
+ catalog: tuple[cat.CatalogEntry, ...]
389
+ port: int
390
+
391
+
352
392
  def _price_rung(
353
- facts: HostFacts,
354
- model: Model,
355
- pool: str,
356
- placement: str,
357
- base_dir: str,
358
- catalog: tuple[cat.CatalogEntry, ...],
359
- port: int,
393
+ ctx: _PriceCtx,
360
394
  rung_posture: AgentPosture,
361
395
  *,
362
396
  budget_bytes: int,
@@ -366,8 +400,8 @@ def _price_rung(
366
400
  bypass_working_set: bool = False,
367
401
  ) -> Plan:
368
402
  priced_facts = facts_for_budget(
369
- facts,
370
- pool,
403
+ ctx.facts,
404
+ ctx.pool,
371
405
  budget_bytes,
372
406
  wired_cap_bytes=wired_cap_bytes,
373
407
  bypass_working_set=bypass_working_set,
@@ -376,24 +410,24 @@ def _price_rung(
376
410
  hosts.LOCAL_ID,
377
411
  priced_facts,
378
412
  deploy.PlanOptions(
379
- model_id=model.entry.id,
380
- placement_id=placement,
381
- port=port,
382
- base_dir=base_dir,
413
+ model_id=ctx.model.entry.id,
414
+ placement_id=ctx.placement,
415
+ port=ctx.port,
416
+ base_dir=ctx.base_dir,
383
417
  hf_download_endpoint=deploy.hf_endpoint(),
384
418
  hf_api_endpoint=deploy.hf_endpoint(),
385
419
  agent=rung_posture,
386
- quant=model.variant.quant,
420
+ quant=ctx.model.variant.quant,
387
421
  ),
388
- entries=catalog,
422
+ entries=ctx.catalog,
389
423
  resolver=deploy.catalog_pins,
390
424
  )
391
425
  validate_plan_bounds(
392
- facts,
393
- model,
394
- pool,
426
+ ctx.facts,
427
+ ctx.model,
428
+ ctx.pool,
395
429
  plan,
396
- catalog,
430
+ ctx.catalog,
397
431
  check_pool_total=check_pool_total,
398
432
  check_host_ram=check_host_ram,
399
433
  )
@@ -409,13 +443,7 @@ def _fits_hard_ceiling(plan: Plan, adm: budget.AdmissionBudget) -> bool:
409
443
 
410
444
 
411
445
  def _try_tier1_ladder(
412
- facts: HostFacts,
413
- model: Model,
414
- pool: str,
415
- placement: str,
416
- base_dir: str,
417
- catalog: tuple[cat.CatalogEntry, ...],
418
- port: int,
446
+ ctx: _PriceCtx,
419
447
  ladder: tuple[PostureRung, ...],
420
448
  requested_spec: PostureSpec,
421
449
  adm: budget.AdmissionBudget,
@@ -428,21 +456,11 @@ def _try_tier1_ladder(
428
456
  else min(adm.soft_budget_bytes, adm.hard_ceiling_bytes)
429
457
  )
430
458
  ram_shortfall: deploy.AgentMemoryError | None = None
431
- start_idx = max(0, min(min_rung_index, len(ladder)))
432
- for idx in range(start_idx, len(ladder)):
459
+ for idx in range(max(0, min(min_rung_index, len(ladder))), len(ladder)):
433
460
  rung = ladder[idx]
434
461
  try:
435
462
  plan = _price_rung(
436
- facts,
437
- model,
438
- pool,
439
- placement,
440
- base_dir,
441
- catalog,
442
- port,
443
- rung.posture,
444
- budget_bytes=tier1_budget,
445
- wired_cap_bytes=wired_cap,
463
+ ctx, rung.posture, budget_bytes=tier1_budget, wired_cap_bytes=wired_cap
446
464
  )
447
465
  except deploy.AgentMemoryError as exc:
448
466
  if exc.memory == "system memory":
@@ -468,14 +486,65 @@ def _try_tier1_ladder(
468
486
  return None, ram_shortfall
469
487
 
470
488
 
489
+ def _force_within_hard_limits(
490
+ adm: budget.AdmissionBudget, min_need: int, min_wired_need: int
491
+ ) -> bool:
492
+ """Whether ``--force`` stays within non-overridable hardware ceilings (non-critical pressure,
493
+ physical memory limit, and on Apple Silicon the kernel/Metal wired ceiling)."""
494
+ if adm.critical_pressure or min_need > adm.physical_limit_bytes:
495
+ return False
496
+ return not (
497
+ adm.backend == "metal"
498
+ and adm.wired_ceiling_bytes is not None
499
+ and min_wired_need > adm.wired_ceiling_bytes
500
+ )
501
+
502
+
503
+ def _price_forced_floor(
504
+ ctx: _PriceCtx,
505
+ compact_floor: AgentPosture,
506
+ adm: budget.AdmissionBudget,
507
+ min_need: int,
508
+ min_wired_need: int,
509
+ *,
510
+ raise_system_ram: bool = False,
511
+ ) -> Plan | None:
512
+ """Price the compact floor under ``--force`` while enforcing hard physical ceilings."""
513
+ if not _force_within_hard_limits(adm, min_need, min_wired_need):
514
+ return None
515
+ wired_cap = adm.wired_ceiling_bytes if adm.backend == "metal" else None
516
+ try:
517
+ plan = _price_rung(
518
+ ctx,
519
+ compact_floor,
520
+ budget_bytes=adm.physical_limit_bytes,
521
+ wired_cap_bytes=wired_cap,
522
+ check_pool_total=False,
523
+ check_host_ram=True,
524
+ bypass_working_set=True,
525
+ )
526
+ except deploy.AgentMemoryError as exc:
527
+ if raise_system_ram and exc.memory == "system memory":
528
+ raise ElasticRoomError(
529
+ str(exc),
530
+ pool="system",
531
+ need_bytes=exc.needed_bytes,
532
+ free_bytes=exc.available_bytes,
533
+ memory="system memory",
534
+ soft_available_bytes=exc.available_bytes,
535
+ can_force=False,
536
+ ) from None
537
+ return None
538
+ wired_ok = (
539
+ adm.backend != "metal"
540
+ or adm.wired_ceiling_bytes is None
541
+ or _vram_bytes(plan) <= adm.wired_ceiling_bytes
542
+ )
543
+ return plan if wired_ok and memory_bytes(plan) <= adm.physical_limit_bytes else None
544
+
545
+
471
546
  def _try_floor_admission(
472
- facts: HostFacts,
473
- model: Model,
474
- pool: str,
475
- placement: str,
476
- base_dir: str,
477
- catalog: tuple[cat.CatalogEntry, ...],
478
- port: int,
547
+ ctx: _PriceCtx,
479
548
  ladder: tuple[PostureRung, ...],
480
549
  compact_floor: AgentPosture,
481
550
  requested_spec: PostureSpec,
@@ -492,19 +561,14 @@ def _try_floor_admission(
492
561
  allow_overcommit
493
562
  and adm.allows_soft_overcommit
494
563
  and not adm.critical_pressure
564
+ and adm.pressure_level != metal.PRESSURE_WARN
495
565
  and min_rung_index <= floor_idx
496
566
  and min_wired_need <= adm.hard_ceiling_bytes
497
567
  and min_need <= adm.physical_limit_bytes
498
568
  ):
499
569
  try:
500
570
  plan = _price_rung(
501
- facts,
502
- model,
503
- pool,
504
- placement,
505
- base_dir,
506
- catalog,
507
- port,
571
+ ctx,
508
572
  compact_floor,
509
573
  budget_bytes=adm.physical_limit_bytes,
510
574
  wired_cap_bytes=adm.hard_ceiling_bytes,
@@ -512,12 +576,10 @@ def _try_floor_admission(
512
576
  except deploy.AgentMemoryError:
513
577
  plan = None
514
578
  if plan is not None and _fits_hard_ceiling(plan, adm):
515
- level: MemoryPressureWarningLevel = (
516
- "high" if adm.pressure_level == metal.PRESSURE_WARN else "soft"
517
- )
579
+ level: MemoryPressureWarningLevel = "soft"
518
580
  warning: MemoryPressureWarning = {
519
581
  "level": level,
520
- "pool": pool,
582
+ "pool": ctx.pool,
521
583
  "free_bytes": adm.soft_budget_bytes,
522
584
  "budget_bytes": adm.hard_ceiling_bytes,
523
585
  }
@@ -533,28 +595,14 @@ def _try_floor_admission(
533
595
  forced=False,
534
596
  admission=adm,
535
597
  )
536
- if force and not adm.critical_pressure and min_need <= adm.physical_limit_bytes:
537
- try:
538
- plan = _price_rung(
539
- facts,
540
- model,
541
- pool,
542
- placement,
543
- base_dir,
544
- catalog,
545
- port,
546
- compact_floor,
547
- budget_bytes=adm.physical_limit_bytes,
548
- check_pool_total=False,
549
- check_host_ram=False,
550
- bypass_working_set=True,
551
- )
552
- except deploy.AgentMemoryError:
553
- plan = None
554
- if plan is not None and memory_bytes(plan) <= adm.physical_limit_bytes:
598
+ if force:
599
+ plan = _price_forced_floor(
600
+ ctx, compact_floor, adm, min_need, min_wired_need, raise_system_ram=True
601
+ )
602
+ if plan is not None:
555
603
  forced_warning: MemoryPressureWarning = {
556
604
  "level": "high",
557
- "pool": pool,
605
+ "pool": ctx.pool,
558
606
  "free_bytes": min(adm.soft_budget_bytes, adm.hard_ceiling_bytes),
559
607
  "budget_bytes": adm.physical_limit_bytes,
560
608
  }
@@ -605,18 +653,7 @@ def price_elastic(
605
653
  require_live=True,
606
654
  )
607
655
  eff = _plan_posture(poly_plan)
608
- return ElasticPlan(
609
- plan=poly_plan,
610
- rung_index=0,
611
- ladder=(),
612
- requested_posture=eff,
613
- effective_posture=eff,
614
- degraded=False,
615
- degradation_reason=None,
616
- memory_pressure_warning=None,
617
- forced=False,
618
- admission=adm,
619
- )
656
+ return ElasticPlan(poly_plan, 0, (), eff, eff, False, None, None, False, adm)
620
657
  ladder = elastic_posture_ladder(
621
658
  library_pricing.posture(),
622
659
  backend=adm.backend,
@@ -651,19 +688,8 @@ def price_elastic(
651
688
  context_tokens=req_window, slots=req_p.slots, kv_types=req_p.kv_types[0]
652
689
  )
653
690
 
654
- admitted, ram_shortfall = _try_tier1_ladder(
655
- facts,
656
- model,
657
- pool,
658
- placement,
659
- base_dir,
660
- catalog,
661
- port,
662
- ladder,
663
- requested_spec,
664
- adm,
665
- min_rung_index,
666
- )
691
+ ctx = _PriceCtx(facts, model, pool, placement, base_dir, catalog, port)
692
+ admitted, ram_shortfall = _try_tier1_ladder(ctx, ladder, requested_spec, adm, min_rung_index)
667
693
  if admitted is not None:
668
694
  return admitted
669
695
  if ram_shortfall is not None:
@@ -677,13 +703,7 @@ def price_elastic(
677
703
  can_force=False,
678
704
  )
679
705
  floor_admitted = _try_floor_admission(
680
- facts,
681
- model,
682
- pool,
683
- placement,
684
- base_dir,
685
- catalog,
686
- port,
706
+ ctx,
687
707
  ladder,
688
708
  compact_floor,
689
709
  requested_spec,
@@ -698,16 +718,23 @@ def price_elastic(
698
718
  return floor_admitted
699
719
 
700
720
  memory_label = "unified memory" if pool == "unified" else "GPU memory"
701
- can_force = (not adm.critical_pressure) and (min_need <= adm.physical_limit_bytes)
721
+ can_force = (
722
+ not force
723
+ and _price_forced_floor(ctx, compact_floor, adm, min_need, min_wired_need) is not None
724
+ )
702
725
  wired_blocked = adm.backend == "metal" and min_wired_need > adm.hard_ceiling_bytes
726
+ phys_blocked = min_need > adm.physical_limit_bytes
727
+ soft_blocked = adm.backend == "metal" and not wired_blocked and not phys_blocked
703
728
  report_need = min_wired_need if wired_blocked else min_need
704
- report_free = (
705
- adm.hard_ceiling_bytes
706
- if wired_blocked or adm.backend != "metal"
707
- else adm.physical_limit_bytes
708
- )
729
+ if wired_blocked or adm.backend != "metal":
730
+ report_free = adm.hard_ceiling_bytes
731
+ elif phys_blocked:
732
+ report_free = adm.physical_limit_bytes
733
+ else:
734
+ report_free = adm.soft_budget_bytes
735
+ ceiling_label = "soft budget" if soft_blocked else "hard ceiling"
709
736
  raise ElasticRoomError(
710
- f"{model.id} does not fit {pool} now (floor needs {report_need} bytes, hard ceiling "
737
+ f"{model.id} does not fit {pool} now (floor needs {report_need} bytes, {ceiling_label} "
711
738
  f"{report_free} bytes)",
712
739
  pool=pool,
713
740
  need_bytes=report_need,
@@ -26,6 +26,7 @@ from localmodels import (
26
26
  bifrost_admin,
27
27
  bifrost_config,
28
28
  bifrost_datasheet,
29
+ bifrost_log,
29
30
  bifrost_models,
30
31
  bifrost_unit,
31
32
  gateway_bifrost,
@@ -204,8 +205,9 @@ def apply_config(record: hosts.OwnedBifrost, config: dict[str, Any], sheet: dict
204
205
  _stop(record)
205
206
  return
206
207
  if changed or not gateway_bifrost._healthy_owned(record):
208
+ log_offset = bifrost_log.log_size(app)
207
209
  gateway_bifrost._start(record, restart=changed)
208
- gateway_bifrost._await(record["addr"], record=record)
210
+ gateway_bifrost._await(record["addr"], record=record, log_offset=log_offset)
209
211
 
210
212
 
211
213
  def _stop(record: hosts.OwnedBifrost) -> None:
@@ -257,6 +259,15 @@ def _ours_marker(provider: str) -> Path:
257
259
  return library_state.root() / f"pi-provider{suffix}"
258
260
 
259
261
 
262
+ def _pi_provider_doc(base: str, models: list[dict[str, Any]]) -> dict[str, Any]:
263
+ return {
264
+ "baseUrl": f"{base}/v1",
265
+ "api": "openai-completions",
266
+ "apiKey": gateway_bifrost.CALLER_KEY,
267
+ "models": models,
268
+ }
269
+
270
+
260
271
  def _pi_add(provider: str, entry: dict[str, Any], base: str) -> None:
261
272
  path = pi_profile() / "models.json"
262
273
  models = _read(path)
@@ -270,12 +281,7 @@ def _pi_add(provider: str, entry: dict[str, Any], base: str) -> None:
270
281
  marker.parent.mkdir(parents=True, exist_ok=True)
271
282
  marker.write_text(str(path) + "\n", encoding="utf-8")
272
283
  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
- }
284
+ providers[provider] = _pi_provider_doc(base, [*kept, entry])
279
285
  _write(path, models)
280
286
 
281
287
 
@@ -294,6 +300,74 @@ def _marker_for_other_file(marker: Path, path: Path) -> bool:
294
300
  return False
295
301
 
296
302
 
303
+ def _agent_target(config: dict[str, Any]) -> str | None:
304
+ rules = (config.get("governance") or {}).get("routing_rules") or []
305
+ agent = next(
306
+ (r for r in rules if isinstance(r, dict) and r.get("id") == gateway_bifrost.AGENT_RULE),
307
+ None,
308
+ )
309
+ targets = (agent or {}).get("targets") or []
310
+ target = targets[0].get("provider") if targets and isinstance(targets[0], dict) else None
311
+ return str(target) if isinstance(target, str) and target else None
312
+
313
+
314
+ def _pi_sync_shared(
315
+ provider: str, model_id: str, context: int, base: str, *, entry: dict[str, Any] | None = None
316
+ ) -> None:
317
+ """Sync ``contextWindow``/``maxTokens`` on an owned pi provider entry without changing
318
+ stack ownership or clobbering a user-defined provider (different ``baseUrl``)."""
319
+ if context <= 0:
320
+ return
321
+ path = pi_profile() / "models.json"
322
+ try:
323
+ models = _read(path)
324
+ except LibraryError:
325
+ if entry is not None:
326
+ raise
327
+ return
328
+ providers = models.setdefault("providers", {})
329
+ if not isinstance(providers, dict):
330
+ if entry is not None:
331
+ raise _fail("providers in pi's models.json is not an object; left as is")
332
+ return
333
+ current = providers.get(provider)
334
+ if current is None:
335
+ if entry is not None:
336
+ providers[provider] = _pi_provider_doc(base, [entry])
337
+ _write(path, models)
338
+ return
339
+ if not isinstance(current, dict) or not str(current.get("baseUrl", "")).startswith(f"{base}/"):
340
+ return
341
+ items = current.get("models")
342
+ if not isinstance(items, list):
343
+ return
344
+ max_tokens = min(32768, max(4096, context // 4))
345
+ matched = [m for m in items if isinstance(m, dict) and m.get("id") == model_id]
346
+ changed = False
347
+ for item in matched:
348
+ if item.get("contextWindow") != context or item.get("maxTokens") != max_tokens:
349
+ item["contextWindow"], item["maxTokens"] = context, max_tokens
350
+ changed = True
351
+ if not matched and entry is not None:
352
+ items.append(entry)
353
+ changed = True
354
+ if changed:
355
+ _write(path, models)
356
+
357
+
358
+ def _sheet_context(sheet: dict[str, Any], provider: str) -> int | None:
359
+ prefix = provider + "/"
360
+ for key in (
361
+ f"{prefix}{gateway_bifrost.AGENT_MODEL}",
362
+ *(k for k in sheet if k.startswith(prefix)),
363
+ ):
364
+ doc = sheet.get(key)
365
+ ctx = doc.get("context_length") if isinstance(doc, dict) else None
366
+ if isinstance(ctx, int) and not isinstance(ctx, bool) and ctx > 0:
367
+ return ctx
368
+ return None
369
+
370
+
297
371
  def _pi_drop(provider: str, model_id: str) -> None:
298
372
  marker = _ours_marker(provider)
299
373
  if not marker.is_file():
@@ -360,7 +434,7 @@ def _agent_rule(provider: str, served: str) -> dict[str, Any]:
360
434
  "description": "local agent turns sent to the local LLM",
361
435
  "cel_expression": f"model == '{gateway_bifrost.AGENT_MODEL}'",
362
436
  "targets": [{"provider": provider, "model": served, "weight": 1}],
363
- "priority": 1,
437
+ "priority": bifrost_config.AGENT_RULE_PRIORITY,
364
438
  }
365
439
 
366
440
 
@@ -376,7 +450,7 @@ def _route_agent(config: dict[str, Any]) -> None:
376
450
  rules = [
377
451
  r
378
452
  for r in governance.get("routing_rules") or []
379
- if r.get("id") != gateway_bifrost.COMPLEX_RULE
453
+ if isinstance(r, dict) and r.get("id") != gateway_bifrost.COMPLEX_RULE
380
454
  ]
381
455
  governance.pop("complexity_analyzer_config", None)
382
456
  left = [p for p in STACK_PROVIDERS if p in providers]
@@ -390,6 +464,11 @@ def _route_agent(config: dict[str, Any]) -> None:
390
464
  served = (keys[0].get("models") or [gateway_bifrost.AGENT_MODEL])[0]
391
465
  rules.append(_agent_rule(left[0], served))
392
466
  governance["routing_rules"] = rules
467
+ bifrost_config.sanitize_governance(config)
468
+
469
+
470
+ def _normalize_existing_rules(config: dict[str, Any]) -> None:
471
+ bifrost_config.sanitize_governance(config)
393
472
 
394
473
 
395
474
  def planned(model: str, plan: Plan, *, stack_provider: str | None = None) -> Registration:
@@ -568,6 +647,7 @@ def _register(
568
647
  listed_as, names = f"{pid}/{gateway_model}", [name, gateway_model]
569
648
  else:
570
649
  providers[pid] = _provider(url, name, key, pid)
650
+ _normalize_existing_rules(config)
571
651
  listed_as, names = gateway_model, [name]
572
652
  context = int(str(plan["launch"].get("window") or 0)) or None
573
653
  sheet = (
@@ -584,6 +664,8 @@ def _register(
584
664
  pi_entry = bifrost_models.pi_provider(facts_, gateway_model, base)["models"][0]
585
665
  if not shared: # the stack's own pi entry already names localmodels-agent
586
666
  _pi_add(pi_provider, pi_entry, base)
667
+ elif _agent_target(config) == pid:
668
+ _pi_sync_shared(pi_provider, gateway_model, facts_["context"], base, entry=pi_entry)
587
669
  _sync_pi_default(
588
670
  pi_profile(),
589
671
  pi_provider,
@@ -617,6 +699,7 @@ def _unregister(registration: Registration) -> None:
617
699
  if not isinstance(providers, dict) or registration["provider"] not in providers:
618
700
  return
619
701
  del providers[registration["provider"]]
702
+ _normalize_existing_rules(config)
620
703
  prefix = registration["provider"] + "/"
621
704
  sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
622
705
  apply_config(record, config, sheet)
@@ -645,8 +728,9 @@ def _unwire_member(registration: Registration) -> None:
645
728
  if not any(p in providers for p in STACK_PROVIDERS): # the last stack LLM
646
729
  tools_root = hosts.tools_dir()
647
730
  environment = {**os.environ, **harness_probe.client_environment(tools_root)}
731
+ pi_environment = {**environment, "PI_CODING_AGENT_DIR": str(pi_profile())}
648
732
  checks = bifrost_clients.unwire(tools_root, environment=environment)
649
- checks += bifrost_pi.unpoint_pi(tools_root, environment=environment)
733
+ checks += bifrost_pi.unpoint_pi(tools_root, environment=pi_environment)
650
734
  failed = [c["detail"] for c in checks if not c["ok"]]
651
735
  if failed:
652
736
  raise _fail("; ".join(failed))
@@ -657,3 +741,10 @@ def _unwire_member(registration: Registration) -> None:
657
741
  prefix = registration["provider"] + "/"
658
742
  sheet = {k: v for k, v in read_sheet(app).items() if not k.startswith(prefix)}
659
743
  apply_config(record, config, sheet)
744
+ if (target := _agent_target(config)) and (ctx := _sheet_context(sheet, target)):
745
+ _pi_sync_shared(
746
+ gateway_bifrost.PI_PROVIDER,
747
+ gateway_bifrost.AGENT_MODEL,
748
+ ctx,
749
+ f"http://{record['addr']}",
750
+ )
@@ -142,9 +142,11 @@ def delete_weights(files: list[str], keep: set[str]) -> list[str]:
142
142
  continue
143
143
  remote_ops_download.discard(path + ".part")
144
144
  for name in (path, path + ".sha256"):
145
- if os.path.lexists(name):
145
+ try:
146
146
  os.remove(name)
147
147
  deleted.append(name)
148
+ except FileNotFoundError:
149
+ pass
148
150
  return deleted
149
151
 
150
152
 
@@ -498,14 +500,21 @@ def download(
498
500
  _give_up(model.id, job, handle)
499
501
  raise LibraryError("CANCELLED", "the download was cancelled") from None
500
502
  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
503
+ with library_state.locked():
504
+ if library_state.load(model.id) is None and library_state.current(job):
505
+ if library_state.cancelled(job):
506
+ _give_up(model.id, job, handle)
507
+ raise LibraryError("CANCELLED", "the download was cancelled") from None
508
+ if exc.code in KEEP_FAILED_DOWNLOAD_CODES:
507
509
  library_state.fail_job(handle.job, {"code": exc.code, "detail": exc.detail})
508
510
  claims.clear()
511
+ else:
512
+ _give_up(model.id, job, handle)
513
+ raise
514
+ except Exception:
515
+ with library_state.locked():
516
+ if library_state.load(model.id) is None and library_state.current(job):
517
+ _give_up(model.id, job, handle)
509
518
  raise
510
519
  if not autoload:
511
520
  return library_status.model_row(library_status.Library.read(probe(), base_dir), model.id)
@@ -316,10 +316,20 @@ def live(
316
316
  else:
317
317
  delta = unified_delta + system_delta
318
318
  ram["available_bytes"] = max(0, min(ram["total_bytes"], ram["available_bytes"] - delta))
319
- metal_doc = seen.get("metal")
320
- if metal.supported(seen) and unified_delta and isinstance(metal_doc, dict):
321
- cur_in_use = metal.gpu_in_use_bytes(seen)
322
- metal_doc["gpu_in_use_bytes"] = max(0, cur_in_use + unified_delta)
319
+ if metal.supported(seen) and unified_delta:
320
+ gpu_reading = metal.gpu_in_use_reading(seen)
321
+ metal_doc = seen.get("metal")
322
+ if isinstance(metal_doc, dict):
323
+ cur_in_use = metal.gpu_in_use_bytes(seen)
324
+ metal_doc["gpu_in_use_bytes"] = max(0, cur_in_use + unified_delta)
325
+ wired_ram = ram.get("wired_bytes")
326
+ if isinstance(wired_ram, int) and not isinstance(wired_ram, bool) and wired_ram >= 0:
327
+ wired_delta = (
328
+ max(unified_delta, -gpu_reading)
329
+ if unified_delta < 0 and gpu_reading is not None
330
+ else unified_delta
331
+ )
332
+ ram["wired_bytes"] = max(0, min(ram["total_bytes"], wired_ram + wired_delta))
323
333
  seen["llama_servers"] = []
324
334
  seen["disk"] = {**seen["disk"], "free_bytes": None}
325
335
  return seen