@simplexai/localmodels-win32-x64 0.1.0-dev.57 → 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 (68) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +66 -64
  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 +161 -1
  9. package/modules/localmodels/catalog.json +55 -32
  10. package/modules/localmodels/catalog.py +5 -2
  11. package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +94 -0
  12. package/modules/localmodels/frontend.py +26 -21
  13. package/modules/localmodels/gateway_bifrost.py +30 -6
  14. package/modules/localmodels/gpu_specs.py +38 -13
  15. package/modules/localmodels/hosts.py +99 -12
  16. package/modules/localmodels/library_cli.py +8 -1
  17. package/modules/localmodels/library_convert.py +34 -0
  18. package/modules/localmodels/library_elastic.py +747 -0
  19. package/modules/localmodels/library_gateway.py +101 -10
  20. package/modules/localmodels/library_jobs.py +16 -7
  21. package/modules/localmodels/library_model.py +101 -4
  22. package/modules/localmodels/library_pricing.py +41 -39
  23. package/modules/localmodels/library_serve.py +322 -58
  24. package/modules/localmodels/library_state.py +35 -1
  25. package/modules/localmodels/library_status.py +113 -6
  26. package/modules/localmodels/llm_rank.py +16 -5
  27. package/modules/localmodels/metal.py +141 -0
  28. package/modules/localmodels/metal_probe.py +167 -0
  29. package/modules/localmodels/plan_envelope.py +4 -1
  30. package/modules/localmodels/probe.py +2 -2
  31. package/modules/localmodels/process_identity_linux.py +39 -0
  32. package/modules/localmodels/recommend.py +6 -1
  33. package/modules/localmodels/remote_ops.py +4 -3
  34. package/modules/localmodels/remote_ops_download.py +37 -24
  35. package/modules/localmodels/remote_ops_mirrors.py +43 -2
  36. package/modules/localmodels/remote_ops_service.py +93 -36
  37. package/modules/localmodels/runtime_auth.py +4 -1
  38. package/modules/localmodels/service_wiring.py +238 -12
  39. package/modules/localmodels/setup_inspection.py +47 -70
  40. package/modules/localmodels/setup_inspection_harness.py +159 -15
  41. package/modules/localmodels/setup_text.py +14 -0
  42. package/modules/localmodels/setup_upgrade.py +1 -1
  43. package/modules/localmodels/source_byok.py +6 -2
  44. package/modules/localmodels/source_byok_probe.py +6 -1
  45. package/modules/localmodels/stack.py +9 -1
  46. package/modules/localmodels/stack_binding.py +3 -35
  47. package/modules/localmodels/stack_cleanup.py +4 -0
  48. package/modules/localmodels/stack_compose.py +24 -3
  49. package/modules/localmodels/stack_hardware.py +3 -1
  50. package/modules/localmodels/stack_lifecycle.py +24 -1
  51. package/modules/localmodels/stack_picks.py +16 -2
  52. package/modules/localmodels/stack_plan.py +6 -2
  53. package/modules/localmodels/stack_ports.py +2 -0
  54. package/modules/localmodels/stack_remove.py +10 -1
  55. package/modules/localmodels/stack_up.py +33 -7
  56. package/modules/localmodels/stack_update.py +3 -1
  57. package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.5.txt} +1 -1
  58. package/modules/localmodels/suite.py +43 -27
  59. package/modules/localmodels/transport.py +13 -2
  60. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/METADATA +1 -1
  61. package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/RECORD +63 -61
  62. package/package.json +1 -1
  63. package/tool.json +1 -1
  64. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
  65. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/WHEEL +0 -0
  66. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/entry_points.txt +0 -0
  67. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/NOTICE +0 -0
  68. /package/modules/{simplex_localmodels-0.1.0.dev57.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -72,6 +72,20 @@ MESSAGES: dict[str, tuple[str, str]] = {
72
72
  "Mac's GPU and unified memory ({apps}). This tool does not count that memory as free; "
73
73
  "quit the app and check again.",
74
74
  ),
75
+ "gpu-inference-app-running": (
76
+ "这台电脑的显卡可以运行本地模型,但其他推理程序或 GPU 任务目前占用了 GPU {index} 的显存"
77
+ "(空闲 {free},安装约需 {needed}:{apps})。请退出该程序后重新检查;本工具不会停止任何进程。",
78
+ "This computer's GPU can run local models, but another inference app or GPU workload is "
79
+ "using GPU {index}'s memory ({free} free; the install needs about {needed}: {apps}). "
80
+ "Quit that app and check again; this tool stops no process.",
81
+ ),
82
+ "gpu-conflict-running": (
83
+ "这台电脑的显卡可以运行本地模型,但其他推理程序或 GPU 任务目前占用了显卡({apps})。"
84
+ "本工具不会把它的显存算作可释放;请退出该程序后重新检查。",
85
+ "This computer's GPU can run local models, but another inference app or GPU workload "
86
+ "holds the GPU ({apps}). This tool does not count that memory as free; quit that app "
87
+ "and check again.",
88
+ ),
75
89
  "cuda-driver-update-required": (
76
90
  "这台电脑的显卡可以运行本地模型,但当前 NVIDIA 驱动支持的 CUDA 版本({detected})低于"
77
91
  "本地模型引擎要求的最低版本(CUDA >= {required})。请更新 NVIDIA 驱动后重新检查。",
@@ -85,7 +85,7 @@ def upgrade_hint(
85
85
  if roomy is None:
86
86
  return None
87
87
  try:
88
- roomy_plan = stack.build(options, facts=roomy)
88
+ roomy_plan = stack.build(options, facts=roomy, min_prompt_cache=True)
89
89
  except (PlanError, StackError, harness.HarnessError):
90
90
  return None
91
91
  live_id = str(live_plan["llm"]["model"]["id"])
@@ -497,13 +497,17 @@ def mount_byok(
497
497
  providers = config.setdefault("providers", {})
498
498
  providers[BYOK_PROVIDER] = render_byok_provider(creds)
499
499
  governance = config.setdefault("governance", {})
500
+ existing_rules = governance.get("routing_rules")
500
501
  rules = [
501
502
  r
502
- for r in (governance.get("routing_rules") or [])
503
- if r.get("id") != bifrost_config.BYOK_RULE
503
+ for r in (existing_rules if isinstance(existing_rules, list) else [])
504
+ if isinstance(r, dict)
505
+ and r.get("id") != bifrost_config.BYOK_RULE
506
+ and r.get("name") != bifrost_config.BYOK_RULE
504
507
  ]
505
508
  rules.append(bifrost_config.byok_rule(creds["model_id"]))
506
509
  governance["routing_rules"] = rules
510
+ bifrost_config.sanitize_governance(config)
507
511
  names = (
508
512
  [creds["model_id"]]
509
513
  if creds["model_id"] == BYOK_MODEL
@@ -31,6 +31,7 @@ _REPLY_FIELD: dict[Protocol, str] = {
31
31
  "anthropic": "content",
32
32
  }
33
33
  _WINDOW_FIELDS = ("context_length", "context_window", "max_input_tokens")
34
+ _USER_AGENT = "localmodels-byok"
34
35
 
35
36
 
36
37
  class ByokModel(TypedDict):
@@ -47,7 +48,11 @@ class _NoRedirect(urllib.request.HTTPRedirectHandler):
47
48
 
48
49
 
49
50
  def _headers(protocol: Protocol, api_key: str) -> dict[str, str]:
50
- headers = {"Accept": "application/json", "Content-Type": "application/json"}
51
+ headers = {
52
+ "Accept": "application/json",
53
+ "Content-Type": "application/json",
54
+ "User-Agent": _USER_AGENT,
55
+ }
51
56
  if protocol == "anthropic":
52
57
  headers["anthropic-version"] = "2023-06-01"
53
58
  if api_key:
@@ -83,7 +83,11 @@ __all__ = [ # this module's API, with the stack_plan names callers reach throug
83
83
 
84
84
 
85
85
  def build(
86
- options: StackOptions, *, facts: HostFacts | None = None, approved: StackPlan | None = None
86
+ options: StackOptions,
87
+ *,
88
+ facts: HostFacts | None = None,
89
+ approved: StackPlan | None = None,
90
+ min_prompt_cache: bool = False,
87
91
  ) -> StackPlan:
88
92
  """Probe this computer now, or take ``facts`` saved earlier, and compose the plan (read-only
89
93
  apart from cached facts). With ``offline`` in the options every file's commit and SHA256 come
@@ -123,6 +127,10 @@ def build(
123
127
  plan = compose(
124
128
  seen, tools, options, resolver=resolver, approved=approved, previous=_attempted
125
129
  )
130
+ elif min_prompt_cache:
131
+ plan = stack_update.with_replaced(
132
+ compose(seen, tools, options, resolver=resolver, min_prompt_cache=True)
133
+ )
126
134
  else:
127
135
  plan = stack_update.with_replaced(compose(seen, tools, options, resolver=resolver))
128
136
  if approved is None and isinstance(plan, dict) and "ram" in raw and "disk" in raw:
@@ -3,7 +3,6 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import hashlib
6
- import json
7
6
  import os
8
7
  import stat
9
8
  import sys
@@ -140,39 +139,6 @@ def _acceptance_ready(plan: StackPlan) -> bool:
140
139
  return bool(view and view["ok"])
141
140
 
142
141
 
143
- def _adopted(plan: StackPlan) -> set[str]:
144
- """The plan's LLM components the library adopted (``library_convert``): from then on the
145
- library loads, unloads, wires and may remove them, so their deployments, gateway route and
146
- pi selection are no longer the stack's to check. The conversion marker names them, and
147
- stays when ``library remove`` deletes the model's record; a converted record (an earlier
148
- one may lack ``stack_provider``: the main LLM's) names them too. Read only; it never
149
- converts."""
150
- from localmodels import library_convert, library_state, stack_verify
151
- from localmodels.library_model import library_id
152
-
153
- try:
154
- marker = json.loads((library_state.root() / library_convert.MARKER).read_text("utf-8"))
155
- except (OSError, ValueError):
156
- return set()
157
- if not isinstance(marker, dict) or marker.get("plan_id") != plan["plan_id"]:
158
- return set()
159
- ids = set(marker.get("adopted") or [])
160
- providers = {
161
- r.get("stack_provider") or harness.LLM_PROVIDER
162
- for r in library_state.records()
163
- if r.get("converted")
164
- }
165
- return {
166
- component
167
- for component, part in stack_verify.parts(plan)
168
- if component in library_convert.STACK_LLMS
169
- and (
170
- library_id(part["model"]["id"], part["model"]["quant"]) in ids
171
- or library_convert.STACK_LLMS[component] in providers
172
- )
173
- }
174
-
175
-
176
142
  def _deployments_ready(
177
143
  plan: StackPlan, owned: hosts.Owned, adopted: frozenset[str] | set[str] = frozenset()
178
144
  ) -> bool:
@@ -445,8 +411,10 @@ def inspect_binding(path: Path, lang: Lang = "zh") -> BindingReport:
445
411
  if not _acceptance_ready(plan):
446
412
  report["reasons"] = [_reason("acceptance-unavailable", lang)]
447
413
  return report
414
+ from localmodels import library_convert
415
+
448
416
  owned = hosts.load_owned(plan["harness"]["tools_dir"])
449
- adopted = _adopted(plan)
417
+ adopted = library_convert.adopted_components(plan)
450
418
  if not _deployments_ready(plan, owned, adopted):
451
419
  report["reasons"] = [_reason("deployment-unavailable", lang)]
452
420
  return report
@@ -272,6 +272,10 @@ def adopted(members: set[str], dry_run: bool, out: Out) -> hosts.Owned:
272
272
  f"- {name}: the manifest named another directory ({entry['deploy_dir']}); this "
273
273
  "installation's record decides where it lives, and that directory is left alone"
274
274
  )
275
+ # Keep the other directory's manifest entry untouched on disk; remove acts on this
276
+ # installation's own record in memory only.
277
+ doc["deployments"][name] = hosts.owned_entry(plan)
278
+ continue
275
279
  if dry_run:
276
280
  doc["deployments"][name] = hosts.owned_entry(plan)
277
281
  else:
@@ -131,6 +131,7 @@ def compose(
131
131
  owned_ram: Callable[[], int] = suite.slice_memory,
132
132
  qa_cpu_decision: bool = False,
133
133
  approved: StackPlan | None = None,
134
+ min_prompt_cache: bool = False,
134
135
  ) -> StackPlan:
135
136
  """The whole-stack plan from facts read now. Pure apart from the Hub lookups in resolver and
136
137
  the local lookups each keyword stands for (tests replace them); who holds a GPU comes from
@@ -171,6 +172,7 @@ def compose(
171
172
  qa_cpu_decision=qa_cpu_decision,
172
173
  approved=approved,
173
174
  check_strata=check_strata,
175
+ min_prompt_cache=min_prompt_cache,
174
176
  )
175
177
  parts["warnings"] = pressure_notes + capped_notes + parts["warnings"]
176
178
  if options.get("route") == "fastest":
@@ -214,6 +216,7 @@ def choose_parts(
214
216
  qa_cpu_decision: bool = False,
215
217
  approved: StackPlan | None = None,
216
218
  check_strata: Callable[[Parts, StackOptions], None] | None = None,
219
+ min_prompt_cache: bool = False,
217
220
  ) -> tuple[Parts, StackOptions]:
218
221
  """The planner's LLM selection and priced parts, shared with read-only upgrade advice.
219
222
 
@@ -265,7 +268,9 @@ def choose_parts(
265
268
  )
266
269
  if parts is None:
267
270
  reads = (resolver, listening, previous, existing, owned_ram)
268
- parts = _llama_parts(facts, options, *reads, qa_cpu_decision, approved)
271
+ parts = _llama_parts(
272
+ facts, options, *reads, qa_cpu_decision, approved, min_prompt_cache=min_prompt_cache
273
+ )
269
274
  parts["warnings"] = passed_over + parts["warnings"]
270
275
  return parts, options
271
276
 
@@ -349,7 +354,12 @@ def _choose_llm(
349
354
  if kept := stack_auto.approved_llama_choice(fitting, approved):
350
355
  return kept[0], placement(kept[1])
351
356
  prefer, ladder = str(options.get("prefer") or "smartest"), llm_rank.mac_ladder(facts)
352
- llm_id, index = llm_rank.choose(fitting, prefer, ladder, fallback_ids=fallback_ids)
357
+ slow_ids = {
358
+ entry_id for (_, tok_s), entry_id, _ in fitting if tok_s < cat.USABLE_FLOOR_TOK_S
359
+ }
360
+ llm_id, index = llm_rank.choose(
361
+ fitting, prefer, ladder, fallback_ids=fallback_ids, slow_ids=slow_ids
362
+ )
353
363
  return llm_id, placement(index)
354
364
  where = (
355
365
  f"GPU {gpu}"
@@ -435,6 +445,8 @@ def _llama_parts(
435
445
  owned_ram: Callable[[], int],
436
446
  qa_cpu_decision: bool,
437
447
  approved: StackPlan | None = None,
448
+ *,
449
+ min_prompt_cache: bool = False,
438
450
  ) -> Parts:
439
451
  """A catalog llama.cpp LLM, the decision model on its card, the auxiliaries in the RAM left.
440
452
  On unified memory the foundations ``--aux`` named are priced first: the LLM, the decision
@@ -530,6 +542,15 @@ def _llama_parts(
530
542
  opts = stack_suite.suite_options(options)
531
543
  candidates, llm = aux_gpu.place(facts, llm, choice, candidates, opts, price_llm, warnings)
532
544
  approved_mib = llm_ram.approved_cache_mib(approved.get("llm") if approved else None, llm)
545
+ ram_posture = posture
546
+ if min_prompt_cache:
547
+ floor = (
548
+ int(str(llm["launch"].get("cache_floor_bytes") or 0)) if hardware.on_metal(llm) else 0
549
+ )
550
+ min_mib = min(
551
+ posture.prompt_cache_mib, -(-floor >> 20) if floor else posture.prompt_cache_min_mib
552
+ )
553
+ ram_posture = replace(posture, prompt_cache_mib=min_mib, prompt_cache_min_mib=min_mib)
533
554
  aux, spill = stack_suite.fit_llama_ram(
534
555
  facts,
535
556
  options,
@@ -539,7 +560,7 @@ def _llama_parts(
539
560
  entries,
540
561
  (running_llm is not None, held, available),
541
562
  warnings,
542
- posture=posture,
563
+ posture=ram_posture,
543
564
  approved_mib=approved_mib,
544
565
  )
545
566
  return {
@@ -302,7 +302,9 @@ def llm_budget(
302
302
  uma=on_mac,
303
303
  gpu_name=gpu["name"],
304
304
  platform=facts.get("platform", ""),
305
- gpu_bandwidth_gb_s=None if on_mac else gpu_specs.bandwidth_gb_s(gpu["name"]),
305
+ gpu_bandwidth_gb_s=gpu_specs.bandwidth_gb_s(
306
+ gpu["name"], total_bytes=facts["ram"]["total_bytes"] if on_mac else None
307
+ ),
306
308
  )
307
309
  return budget, reserve
308
310
 
@@ -69,6 +69,25 @@ def _run(argv: list[str]) -> str:
69
69
  return out.stdout.strip() if out.returncode == 0 else ""
70
70
 
71
71
 
72
+ def _systemd_unit_elsewhere(plan: Plan) -> bool:
73
+ """True when the systemd unit for ``plan`` runs another deployment's script or loads from
74
+ another unit file, so status/doctor/deployment_pids never impersonate another install."""
75
+ svc = plan["service"]
76
+ unit = f"{svc['name']}.service"
77
+ unit_path = Path(os.path.expanduser(f"~/.config/systemd/user/{unit}"))
78
+ script = str(Path(os.path.expanduser(svc["deploy_dir"])) / "run.sh")
79
+ if unit_path.is_symlink():
80
+ return True
81
+ try:
82
+ text = unit_path.read_text(encoding="utf-8")
83
+ except OSError:
84
+ text = None
85
+ if text is not None and f"\nExecStart={script}\n" not in text:
86
+ return True
87
+ fragment = _run(["systemctl", "--user", "show", "-p", "FragmentPath", "--value", unit])
88
+ return bool(fragment and Path(fragment).resolve() != unit_path.resolve())
89
+
90
+
72
91
  def _service(plan: Plan) -> tuple[str, int | None]:
73
92
  if not sys.platform.startswith("linux") and sys.platform not in ("darwin", "win32"):
74
93
  return "unknown", None
@@ -76,6 +95,8 @@ def _service(plan: Plan) -> tuple[str, int | None]:
76
95
  if svc["kind"] == "launchd-user":
77
96
  return remote_ops_launchd.status(svc["deploy_dir"])
78
97
  if svc["kind"] == "systemd-user":
98
+ if _systemd_unit_elsewhere(plan):
99
+ return "inactive", None
79
100
  unit = f"{svc['name']}.service"
80
101
  state = harness.run_tool(["systemctl", "--user", "is-active", unit], timeout=10)
81
102
  pid = _run(["systemctl", "--user", "show", "-p", "MainPID", "--value", unit])
@@ -374,7 +395,9 @@ def service_remove(
374
395
  params["purge"] = [path for path, _, _ in found]
375
396
  result = _act(executor, params)
376
397
  if result.get("event") == "result":
377
- hosts.delete_record(dev_id, name, purged=purge)
398
+ hosts.delete_record(
399
+ dev_id, name, purged=purge, deploy_dir=record["plan"]["service"]["deploy_dir"]
400
+ )
378
401
  return result
379
402
 
380
403
 
@@ -86,6 +86,7 @@ def picks(cards: Sequence[CardFits], ladder: llm_rank.MacLadder | None = None) -
86
86
  p["quality"]
87
87
  for p in found.values()
88
88
  if p["decode_tok_s"] is not None
89
+ and p["decode_tok_s"] >= cat.USABLE_FLOOR_TOK_S
89
90
  and p["id"] not in strata_ids
90
91
  and not p.get("candidate_fallback")
91
92
  ]
@@ -108,14 +109,27 @@ def picks(cards: Sequence[CardFits], ladder: llm_rank.MacLadder | None = None) -
108
109
 
109
110
  ranked = [((p["quality"], _smart_tie(p)), p["id"], p["card"]) for p in eligible]
110
111
  fallback_ids = {p["id"] for p in eligible if p.get("candidate_fallback")}
111
- smartest = found[llm_rank.choose(ranked, "smartest", ladder, fallback_ids=fallback_ids)[0]]
112
+ slow_ids = {
113
+ p["id"]
114
+ for p in eligible
115
+ if p["id"] not in strata_ids
116
+ and p["decode_tok_s"] is not None
117
+ and p["decode_tok_s"] < cat.USABLE_FLOOR_TOK_S
118
+ }
119
+ smartest = found[
120
+ llm_rank.choose(ranked, "smartest", ladder, fallback_ids=fallback_ids, slow_ids=slow_ids)[0]
121
+ ]
112
122
  llama_ranked = [
113
123
  ((p["quality"], float(p["decode_tok_s"])), p["id"], p["card"])
114
124
  for p in eligible
115
125
  if p["id"] not in strata_ids and p["decode_tok_s"] is not None
116
126
  ]
117
127
  fastest = (
118
- found[llm_rank.choose(llama_ranked, "fastest", ladder, fallback_ids=fallback_ids)[0]]
128
+ found[
129
+ llm_rank.choose(
130
+ llama_ranked, "fastest", ladder, fallback_ids=fallback_ids, slow_ids=slow_ids
131
+ )[0]
132
+ ]
119
133
  if llama_ranked
120
134
  else smartest
121
135
  )
@@ -544,8 +544,12 @@ def own_name(model_id: str, port: int, base_dir: str) -> str:
544
544
 
545
545
 
546
546
  def is_redeploy(plan: Plan) -> bool:
547
- """A deployment directory with this plan's name is a previous run of the same component."""
548
- return Path(os.path.expanduser(plan["service"]["deploy_dir"]), "deployment.json").is_file()
547
+ """A deployment directory with this plan's name is a previous run of the same component,
548
+ provided another live controller deployment does not already own its port."""
549
+ svc = plan["service"]
550
+ if hosts.port_owned_elsewhere(svc["port"], svc["deploy_dir"]):
551
+ return False
552
+ return Path(os.path.expanduser(svc["deploy_dir"]), "deployment.json").is_file()
549
553
 
550
554
 
551
555
  def reuse_copies(
@@ -103,6 +103,8 @@ def failed_own_port(model_ids: Sequence[str], base_dir: str) -> int | None:
103
103
  continue
104
104
  if record["ok"] or not (directory / "deployment.json").is_file():
105
105
  return None
106
+ if hosts.port_owned_elsewhere(int(service["port"]), service["deploy_dir"]):
107
+ return None
106
108
  return int(service["port"])
107
109
  return None
108
110
 
@@ -187,7 +187,9 @@ def remove_services(
187
187
  {"check": name, "ok": ok, "detail": done if ok else str(result.get("message"))}
188
188
  )
189
189
  if ok:
190
- hosts.delete_record(hosts.LOCAL_ID, name, purged=not kept)
190
+ hosts.delete_record(
191
+ hosts.LOCAL_ID, name, purged=not kept, deploy_dir=entry["deploy_dir"]
192
+ )
191
193
  return checks
192
194
 
193
195
 
@@ -332,6 +334,13 @@ def run_remove(
332
334
  serve_log = str(hosts.owned_path().parent / "magpie-serve.log")
333
335
  keep = in_use(hosts.records(hosts.LOCAL_ID), selected)
334
336
  keep |= {f for n, d in doc["deployments"].items() if n not in selected for f in d["files"]}
337
+ keep |= {
338
+ f
339
+ for n, d in hosts.load_owned()["deployments"].items()
340
+ if not d["removed"]
341
+ and (n not in entries or not hosts._same_place(d["deploy_dir"], entries[n]["deploy_dir"]))
342
+ for f in d["files"]
343
+ }
335
344
  found = list_files(executor, entries, plans, keep, purge, act=act)
336
345
  found += stack_cleanup.local_listing(
337
346
  [*doc["archives"], serve_log, *([str(profile)] if profile else [])]
@@ -83,12 +83,26 @@ def _accepted(plan_id: str | None = None) -> StackPlan | None:
83
83
  return None
84
84
 
85
85
 
86
- def drift(plan: StackPlan) -> list[str]:
87
- """Why the deployments on this computer are no longer ``plan``'s; empty: they are."""
86
+ def library_parts(plan: StackPlan) -> set[str]:
87
+ """The deployment names of ``plan``'s LLMs the model library adopted (the rule setup binding
88
+ uses, library_convert.adopted_components): the library loads, unloads and removes them, so
89
+ ``library unload`` (Linger runs it on quit and before a kit update) deletes their records. They are the library's to start, not ``stack
90
+ up``'s, and their records missing is not drift."""
91
+ from localmodels import library_convert, stack_verify
92
+
93
+ adopted = library_convert.adopted_components(plan)
94
+ return {part["name"] for component, part in stack_verify.parts(plan) if component in adopted}
95
+
96
+
97
+ def drift(plan: StackPlan, library: set[str] | frozenset[str] = frozenset()) -> list[str]:
98
+ """Why the deployments on this computer are no longer ``plan``'s; empty: they are. Parts in
99
+ ``library`` (library_parts) are not checked."""
88
100
  records = {r["plan"]["name"]: r for r in hosts.records(hosts.LOCAL_ID)}
89
101
  owned = hosts.load_owned(plan["harness"]["tools_dir"])["deployments"]
90
102
  found = []
91
103
  for part in deployments(plan):
104
+ if part["name"] in library:
105
+ continue
92
106
  record, entry = records.get(part["name"]), owned.get(part["name"])
93
107
  if record is None or (entry is not None and entry["removed"]):
94
108
  found.append(f"{part['name']} was removed")
@@ -211,7 +225,8 @@ def up(
211
225
  ) -> UpReport:
212
226
  if sys.platform != "darwin" and (error := platform_error(sys.platform)):
213
227
  raise StackError(error)
214
- if moved := drift(plan):
228
+ library = library_parts(plan)
229
+ if moved := drift(plan, library):
215
230
  raise StackError(
216
231
  "the deployments on this computer no longer match this plan ("
217
232
  + ", ".join(moved)
@@ -219,7 +234,7 @@ def up(
219
234
  )
220
235
  try:
221
236
  with hosts.stack_apply_lock():
222
- report = _up(plan, share_gpu, timeout, out)
237
+ report = _up(plan, share_gpu, timeout, out, library)
223
238
  except hosts.LockedError as exc:
224
239
  raise StackError("another stack apply is running") from exc
225
240
  if report["ok"]:
@@ -227,9 +242,20 @@ def up(
227
242
  return report
228
243
 
229
244
 
230
- def _up(plan: StackPlan, share_gpu: bool, timeout: float, out: Out) -> UpReport:
231
- parts = deployments(plan) # the LLM first: Strata sizes its expert cache on an empty card
232
- notes: list[str] = []
245
+ def _up(
246
+ plan: StackPlan,
247
+ share_gpu: bool,
248
+ timeout: float,
249
+ out: Out,
250
+ library: set[str] | frozenset[str] = frozenset(),
251
+ ) -> UpReport:
252
+ # The LLM first: Strata sizes its expert cache on an empty card.
253
+ parts = [p for p in deployments(plan) if p["name"] not in library]
254
+ notes: list[str] = [
255
+ f"{name} belongs to the model library, which loads it (library load or source apply); "
256
+ "stack up does not start it"
257
+ for name in sorted(library)
258
+ ]
233
259
  if outside := plan["decision_existing"]:
234
260
  notes.append(
235
261
  f"the decision model uses the external service {outside['url']}, "
@@ -432,7 +432,9 @@ def retire(names: list[str]) -> list[str]:
432
432
  hosts.own_deployment(record["plan"]) # a record from before the manifest
433
433
  result = remove(lifecycle.plan_params(record["plan"]))
434
434
  if result.get("event") == "result":
435
- hosts.delete_record(hosts.LOCAL_ID, name)
435
+ hosts.delete_record(
436
+ hosts.LOCAL_ID, name, deploy_dir=record["plan"]["service"]["deploy_dir"]
437
+ )
436
438
  done.append(f"retired {name} (model and logs kept)")
437
439
  else:
438
440
  failed.append(f"{name}: {str(result.get('message') or 'remove failed')[:200]}")
@@ -1,4 +1,4 @@
1
- # PolyStrata 0.2.19-poly.1's Python server (terminal/serve/server.py, MIT) for strata-poly LLM
1
+ # PolyStrata 0.2.20-poly.5's Python server (terminal/serve/server.py, MIT) for strata-poly LLM
2
2
  # recipes: jinja2 3.1.6 (BSD-3-Clause) with markupsafe 3.0.3 (BSD-3-Clause) renders the chat
3
3
  # template, regex 2026.9.10 (Apache-2.0 and CNRI-Python) drives its tokenizer, psutil 7.2.2
4
4
  # (BSD-3-Clause) reads memory for its status page, and pillow (MIT-CMU; 13.0.0 on Python 3.11+,
@@ -20,7 +20,7 @@ import sys
20
20
  import urllib.parse
21
21
  from dataclasses import dataclass, field
22
22
  from pathlib import Path
23
- from typing import TypedDict, cast
23
+ from typing import Any, TypedDict, cast
24
24
 
25
25
  from localmodels import catalog as cat
26
26
  from localmodels import hosts, reuse, vision
@@ -303,6 +303,47 @@ def _plan_files(
303
303
  return files
304
304
 
305
305
 
306
+ def _profile_template(
307
+ facts: HostFacts,
308
+ r: SuiteRecipe,
309
+ options: SuiteOptions,
310
+ files: list[ReusableFile],
311
+ values: dict[str, str],
312
+ reader: str,
313
+ ) -> dict[str, Any]:
314
+ """Build the rendered Strata/PolyStrata ``strata-profile.json`` template."""
315
+ profile_template = dict(r.get("profile") or {})
316
+ if reader != "off":
317
+ projector = next(f for f in files if f["local_name"] == r["vision"]["mmproj"])
318
+ values["vision_mmproj"] = projector["dest"]
319
+ cores = int(facts.get("cpu", {}).get("logical_cores") or 2)
320
+ profile_template["vision"] = vision.strata_section(reader, cores, exe="{vision_exe}")
321
+ if r["runtime"] == "strata":
322
+ profile_template["args"] = [*cast("list[str]", profile_template["args"]), "--vision"]
323
+ if options.gpu and r.get("card_args"):
324
+ # Under --gpu-memory the reserve also holds what the share leaves out of the real card
325
+ # (stack_gpu_memory.LEFT_OUT, stack_suite.poly_reserve_mib), so the room is counted on it.
326
+ left_out = int(cast("dict[str, int]", options.gpu).get("share_left_out_bytes", 0))
327
+ room = options.gpu["total_bytes"] + left_out - (options.vram_reserve_mib << 20)
328
+ profile_template["args"] = [
329
+ *cast("list[str]", profile_template["args"]),
330
+ *(
331
+ a
332
+ for group in r["card_args"]
333
+ if room >= group["at_least_bytes"]
334
+ and facts["platform"] in group.get("platforms", [facts["platform"]])
335
+ for a in group["args"]
336
+ ),
337
+ ]
338
+ if options.reasoning_budget and r["runtime"] == "strata":
339
+ # strata-<model>.json's default for requests that name none (Strata DETAILS, v0.2.4).
340
+ profile_template["reasoning_budget_tokens"] = options.reasoning_budget
341
+ if r["runtime"] == "strata-poly":
342
+ # PolyStrata's server enables prompt-start warm-up only when opt-in warm_start is true.
343
+ profile_template.setdefault("warm_start", True)
344
+ return profile_template
345
+
346
+
306
347
  def build_plan(host_id: str, facts: HostFacts, r: SuiteRecipe, options: SuiteOptions) -> Plan:
307
348
  """The deployment plan for one suite component from its catalog template."""
308
349
  base = options.base_dir.rstrip("/")
@@ -344,33 +385,8 @@ def build_plan(host_id: str, facts: HostFacts, r: SuiteRecipe, options: SuiteOpt
344
385
  }
345
386
  parking = r.get("conversation_cache")
346
387
  parking_mib = options.conversation_cache_mib if parking else 0
347
- profile_template = dict(r.get("profile") or {})
348
388
  reader_ram_mib = vision.strata_ram_mib(r.get("vision") or {}, reader)
349
- if reader != "off":
350
- projector = next(f for f in files if f["local_name"] == r["vision"]["mmproj"])
351
- values["vision_mmproj"] = projector["dest"]
352
- cores = int(facts.get("cpu", {}).get("logical_cores") or 2)
353
- profile_template["vision"] = vision.strata_section(reader, cores, exe="{vision_exe}")
354
- if r["runtime"] == "strata":
355
- profile_template["args"] = [*cast("list[str]", profile_template["args"]), "--vision"]
356
- if options.gpu and r.get("card_args"):
357
- # Under --gpu-memory the reserve also holds what the share leaves out of the real card
358
- # (stack_gpu_memory.LEFT_OUT, stack_suite.poly_reserve_mib), so the room is counted on it.
359
- left_out = int(cast("dict[str, int]", options.gpu).get("share_left_out_bytes", 0))
360
- room = options.gpu["total_bytes"] + left_out - (options.vram_reserve_mib << 20)
361
- profile_template["args"] = [
362
- *cast("list[str]", profile_template["args"]),
363
- *(
364
- a
365
- for group in r["card_args"]
366
- if room >= group["at_least_bytes"]
367
- and facts["platform"] in group.get("platforms", [facts["platform"]])
368
- for a in group["args"]
369
- ),
370
- ]
371
- if options.reasoning_budget and r["runtime"] == "strata":
372
- # strata-<model>.json's default for requests that name none (Strata DETAILS, v0.2.4).
373
- profile_template["reasoning_budget_tokens"] = options.reasoning_budget
389
+ profile_template = _profile_template(facts, r, options, files, values, reader)
374
390
  if parking:
375
391
  values |= {
376
392
  "conversation_cache_mib": str(parking_mib),
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  import base64
12
12
  import json
13
+ import os
13
14
  import shlex
14
15
  import subprocess
15
16
  import sys
@@ -136,8 +137,9 @@ class Executor:
136
137
  script source as ``_PARAMS_B64``, never on a command line. ``on_line`` receives stdout lines
137
138
  as they arrive; long actions report progress that way."""
138
139
  source = (PACKAGE_DIR / script).read_bytes()
140
+ parent_pid = os.getpid() if self.is_local and on_line is not None else None
139
141
  if script in BUNDLES:
140
- source = self._bundle_source(script, source, params)
142
+ source = self._bundle_source(script, source, params, parent_pid=parent_pid)
141
143
  elif params is not None:
142
144
  encoded = base64.b64encode(json.dumps(params).encode()).decode()
143
145
  # Compile separately so the payload does not precede a future import.
@@ -161,7 +163,14 @@ class Executor:
161
163
  )
162
164
  return stream(argv, source, on_line)
163
165
 
164
- def _bundle_source(self, script: str, entry: bytes, params: object) -> bytes:
166
+ def _bundle_source(
167
+ self,
168
+ script: str,
169
+ entry: bytes,
170
+ params: object,
171
+ *,
172
+ parent_pid: int | None = None,
173
+ ) -> bytes:
165
174
  """The payload for a BUNDLES script: a stub ``localmodels`` package plus a meta-path
166
175
  loader that executes each sibling from the embedded sources, then the entry module as
167
176
  ``__main__`` registered under its package name. ``params`` land in the entry's globals
@@ -198,6 +207,8 @@ class Executor:
198
207
  f"_REQUEST_ID = {request_id(REQUEST_ID.get())!r}",
199
208
  "_mod.__dict__.update({'_PARAMS_B64': _PARAMS_B64, '_REQUEST_ID': _REQUEST_ID})",
200
209
  ]
210
+ if parent_pid is not None:
211
+ lines.append(f"_mod.__dict__['_PARENT_PID'] = {parent_pid!r}")
201
212
  lines.append(
202
213
  f"exec(compile({entry!r}, {str(PACKAGE_DIR / script)!r}, 'exec'), _mod.__dict__)"
203
214
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: simplex-localmodels
3
- Version: 0.1.0.dev57
3
+ Version: 0.1.0.dev59
4
4
  Summary: Detect hardware, recommend and install a verified local model stack
5
5
  License-Expression: LicenseRef-Proprietary
6
6
  License-File: NOTICE