@simplexai/localmodels-win32-x64 0.1.0-dev.62 → 0.1.0-dev.64

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 +112 -103
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/app.py +15 -2
  5. package/modules/localmodels/bifrost_checks.py +19 -13
  6. package/modules/localmodels/bifrost_clients.py +38 -36
  7. package/modules/localmodels/bifrost_config.py +19 -6
  8. package/modules/localmodels/bifrost_log.py +3 -3
  9. package/modules/localmodels/bifrost_models.py +9 -8
  10. package/modules/localmodels/bifrost_pi.py +27 -72
  11. package/modules/localmodels/catalog.json +85 -58
  12. package/modules/localmodels/catalog.py +26 -4
  13. package/modules/localmodels/catalog_recipes.py +37 -1
  14. package/modules/localmodels/context_policy.py +6 -1
  15. package/modules/localmodels/custom_hub.py +10 -1
  16. package/modules/localmodels/custom_hub_http.py +14 -3
  17. package/modules/localmodels/debug_mode.py +85 -103
  18. package/modules/localmodels/deploy.py +41 -6
  19. package/modules/localmodels/download-mirrors.json +126 -6
  20. package/modules/localmodels/draft_spec.py +122 -0
  21. package/modules/localmodels/engine_adapters/__init__.py +4 -0
  22. package/modules/localmodels/engine_adapters/auxiliary.py +27 -0
  23. package/modules/localmodels/engine_adapters/base.py +40 -0
  24. package/modules/localmodels/engine_adapters/strata_poly.py +57 -0
  25. package/modules/localmodels/engine_adapters/suite_plan.py +394 -0
  26. package/modules/localmodels/engines-prism-b12178-03ec600.json +7 -7
  27. package/modules/localmodels/gateway.py +56 -55
  28. package/modules/localmodels/gateway_bifrost.py +70 -83
  29. package/modules/localmodels/gateway_clients.py +33 -116
  30. package/modules/localmodels/gateway_home.py +5 -5
  31. package/modules/localmodels/gateway_keys.py +8 -6
  32. package/modules/localmodels/gateway_probe.py +4 -4
  33. package/modules/localmodels/gateway_server.py +4 -4
  34. package/modules/localmodels/gateway_speed.py +2 -2
  35. package/modules/localmodels/harness.py +185 -401
  36. package/modules/localmodels/harness_core.py +409 -0
  37. package/modules/localmodels/harness_gateway.py +75 -73
  38. package/modules/localmodels/harness_probe.py +19 -216
  39. package/modules/localmodels/install.py +15 -0
  40. package/modules/localmodels/library_convert.py +2 -8
  41. package/modules/localmodels/library_custom.py +51 -16
  42. package/modules/localmodels/library_elastic.py +3 -119
  43. package/modules/localmodels/library_gateway.py +59 -176
  44. package/modules/localmodels/library_jobs.py +1 -2
  45. package/modules/localmodels/library_model.py +23 -0
  46. package/modules/localmodels/library_poly.py +3 -2
  47. package/modules/localmodels/library_pricing.py +124 -15
  48. package/modules/localmodels/library_serve.py +9 -9
  49. package/modules/localmodels/library_smoke.py +33 -21
  50. package/modules/localmodels/library_status.py +330 -2
  51. package/modules/localmodels/llm_rank.py +14 -5
  52. package/modules/localmodels/magpie_setup.py +5 -4
  53. package/modules/localmodels/magpie_windows.py +1 -1
  54. package/modules/localmodels/memcalc_cli.py +2 -2
  55. package/modules/localmodels/pi_profile.py +384 -0
  56. package/modules/localmodels/planning/__init__.py +3 -0
  57. package/modules/localmodels/{memcalc_load.py → planning/memcalc_load.py} +1 -1
  58. package/modules/localmodels/{sizecalc.py → planning/sizecalc.py} +1 -1
  59. package/modules/localmodels/process_identity.py +3 -3
  60. package/modules/localmodels/runtime_cli.py +32 -46
  61. package/modules/localmodels/runtime_pi.py +1 -1
  62. package/modules/localmodels/service_deployment.py +2 -1
  63. package/modules/localmodels/sizecalc_cli.py +10 -2
  64. package/modules/localmodels/source_byok.py +9 -16
  65. package/modules/localmodels/speech_worker_sensevoice.py +30 -0
  66. package/modules/localmodels/stack.py +2 -4
  67. package/modules/localmodels/stack_arena.py +2 -2
  68. package/modules/localmodels/stack_auto.py +1 -1
  69. package/modules/localmodels/stack_aux_gpu.py +4 -2
  70. package/modules/localmodels/stack_binding.py +9 -7
  71. package/modules/localmodels/stack_card.py +2 -2
  72. package/modules/localmodels/stack_cleanup.py +3 -2
  73. package/modules/localmodels/stack_clients.py +137 -21
  74. package/modules/localmodels/stack_compose.py +9 -1
  75. package/modules/localmodels/stack_doctor.py +6 -3
  76. package/modules/localmodels/stack_hardware.py +18 -0
  77. package/modules/localmodels/stack_ledger.py +2 -1
  78. package/modules/localmodels/stack_lifecycle.py +3 -2
  79. package/modules/localmodels/stack_mcp.py +1 -1
  80. package/modules/localmodels/stack_memory.py +3 -3
  81. package/modules/localmodels/stack_remove.py +2 -1
  82. package/modules/localmodels/stack_run.py +16 -0
  83. package/modules/localmodels/stack_suite.py +4 -3
  84. package/modules/localmodels/stack_try.py +2 -1
  85. package/modules/localmodels/stack_up.py +15 -30
  86. package/modules/localmodels/stack_verify.py +2 -2
  87. package/modules/localmodels/stack_view_events.py +2 -2
  88. package/modules/localmodels/stack_view_llm.py +12 -7
  89. package/modules/localmodels/stack_warm.py +6 -3
  90. package/modules/localmodels/stack_whatif.py +1 -1
  91. package/modules/localmodels/suite.py +6 -334
  92. package/modules/localmodels/tui_views.py +17 -2
  93. package/modules/localmodels/web/index.html +595 -226
  94. package/modules/localmodels/web/sizecalc/app.js +34 -40
  95. package/modules/localmodels/web/sizecalc/calc.js +3 -3
  96. package/modules/localmodels/web/sizecalc/page.html +4 -3
  97. package/modules/localmodels/web/view/fleet.html +18 -3
  98. package/modules/localmodels/web/view/fleet.js +135 -14
  99. package/modules/localmodels/web/view/i18n.js +4 -0
  100. package/modules/localmodels/web/view/index.html +16 -0
  101. package/modules/localmodels/web/view/nav.js +49 -0
  102. package/modules/localmodels/web/view/theme.js +1 -1
  103. package/modules/localmodels/web/view/view.css +51 -15
  104. package/modules/localmodels/web/view/view.js +22 -4
  105. package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/METADATA +1 -1
  106. package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/RECORD +109 -100
  107. package/package.json +1 -1
  108. package/tool.json +1 -1
  109. /package/modules/localmodels/{memcalc.py → planning/memcalc.py} +0 -0
  110. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/WHEEL +0 -0
  111. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/entry_points.txt +0 -0
  112. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/licenses/NOTICE +0 -0
  113. /package/modules/{simplex_localmodels-0.1.0.dev62.dist-info → simplex_localmodels-0.1.0.dev64.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -10,8 +10,6 @@ non-critical VM pressure, admission succeeds at the floor posture with a pressur
10
10
 
11
11
  from __future__ import annotations
12
12
 
13
- import copy
14
- import math
15
13
  from dataclasses import dataclass, replace
16
14
  from typing import cast
17
15
 
@@ -31,8 +29,6 @@ from localmodels import (
31
29
  from localmodels import catalog as cat
32
30
  from localmodels.context_policy import AgentPosture
33
31
  from localmodels.estimator import (
34
- AGENT_VRAM_RESERVE_BYTES,
35
- METAL_VRAM_RESERVE_BYTES,
36
32
  PhysicsRefusal,
37
33
  )
38
34
  from localmodels.library_model import (
@@ -182,76 +178,6 @@ def elastic_posture_ladder(
182
178
  return tuple(rungs)
183
179
 
184
180
 
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
-
211
- def facts_for_budget(
212
- facts: HostFacts,
213
- pool: str,
214
- target_bytes: int,
215
- *,
216
- wired_cap_bytes: int | None = None,
217
- bypass_working_set: bool = False,
218
- ) -> HostFacts:
219
- """Project ``facts`` so ``deploy.build_plan`` prices ``pool`` against ``target_bytes``
220
- (unified/total) and optional ``wired_cap_bytes`` (Metal GPU wired headroom)."""
221
- target = max(0, target_bytes)
222
- if pool == "unified" and metal.supported(facts):
223
- seen = copy.deepcopy(facts)
224
- ram = seen["ram"]
225
- needed_avail = target + metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
226
- ram["available_bytes"] = (
227
- needed_avail if bypass_working_set else min(int(ram["total_bytes"]), needed_avail)
228
- )
229
- ram["pressure_level"] = metal.PRESSURE_NORMAL
230
- ram.pop("pressure_kept_bytes", None)
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
- )
239
- metal_doc["recommended_max_working_set_bytes"] = ceiling
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)
243
- if (idx := library_pricing.gpu_index(pool)) is not None:
244
- seen = copy.deepcopy(facts)
245
- for gpu in seen.get("gpus") or []:
246
- if gpu["index"] == idx:
247
- free = target + AGENT_VRAM_RESERVE_BYTES
248
- gpu["free_bytes"] = free if bypass_working_set else min(gpu["total_bytes"], free)
249
- gpu["used_bytes"] = max(0, gpu["total_bytes"] - gpu["free_bytes"])
250
- break
251
- return seen
252
- return facts
253
-
254
-
255
181
  def _plan_posture(plan: Plan) -> PostureSpec:
256
182
  launch = plan["launch"]
257
183
  window = int(str(launch.get("window") or 0))
@@ -336,48 +262,6 @@ def minimum_memory_bytes(facts: HostFacts, model: Model, pool: str) -> int | Non
336
262
  return min_need
337
263
 
338
264
 
339
- def validate_plan_bounds(
340
- facts: HostFacts,
341
- model: Model,
342
- pool: str,
343
- plan: Plan,
344
- catalog: tuple[cat.CatalogEntry, ...],
345
- *,
346
- check_pool_total: bool = True,
347
- check_host_ram: bool = True,
348
- ) -> None:
349
- """Reject a plan exceeding ``pool``'s total capacity or host RAM on a discrete GPU."""
350
- if check_pool_total:
351
- total = library_pricing.pool_total(facts, pool)
352
- used = memory_bytes(plan)
353
- if used > total:
354
- refused = PhysicsRefusal(
355
- needed_bytes=used,
356
- available_bytes=total,
357
- message=f"{model.id} needs {used} bytes, exceeding pool {pool} total {total} bytes",
358
- )
359
- raise deploy.AgentMemoryError(
360
- refused.message,
361
- refused,
362
- "unified memory" if pool == "unified" else "GPU memory",
363
- )
364
- if check_host_ram and library_pricing.gpu_index(pool) is not None:
365
- needed_ram = (
366
- library_pricing.host_ram_bytes(plan, catalog) + budget.HARNESS_RAM + budget.RAM_FLOOR
367
- )
368
- _, avail_ram = budget.host_ram(facts)
369
- if needed_ram > avail_ram:
370
- refused = PhysicsRefusal(
371
- needed_bytes=needed_ram,
372
- available_bytes=avail_ram,
373
- message=(
374
- f"{model.id} needs {needed_ram} bytes of system memory, "
375
- f"exceeding {avail_ram} bytes available"
376
- ),
377
- )
378
- raise deploy.AgentMemoryError(refused.message, refused, "system memory")
379
-
380
-
381
265
  @dataclass(frozen=True)
382
266
  class _PriceCtx:
383
267
  facts: HostFacts
@@ -400,7 +284,7 @@ def _price_rung(
400
284
  check_host_ram: bool = True,
401
285
  bypass_working_set: bool = False,
402
286
  ) -> Plan:
403
- priced_facts = facts_for_budget(
287
+ priced_facts = library_pricing.facts_for_budget(
404
288
  ctx.facts,
405
289
  ctx.pool,
406
290
  budget_bytes,
@@ -424,7 +308,7 @@ def _price_rung(
424
308
  entries=ctx.catalog,
425
309
  resolver=deploy.catalog_pins,
426
310
  )
427
- validate_plan_bounds(
311
+ library_pricing.validate_plan_bounds(
428
312
  ctx.facts,
429
313
  ctx.model,
430
314
  ctx.pool,
@@ -597,7 +481,7 @@ def _try_floor_admission(
597
481
  forced=False,
598
482
  admission=adm,
599
483
  )
600
- if force:
484
+ if force and min_rung_index <= floor_idx:
601
485
  plan = _price_forced_floor(
602
486
  ctx, compact_floor, adm, min_need, min_wired_need, raise_system_ram=True
603
487
  )
@@ -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)
@@ -23,6 +23,7 @@ from localmodels import (
23
23
  deploy_steps,
24
24
  frontend,
25
25
  hosts,
26
+ library_convert,
26
27
  library_gateway,
27
28
  library_pricing,
28
29
  library_state,
@@ -537,8 +538,6 @@ def download(
537
538
  load: Callable[[str, str, list[str]], Row],
538
539
  ) -> Row:
539
540
  """Fetch the model into ``base_dir``, record it, then load it when its pool has room."""
540
- from localmodels import library_convert
541
-
542
541
  library_convert.convert_once()
543
542
  lib = library_status.Library.read(probe(), base_dir)
544
543
  model = library_pricing.find(model_id, lib.catalog)
@@ -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