@simplexai/localmodels-linux-arm64 0.1.0-dev.103 → 0.1.0-dev.104

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 (139) hide show
  1. package/LICENSE +201 -0
  2. package/{modules/simplex_localmodels-0.1.0.dev103.dist-info/licenses/NOTICE → NOTICE} +42 -13
  3. package/README.md +10 -0
  4. package/bootstrap.identity +1 -1
  5. package/bootstrap.sha256 +126 -127
  6. package/modules/localmodels/__init__.py +1 -1
  7. package/modules/localmodels/catalog.json +130 -127
  8. package/modules/localmodels/catalog.py +7 -3
  9. package/modules/localmodels/catalog_recipes.py +3 -3
  10. package/modules/localmodels/cli_parser.py +3 -3
  11. package/modules/localmodels/component.py +1 -1
  12. package/modules/localmodels/console.py +1 -1
  13. package/modules/localmodels/context_policy.py +6 -5
  14. package/modules/localmodels/debug_cli.py +0 -12
  15. package/modules/localmodels/debug_mode.py +0 -6
  16. package/modules/localmodels/decode_calibration.json +3 -4
  17. package/modules/localmodels/decode_calibration.py +5 -2
  18. package/modules/localmodels/deployment_lifecycle.py +1 -1
  19. package/modules/localmodels/download-mirrors.json +1 -1
  20. package/modules/localmodels/engine_adapters/base.py +11 -1
  21. package/modules/localmodels/engine_adapters/strata_poly.py +65 -3
  22. package/modules/localmodels/engine_adapters/suite_plan.py +57 -20
  23. package/modules/localmodels/engines-b11583.json +6 -26
  24. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +3 -15
  25. package/modules/localmodels/engines-b12757-mix-ef2df21.json +3 -15
  26. package/modules/localmodels/engines-prism-b12178-03ec600.json +3 -15
  27. package/modules/localmodels/engines-speechcpp-v0.11.3.json +4 -20
  28. package/modules/localmodels/engines-strata-0.1.47.json +1 -5
  29. package/modules/localmodels/engines-strata-0.1.49.2.json +1 -5
  30. package/modules/localmodels/engines-strata-0.1.59.1.json +1 -5
  31. package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +6 -30
  32. package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +129 -0
  33. package/modules/localmodels/engines-whisper-b5454.json +6 -30
  34. package/modules/localmodels/engines.json +13 -61
  35. package/modules/localmodels/estimator.py +10 -5
  36. package/modules/localmodels/gpu_specs.py +1 -1
  37. package/modules/localmodels/hosts.py +12 -16
  38. package/modules/localmodels/kokoro-tts-0.6.1.txt +1 -1
  39. package/modules/localmodels/library_elastic.py +135 -6
  40. package/modules/localmodels/library_kept.py +9 -1
  41. package/modules/localmodels/library_model.py +28 -1
  42. package/modules/localmodels/library_poly.py +109 -11
  43. package/modules/localmodels/library_pricing.py +12 -3
  44. package/modules/localmodels/library_serve.py +134 -67
  45. package/modules/localmodels/library_smoke.py +63 -5
  46. package/modules/localmodels/library_state.py +3 -2
  47. package/modules/localmodels/library_status.py +8 -1
  48. package/modules/localmodels/llm_rank.py +13 -8
  49. package/modules/localmodels/metal.py +1 -2
  50. package/modules/localmodels/plan_envelope.py +29 -11
  51. package/modules/localmodels/planning/budget.py +14 -12
  52. package/modules/localmodels/planning/memory_pools.py +7 -1
  53. package/modules/localmodels/privacy_acceptance.py +6 -5
  54. package/modules/localmodels/py.typed +0 -0
  55. package/modules/localmodels/quant_formats.py +1 -1
  56. package/modules/localmodels/recommend_cli.py +1 -1
  57. package/modules/localmodels/remote_ops_launchd.py +8 -1
  58. package/modules/localmodels/runtime_process.py +1 -1
  59. package/modules/localmodels/service_deployment.py +2 -4
  60. package/modules/localmodels/service_probe.py +59 -13
  61. package/modules/localmodels/setup_inspection.py +72 -70
  62. package/modules/localmodels/setup_text.py +7 -56
  63. package/modules/localmodels/sidecar_downloads.py +34 -0
  64. package/modules/localmodels/sidecar_http.py +61 -5
  65. package/modules/localmodels/sidecar_state.py +52 -2
  66. package/modules/localmodels/speech_admission.py +20 -4
  67. package/modules/localmodels/speech_catalog.py +23 -0
  68. package/modules/localmodels/speech_cli.py +10 -2
  69. package/modules/localmodels/speech_jobs.py +42 -17
  70. package/modules/localmodels/speech_server.py +182 -81
  71. package/modules/localmodels/speech_state.py +4 -1
  72. package/modules/localmodels/speech_workers.py +11 -0
  73. package/modules/localmodels/stack.py +1 -1
  74. package/modules/localmodels/stack_args.py +6 -6
  75. package/modules/localmodels/stack_auto.py +1 -1
  76. package/modules/localmodels/stack_aux_gpu.py +1 -1
  77. package/modules/localmodels/stack_cleanup.py +21 -18
  78. package/modules/localmodels/stack_cli.py +6 -2
  79. package/modules/localmodels/stack_compose.py +11 -4
  80. package/modules/localmodels/stack_debug.py +1 -2
  81. package/modules/localmodels/stack_decision.py +4 -4
  82. package/modules/localmodels/stack_doctor.py +2 -2
  83. package/modules/localmodels/stack_events.py +1 -1
  84. package/modules/localmodels/stack_gpu_memory.py +1 -1
  85. package/modules/localmodels/stack_hardware.py +3 -3
  86. package/modules/localmodels/stack_mcp.py +1 -2
  87. package/modules/localmodels/stack_picks.py +1 -1
  88. package/modules/localmodels/stack_plan.py +9 -9
  89. package/modules/localmodels/stack_ports.py +31 -4
  90. package/modules/localmodels/stack_rollback.py +1 -1
  91. package/modules/localmodels/stack_run.py +1 -1
  92. package/modules/localmodels/stack_suite.py +61 -12
  93. package/modules/localmodels/stack_view_agent.py +1 -1
  94. package/modules/localmodels/stack_view_serve.py +0 -2
  95. package/modules/localmodels/stack_view_words.py +2 -2
  96. package/modules/localmodels/stack_warm.py +2 -2
  97. package/modules/localmodels/stack_whatif.py +524 -41
  98. package/modules/localmodels/stack_whatif_html.py +903 -0
  99. package/modules/localmodels/startlux-decide-83fe6c7d.txt +2 -2
  100. package/modules/localmodels/{strata-poly-serve-0.2.20-poly.7.txt → strata-poly-serve-0.2.20-poly.9.txt} +1 -1
  101. package/modules/localmodels/strata_poly_server.py +114 -3
  102. package/modules/localmodels/suite.py +137 -5
  103. package/modules/localmodels/tts_admission.py +2 -17
  104. package/modules/localmodels/tts_catalog.py +29 -1
  105. package/modules/localmodels/tts_cli.py +23 -4
  106. package/modules/localmodels/tts_http.py +10 -4
  107. package/modules/localmodels/tts_jobs.py +49 -19
  108. package/modules/localmodels/tts_server.py +1 -1
  109. package/modules/localmodels/tts_sidecar.py +66 -28
  110. package/modules/localmodels/tts_state.py +7 -2
  111. package/modules/localmodels/vision.py +5 -3
  112. package/modules/localmodels/web/view/ASSET-SOURCES.md +4 -7
  113. package/modules/localmodels/web/view/view.css +0 -1
  114. package/modules/localmodels/web/view/view.js +2 -5
  115. package/modules/localmodels/web/whatif/app.js +730 -0
  116. package/modules/localmodels/web/whatif/page.html +1172 -0
  117. package/modules/localmodels/web/whatif/sim.js +303 -0
  118. package/modules/localmodels/windows_job.py +179 -11
  119. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/METADATA +14 -0
  120. package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/RECORD +118 -114
  121. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/LICENSE +201 -0
  122. package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/NOTICE +126 -0
  123. package/package.json +11 -2
  124. package/tool.json +1 -1
  125. package/modules/localmodels/engines-strata-poly-0.2.20-poly.7.json +0 -94
  126. package/modules/localmodels/fixtures/stack-research-demo-plan.json +0 -1059
  127. package/modules/localmodels/stack_research.py +0 -716
  128. package/modules/localmodels/stack_research_demo.py +0 -125
  129. package/modules/localmodels/stack_research_plan.py +0 -146
  130. package/modules/localmodels/web/index.html +0 -2605
  131. package/modules/localmodels/web/sizecalc/app.js +0 -1306
  132. package/modules/localmodels/web/sizecalc/calc.js +0 -269
  133. package/modules/localmodels/web/sizecalc/page.html +0 -520
  134. package/modules/localmodels/web/view/logo-claude.svg +0 -3
  135. package/modules/localmodels/web/view/logo-codex.png +0 -0
  136. package/modules/simplex_localmodels-0.1.0.dev103.dist-info/METADATA +0 -9
  137. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/WHEEL +0 -0
  138. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/entry_points.txt +0 -0
  139. /package/modules/{simplex_localmodels-0.1.0.dev103.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -22,11 +22,15 @@ from __future__ import annotations
22
22
 
23
23
  import re
24
24
  from dataclasses import dataclass, replace
25
- from typing import Literal
26
25
 
27
26
  from localmodels import gpu_specs, metal
28
27
  from localmodels.context_policy import RUNTIME_OVERHEAD_BYTES
29
- from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES, METAL_VRAM_RESERVE_BYTES, HardwareBudget
28
+ from localmodels.estimator import (
29
+ AGENT_VRAM_RESERVE_BYTES,
30
+ METAL_VRAM_RESERVE_BYTES,
31
+ HardwareBudget,
32
+ )
33
+ from localmodels.estimator import Backend as Backend
30
34
  from localmodels.probe import GPU, ComputeProcess, HostFacts
31
35
 
32
36
  _GIB = 1 << 30
@@ -38,7 +42,9 @@ _LAUNCH_HEADROOM = 1 << 30
38
42
  # Unified memory (a Mac, an integrated CUDA device, CPU RAM) keeps this share back from models.
39
43
  UMA_HEADROOM_FRACTION = 0.20
40
44
  _POOL_DISAGREEMENT_FACTOR = 1.5
41
- _POOL_RAM_FRACTION = 0.75
45
+ # Without the driver's INTEGRATED attribute, a CUDA pool at least this share of physical RAM (and
46
+ # well above nvidia-smi's total) is unified memory behind a carve-out (unified_pool_bytes).
47
+ _UNIFIED_POOL_MIN_RAM_SHARE = 0.75
42
48
  # A card whose free memory is below this share of its total holds someone else's work.
43
49
  BUSY_GPU_FRACTION = 0.10 # another program holding more of a card than this needs consent
44
50
  IDLE_USED_BYTES = 1 << 30 # what an idle card's driver context may hold
@@ -56,16 +62,12 @@ _SERVING_IMAGE_RE = re.compile(
56
62
  )
57
63
  # A Windows GPU context named like one of these is another inference server. Any other one (the
58
64
  # desktop, a game, a browser, an app that uses CUDA) is not a conflict: only the free memory
59
- # decides whether a model fits beside it (roadmap decision 60).
65
+ # decides whether a model fits beside it.
60
66
  _SERVING_PROCESS_RE = re.compile(
61
67
  _SERVING_IMAGE_RE.pattern + r"|lm.?studio|lms\b|kobold", re.IGNORECASE
62
68
  )
63
69
 
64
70
 
65
- # The device a placement runs on; engine_adapters.llama_cpp.backend_for keys its hooks on it.
66
- Backend = Literal["cuda", "metal", "cpu"]
67
-
68
-
69
71
  @dataclass(frozen=True)
70
72
  class Placement:
71
73
  """Where one model would run: one card, every card split by layer, or the host's unified pool."""
@@ -135,7 +137,7 @@ def unified_pool_bytes(facts: HostFacts) -> int | None:
135
137
  smi_total > 0
136
138
  and total >= int(smi_total * _POOL_DISAGREEMENT_FACTOR)
137
139
  and ram_total > 0
138
- and total >= int(ram_total * _POOL_RAM_FRACTION)
140
+ and total >= int(ram_total * _UNIFIED_POOL_MIN_RAM_SHARE)
139
141
  ):
140
142
  return total
141
143
  return None
@@ -219,7 +221,7 @@ def gpu_conflicts(facts: HostFacts) -> dict[str, list[str]]:
219
221
  def foreign_work(proc: ComputeProcess, facts: HostFacts) -> bool:
220
222
  """A compute process this tool does not own that holds a card for someone else: any such
221
223
  process, its owner known or not, except on Windows, where only an inference server counts
222
- (``_SERVING_PROCESS_RE``); every other WDDM context is the desktop's (roadmap decision 60)."""
224
+ (``_SERVING_PROCESS_RE``); every other WDDM context is the desktop's."""
223
225
  if proc["owned"] is True:
224
226
  return False
225
227
  return facts.get("platform") != "win32" or bool(_SERVING_PROCESS_RE.search(proc["name"]))
@@ -232,7 +234,7 @@ def holders(facts: HostFacts) -> dict[str, list[str]]:
232
234
  found: dict[str, list[str]] = {}
233
235
  # A desktop always draws on its card (WDDM's desktop, Xorg, gnome-shell, browsers, games);
234
236
  # with no foreign compute work there, that memory is the desktop's, and the plan prices only
235
- # what is free (roadmap decision 60). Inside a container other namespaces' processes are
237
+ # what is free. Inside a container other namespaces' processes are
236
238
  # invisible, so memory held there still counts as someone's work.
237
239
  desktop = facts.get("services") is not None and facts.get("environment") != "container"
238
240
  for g in facts.get("gpus") or []:
@@ -312,7 +314,7 @@ def idle_cards(facts: HostFacts, need_bytes: int) -> list[GPU]:
312
314
 
313
315
  def sharing_cards(facts: HostFacts, need_bytes: int) -> list[GPU]:
314
316
  """NVIDIA cards with ``need_bytes`` free, only for an explicit sharing consent. Who else uses
315
- a card, known or not, does not matter there: the free memory decides (roadmap decision 60)."""
317
+ a card, known or not, does not matter there: the free memory decides."""
316
318
  nvidia = [g for g in facts.get("gpus") or [] if g["vendor"] == "nvidia"]
317
319
  unified_uuid = (
318
320
  nvidia[0]["uuid"] if len(nvidia) > 1 and unified_pool_bytes(facts) is not None else None
@@ -24,7 +24,8 @@ from localmodels.planning import budget
24
24
  from localmodels.probe import GPU, HostFacts
25
25
  from localmodels.records import Plan
26
26
 
27
- POOL_RAM_FRACTION = 0.8 # a "system" pool's budget: RAM x 0.8 (contract v2)
27
+ # A "system" pool's budget: RAM less the unified-memory headroom, RAM x 0.8 (contract v2).
28
+ POOL_RAM_FRACTION = 1 - budget.UMA_HEADROOM_FRACTION
28
29
  UNIFIED_RESERVE_BYTES = metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
29
30
 
30
31
 
@@ -215,6 +216,11 @@ def live(
215
216
  else unified_delta
216
217
  )
217
218
  ram["wired_bytes"] = max(0, min(ram["total_bytes"], wired_ram + wired_delta))
219
+ if unified_delta < 0 and ram.get("pressure_level") == metal.PRESSURE_WARN:
220
+ # Reclaiming a resident Metal model clears the WARN pressure it caused, allowing
221
+ # MakeRoom (--unload) admission; never relax CRITICAL pressure or non-freeing loads.
222
+ ram["pressure_level"] = metal.PRESSURE_NORMAL
223
+ ram.pop("pressure_kept_bytes", None)
218
224
  seen["llama_servers"] = []
219
225
  seen["disk"] = {**seen["disk"], "free_bytes": None}
220
226
  return seen
@@ -18,17 +18,18 @@ class CaseResult(TypedDict):
18
18
 
19
19
 
20
20
  def acceptance(detector: Detector) -> dict[str, object]:
21
+ synthetic_token = "_".join(("example", "synthetic", "secret", "0123456789abcdef"))
21
22
  cases = (
22
23
  (
23
24
  "english-pii-and-secret",
24
25
  "Contact Jane Doe at jane.doe@example.org or +1 415-555-0132. "
25
- 'Server 10.0.3.17, api_key = "q7Vt2LmX9pRk4sWz8bNc3yHd6fJg1aE5"',
26
+ f'Server 198.51.100.17, api_key = "{synthetic_token}"',
26
27
  (
27
28
  "Jane Doe",
28
29
  "jane.doe@example.org",
29
30
  "+1 415-555-0132",
30
- "10.0.3.17",
31
- "q7Vt2LmX9pRk4sWz8bNc3yHd6fJg1aE5",
31
+ "198.51.100.17",
32
+ synthetic_token,
32
33
  ),
33
34
  ),
34
35
  (
@@ -46,8 +47,8 @@ def acceptance(detector: Detector) -> dict[str, object]:
46
47
  ("log-date-negative", "[2026-09-30 14:05:12] INFO request served in 35 ms", ()),
47
48
  (
48
49
  "code-secret",
49
- 'api_key = "q7Vt2LmX9pRk4sWz8bNc3yHd6fJg1aE5"',
50
- ("q7Vt2LmX9pRk4sWz8bNc3yHd6fJg1aE5",),
50
+ f'api_key = "{synthetic_token}"',
51
+ (synthetic_token,),
51
52
  ),
52
53
  (
53
54
  "multi-window-tail",
File without changes
@@ -6,7 +6,7 @@ width: a GGUF k-quant keeps some tensors (attention V, the output layer) at high
6
6
  group-quantized formats store a scale (and a zero point) per group. Small models with large
7
7
  vocabularies run above these averages because embeddings are a bigger share of them; a real file
8
8
  size always outranks the table. Sources for each number are in
9
- research/2026-11-13-model-size-tools.md.
9
+ standard GGUF quantization bit-width conventions.
10
10
  """
11
11
 
12
12
  from __future__ import annotations
@@ -24,7 +24,7 @@ from localmodels.records import Plan
24
24
  from localmodels.stack_compose import agent_posture
25
25
  from localmodels.stack_plan import command, platform_error
26
26
 
27
- # Where the LLM's picture reader runs (roadmap decision 31); absent: a text-only plan.
27
+ # Where the LLM's picture reader runs; absent: a text-only plan.
28
28
  READER_WORDS = {
29
29
  "gpu": "图片输入开启(读图组件在 GPU)",
30
30
  "cpu": "图片输入开启(读图组件在 CPU,不占显存)",
@@ -10,6 +10,12 @@ import subprocess
10
10
  import time
11
11
  from pathlib import Path
12
12
 
13
+ # PolyStrata's graceful shutdown (ENGINE_QUIT_WAIT_S + Vision shutdown) can exceed 10 s while
14
+ # unloading large Metal unified-memory models; cap launchd's own SIGTERM grace at 15 s and poll
15
+ # up to 30 s so unload never fails spuriously while shutdown is still completing.
16
+ EXIT_TIMEOUT_S = 15
17
+ STOP_WAIT_S = 30.0
18
+
13
19
 
14
20
  def identity(directory: str) -> tuple[Path, str]:
15
21
  root = Path(directory).expanduser().resolve()
@@ -53,6 +59,7 @@ def install(directory: str) -> None:
53
59
  "ProgramArguments": ["/bin/sh", str(plist.parent / "run.sh")],
54
60
  "RunAtLoad": True,
55
61
  "KeepAlive": False,
62
+ "ExitTimeOut": EXIT_TIMEOUT_S,
56
63
  "StandardOutPath": str(plist.parent / "server.log"),
57
64
  "StandardErrorPath": str(plist.parent / "server.log"),
58
65
  }
@@ -80,7 +87,7 @@ def stop(directory: str) -> None:
80
87
  return
81
88
  if _launchctl("bootout", target).returncode:
82
89
  raise RuntimeError("launchd unload failed")
83
- deadline = time.monotonic() + 10
90
+ deadline = time.monotonic() + STOP_WAIT_S
84
91
  while time.monotonic() < deadline:
85
92
  result = _launchctl("print", target)
86
93
  if result.returncode and "Could not find service" in result.stderr:
@@ -77,7 +77,7 @@ _terminate_tree = terminate_tree
77
77
  def await_group_exit(pgid: int, timeout: float = GROUP_EXIT_S) -> bool:
78
78
  """Wait until no process is left in the group. SIGKILL takes effect only when each member
79
79
  next runs (a member in a system call finishes it first), so without this wait a probe could
80
- return while its timed-out tree still writes files (WHI-582). True when the group is gone;
80
+ return while its timed-out tree still writes files. True when the group is gone;
81
81
  False after ``timeout`` (the caller goes on: the kill stays pending)."""
82
82
  deadline = time.monotonic() + timeout
83
83
  while True:
@@ -15,6 +15,7 @@ from localmodels import (
15
15
  catalog,
16
16
  component,
17
17
  deploy,
18
+ deployment_lifecycle,
18
19
  hosts,
19
20
  metal,
20
21
  probe,
@@ -136,10 +137,7 @@ def _binding(plan: Plan, key: str) -> dict[str, str]:
136
137
  def healthy(record: FinishedRecord) -> bool:
137
138
  rows = lifecycle.status_rows([record])
138
139
  return bool(
139
- rows
140
- and rows[0]["ok"]
141
- and rows[0]["state"] == "active"
142
- and rows[0]["health"] in ("ok", "ready")
140
+ rows and rows[0]["ok"] and deployment_lifecycle.healthy(rows[0]["state"], rows[0]["health"])
143
141
  )
144
142
 
145
143
 
@@ -31,7 +31,7 @@ import subprocess
31
31
  import sys
32
32
  import urllib.error
33
33
  import urllib.request
34
- from collections.abc import Callable, Sequence
34
+ from collections.abc import Callable, Mapping, Sequence
35
35
  from concurrent.futures import ThreadPoolExecutor
36
36
  from pathlib import Path
37
37
 
@@ -322,16 +322,28 @@ def parse_darwin_ps(
322
322
  its physical footprint) the part of it that is file cache. Python servers need their
323
323
  module/script argument to identify the engine; no arguments or model paths are kept.
324
324
  ``parent`` gives a process's parent, for an engine its deployment's launcher started."""
325
- found: list[dict[str, object]] = []
325
+ entries: list[tuple[int, int, str, str]] = []
326
+ users: dict[int, str] = {}
326
327
  for line in text.splitlines():
327
328
  cols = line.split(None, 3)
328
329
  if len(cols) != 4 or not cols[0].isdigit() or not cols[1].isdigit():
329
330
  continue
330
331
  pid, rss, user, comm = int(cols[0]), int(cols[1]), cols[2], cols[3].strip()
331
- name, argv = _darwin_engine(comm, pid, args)
332
+ entries.append((pid, rss, user, comm))
333
+ users[pid] = user
334
+ args_cache: dict[int, str] = {}
335
+
336
+ def cached_args(pid: int) -> str:
337
+ if pid not in args_cache:
338
+ args_cache[pid] = args(pid)
339
+ return args_cache[pid]
340
+
341
+ found: list[dict[str, object]] = []
342
+ for pid, rss, user, comm in entries:
343
+ name, argv = _darwin_engine(comm, pid, cached_args)
332
344
  if name is None:
333
345
  continue
334
- owned = user == me and _beside_deployment(argv, pid, parent)
346
+ owned = user == me and _beside_deployment(argv, pid, parent, cached_args, users, me)
335
347
  row: dict[str, object] = {
336
348
  "gpu_uuid": METAL_UUID,
337
349
  "pid": pid,
@@ -381,23 +393,57 @@ def _receipt_pids(directory: str) -> set[int]:
381
393
  return held
382
394
 
383
395
 
384
- def _beside_deployment(
385
- argv: Sequence[str], pid: int, parent: Callable[[int], int | None] | None = None
386
- ) -> bool:
387
- """A deployment's receipt names this process, or names its parent: a launcher in front of
388
- the server (slot_cache.py) is the recorded process and the server is its child, as the
389
- Linux check follows a process's ancestors to the recorded command (_posix_owned)."""
396
+ def _held_from_argv(argv: Sequence[str]) -> set[int]:
390
397
  values = (arg.split("=", 1)[-1] for arg in argv[:256])
391
398
  held: set[int] = set()
392
399
  for directory in {os.path.dirname(v) for v in values if v[:1] == "/"}:
393
400
  if os.path.isfile(directory + "/deployment.json"):
394
401
  held |= _receipt_pids(directory)
402
+ return held
403
+
404
+
405
+ def _split_args(pid: int, args: Callable[[int], str]) -> list[str]:
406
+ try:
407
+ return shlex.split(args(pid))
408
+ except ValueError:
409
+ return []
410
+
411
+
412
+ def _beside_deployment(
413
+ argv: Sequence[str],
414
+ pid: int,
415
+ parent: Callable[[int], int | None] | None = None,
416
+ args: Callable[[int], str] | None = None,
417
+ users: Mapping[int, str] | None = None,
418
+ me: str = "",
419
+ ) -> bool:
420
+ """A deployment's receipt names this process, or names a verified same-user ancestor: a
421
+ launcher in front of the server (slot_cache.py, strata_poly_server.py) is the recorded
422
+ process and its engine/vision children (such as ``strata-vision``, whose argv carries only
423
+ model paths) inherit ownership from that recorded ancestor, matching ``_posix_owned``."""
424
+ held = _held_from_argv(argv)
395
425
  if pid in held:
396
426
  return True
397
- if not held or parent is None:
427
+ if parent is None:
398
428
  return False
399
- above = parent(pid)
400
- return above is not None and above > 1 and above in held
429
+ seen = {pid}
430
+ cur = pid
431
+ for _ in range(16):
432
+ above = parent(cur)
433
+ if above is None or above <= 1 or above in seen:
434
+ return False
435
+ seen.add(above)
436
+ if users is not None and me and users.get(above) not in (None, me):
437
+ return False
438
+ if above in held:
439
+ return True
440
+ if args is not None:
441
+ ancestor_held = _held_from_argv(_split_args(above, args))
442
+ if above in ancestor_held:
443
+ return True
444
+ held |= ancestor_held
445
+ cur = above
446
+ return False
401
447
 
402
448
 
403
449
  LIBPROC = "/usr/lib/libproc.dylib"
@@ -15,6 +15,7 @@ from localmodels import (
15
15
  cli_help,
16
16
  deploy,
17
17
  metal,
18
+ plan_envelope,
18
19
  probe,
19
20
  service_probe,
20
21
  setup_capacity,
@@ -80,6 +81,24 @@ def _plan_reason(error: PlanError | StackError) -> Reason:
80
81
  return {"code": "plan-unavailable", "message": str(error)}
81
82
 
82
83
 
84
+ PortCode = Literal["port-check-failed", "ports-in-use"]
85
+
86
+
87
+ def _port_code(error: BaseException) -> PortCode | None:
88
+ """``port-check-failed`` when no port of a range could be confirmed free
89
+ (stack_ports.PortProbeError), ``ports-in-use`` when every one is in use (PORTS_IN_USE)."""
90
+ if isinstance(error, stack_ports.PortProbeError):
91
+ return "port-check-failed"
92
+ return "ports-in-use" if stack_ports.ports_in_use(error) else None
93
+
94
+
95
+ def _unless_ports(error: PlanError | StackError) -> None:
96
+ """A refusal for ports says nothing about the hardware: it leaves pricing to _plan_stack,
97
+ which prices again with every port taken as free."""
98
+ if _port_code(error) is not None:
99
+ raise error
100
+
101
+
83
102
  def _cuda_driver_reason(error: CudaDriverError, lang: Lang) -> Reason:
84
103
  detected = error.detected_cuda if _VERSION_RE.fullmatch(error.detected_cuda) else ""
85
104
  required = error.required_cuda if _VERSION_RE.fullmatch(error.required_cuda) else ""
@@ -117,7 +136,8 @@ def _cuda_driver_reason(error: CudaDriverError, lang: Lang) -> Reason:
117
136
  def _plans_hardware(options: StackOptions, facts: HostFacts) -> bool:
118
137
  try:
119
138
  stack.build(options, facts=facts)
120
- except (PlanError, stack.StackError):
139
+ except (PlanError, stack.StackError) as exc:
140
+ _unless_ports(exc)
121
141
  return False
122
142
  return True
123
143
 
@@ -163,6 +183,7 @@ def _other_inference_availability(
163
183
  try:
164
184
  plan = stack.build(options, facts=alone_facts, min_prompt_cache=True)
165
185
  except (PlanError, stack.StackError) as alone_exc:
186
+ _unless_ports(alone_exc)
166
187
  return _driver_block(alone_exc, options, alone_facts, lang)
167
188
  if metal.supported(facts):
168
189
  reasons: list[Reason] = [
@@ -192,6 +213,7 @@ def _capacity_availability(
192
213
  try:
193
214
  plan = stack.build(options, facts=roomy, min_prompt_cache=True)
194
215
  except (PlanError, stack.StackError) as roomy_exc:
216
+ _unless_ports(roomy_exc)
195
217
  if blocked := _driver_block(roomy_exc, options, roomy, lang):
196
218
  return blocked
197
219
  else:
@@ -204,79 +226,51 @@ def _capacity_availability(
204
226
  return _other_inference_availability(options, facts, roomy, lang)
205
227
 
206
228
 
207
- def _fits_without_ports(options: StackOptions, facts: HostFacts) -> bool:
208
- """Whether ``facts`` fits a stack once loopback ports can be probed."""
209
- resolver = deploy.catalog_pins if options.get("offline") else deploy.resolve_files
210
-
211
- def once(opts: StackOptions, seen: HostFacts) -> bool:
212
- try:
213
- stack.compose(
214
- seen,
215
- opts,
216
- resolver=resolver,
217
- listening=lambda _port: False,
218
- previous=lambda _name, _port: None,
219
- existing=lambda _recipes: [],
220
- copies=lambda _wanted: {},
221
- owned_ram=lambda: 0,
222
- )
223
- except (PlanError, stack.StackError):
224
- return False
225
- return True
226
-
227
- if once(options, facts):
228
- return True
229
- if (
230
- not options.get("share_gpu")
231
- and budget.holders(facts)
232
- and (not budget.unknown_services(facts) or not metal.supported(facts))
233
- and once({**options, "share_gpu": True}, facts)
234
- ):
235
- return True
236
- roomy = _capacity_facts(facts)
237
- if roomy is not None and once(options, roomy):
238
- return True
239
- if (alone := setup_capacity.without_other_inference(roomy or facts)) is not None:
240
- return once(options, alone)
241
- return False
242
-
243
-
244
- def _port_check_availability(
245
- options: StackOptions, facts: HostFacts, exc: StackError, lang: Lang
246
- ) -> StackAvailability:
247
- """No port of a range could be confirmed free (stack_ports.PortProbeError): blocked now and
248
- retryable, never a reason to recommend another runtime when the hardware fits."""
249
- capable = _fits_without_ports(options, facts)
250
- return {
251
- "available": False,
252
- "reasons": [
253
- {
254
- "code": "port-check-failed",
255
- "message": text("port-check-failed", lang, detail=str(exc))
256
- if capable
257
- else str(exc),
258
- }
259
- ],
260
- "plan": None,
261
- "hardwareCapable": capable,
262
- }
263
-
264
-
265
229
  def _plan_stack(
266
230
  options: StackOptions,
267
231
  facts: HostFacts,
268
232
  share_gpu: bool,
269
233
  lang: Lang,
234
+ ) -> StackAvailability:
235
+ """Price the stack. A refusal for loopback ports anywhere on the way says nothing about the
236
+ hardware, so the stack is priced again as if every port were free: a host that would then be
237
+ ready is blocked now by its ports alone (``port-check-failed`` / ``ports-in-use``, retryable,
238
+ hardwareCapable true); one blocked now for something else gets the port reason after its own;
239
+ one that cannot run local models keeps its own reason. Busy ports never make
240
+ hardwareCapable false."""
241
+ try:
242
+ return _priced(options, facts, share_gpu, lang)
243
+ except (PlanError, stack.StackError) as exc:
244
+ if (code := _port_code(exc)) is None:
245
+ raise
246
+ refused = exc
247
+ with plan_envelope.assume_ports_free():
248
+ try:
249
+ freed = _priced(options, facts, share_gpu, lang)
250
+ except (PlanError, stack.StackError) as exc:
251
+ return {"available": False, "reasons": [_plan_reason(exc)], "plan": None}
252
+ reason: Reason = {"code": code, "message": text(code, lang, detail=str(refused))}
253
+ if freed["available"]:
254
+ return {"available": False, "reasons": [reason], "plan": None, "hardwareCapable": True}
255
+ if _capable_now(freed):
256
+ return {**freed, "reasons": [*freed["reasons"], reason]}
257
+ return freed
258
+
259
+
260
+ def _priced(
261
+ options: StackOptions,
262
+ facts: HostFacts,
263
+ share_gpu: bool,
264
+ lang: Lang,
270
265
  ) -> StackAvailability:
271
266
  try:
272
267
  plan = stack.build(options, facts=facts)
273
- except stack_ports.PortProbeError as exc:
274
- return _port_check_availability(options, facts, exc, lang)
275
268
  except (PlanError, stack.StackError) as exc:
269
+ _unless_ports(exc)
276
270
  last_error: PlanError | StackError | None = exc
277
271
  last_options = options
278
272
  reason = _plan_reason(exc)
279
- # Consent decides by free VRAM whoever else uses a card (roadmap decision 60), so
273
+ # Consent decides by free VRAM whoever else uses a card, so
280
274
  # only a Mac, whose sharing still needs every discovery section, skips the retry.
281
275
  if (
282
276
  not share_gpu
@@ -287,6 +281,7 @@ def _plan_stack(
287
281
  try:
288
282
  stack.build(shared_options, facts=facts)
289
283
  except (PlanError, stack.StackError) as shared_exc:
284
+ _unless_ports(shared_exc)
290
285
  last_error, last_options = shared_exc, shared_options
291
286
  reason = _plan_reason(shared_exc)
292
287
  else:
@@ -340,7 +335,8 @@ def _stack(
340
335
  def _plans(options: StackOptions, facts: HostFacts) -> bool:
341
336
  try:
342
337
  stack.build(options, facts=facts)
343
- except (PlanError, stack.StackError):
338
+ except (PlanError, stack.StackError) as exc:
339
+ _unless_ports(exc)
344
340
  return False
345
341
  return True
346
342
 
@@ -408,16 +404,22 @@ def _free_memory_reason(facts: HostFacts, roomy: HostFacts, lang: Lang = "zh") -
408
404
  }
409
405
 
410
406
 
411
- def _classify(availability: StackAvailability, facts: HostFacts) -> None:
407
+ def _capable_now(availability: StackAvailability) -> bool:
408
+ """Refused now, but the hardware can run local models once what the reasons name changes."""
412
409
  codes = {reason["code"] for reason in availability["reasons"]}
413
- if availability["available"]:
414
- availability["state"], availability["hardwareCapable"] = "ready", True
415
- elif (
410
+ return (
416
411
  availability.get("basis") == "capacity"
417
412
  or "gpu-sharing-required" in codes
418
413
  or bool(codes & _DRIVER_REASON_CODES)
419
- or ("port-check-failed" in codes and availability.get("hardwareCapable") is True)
420
- ):
414
+ or availability.get("hardwareCapable") is True
415
+ )
416
+
417
+
418
+ def _classify(availability: StackAvailability, facts: HostFacts) -> None:
419
+ codes = {reason["code"] for reason in availability["reasons"]}
420
+ if availability["available"]:
421
+ availability["state"], availability["hardwareCapable"] = "ready", True
422
+ elif _capable_now(availability):
421
423
  availability["state"], availability["hardwareCapable"] = "blocked-now", True
422
424
  else:
423
425
  availability["state"] = "unavailable"
@@ -522,7 +524,7 @@ INSPECT = (
522
524
  INSPECT_REASONS = (
523
525
  "unsupported-platform · facts-unavailable · plan-unavailable · gpu-sharing-required\n"
524
526
  "cuda-driver-update-required · cuda-driver-version-unknown · port-check-failed · "
525
- "gpu-memory-required · free-memory-required"
527
+ "ports-in-use · gpu-memory-required · free-memory-required"
526
528
  )
527
529
  REVIEW = (
528
530
  "Read-only: verify the saved plan's digest and project it for the user to approve. The "
@@ -1,4 +1,4 @@
1
- """The messages ``setup inspect``, ``review`` and ``binding`` show a user, in Chinese and English.
1
+ """The messages ``setup inspect`` and ``review`` show a user, in Chinese and English.
2
2
 
3
3
  Chinese stays the default: it is what installers built before ``--lang`` show. Reason codes and
4
4
  every other field are the same in both languages, so a caller may also show its own text per
@@ -100,67 +100,18 @@ MESSAGES: dict[str, tuple[str, str]] = {
100
100
  "(requires CUDA {required} or newer). Update or reinstall the NVIDIA driver and check "
101
101
  "again.",
102
102
  ),
103
- "gateway-port-in-use": (
104
- "这台电脑的硬件可以运行本地模型,但网关端口当前被其他程序占用({detail})。"
105
- "请停止占用该端口的程序,或设置其他网关地址后重新检查。",
106
- "This computer's hardware can run local models, but the gateway port is currently in use "
107
- "({detail}). Stop that program or set another gateway address, then check again.",
108
- ),
109
103
  "port-check-failed": (
110
104
  "这台电脑的硬件可以运行本地模型,但暂时无法确认本地端口是否空闲({detail})。"
111
105
  "请稍后重新检查。",
112
106
  "This computer's hardware can run local models, but whether a local port is free could "
113
107
  "not be confirmed right now ({detail}). Check again in a moment.",
114
108
  ),
115
- "harness-unavailable": (
116
- "这台电脑的硬件可以运行本地模型,但网关或工具环境检查未通过({detail})。"
117
- "请先处理该问题后重新检查。",
118
- "This computer's hardware can run local models, but gateway or tool preparation is "
119
- "currently blocked ({detail}). Resolve this issue and check again.",
120
- ),
121
- "plan-invalid": (
122
- "批准计划不存在、无效或摘要不一致。",
123
- "The approved plan is missing or invalid, or its digest does not match.",
124
- ),
125
- "acceptance-unavailable": (
126
- "批准计划缺少完整成功的套件验收记录,请完成已有安装的验收后重试。",
127
- "The approved plan has no complete, successful stack acceptance record. Finish "
128
- "accepting the existing install and try again.",
129
- ),
130
- "deployment-unavailable": (
131
- "计划中的部署尚未全部就绪,或当前记录与归属不一致。",
132
- "Not every deployment in the plan is ready yet, or the current records do not match "
133
- "their ownership.",
134
- ),
135
- "gateway-ownership": (
136
- "网关或 Pi 的归属与批准计划不一致。",
137
- "The gateway or Pi is not the one the approved plan set up.",
138
- ),
139
- "gateway-record": (
140
- "网关归属与批准计划不一致。",
141
- "The gateway is not the one the approved plan set up.",
142
- ),
143
- "gateway-unavailable": (
144
- "计划中的网关或 Pi 默认模型当前不可用。",
145
- "The plan's gateway or Pi's default model is not available now.",
146
- ),
147
- "pi-model-unavailable": (
148
- "Pi 当前没有列出计划中的网关模型。",
149
- "Pi does not list the plan's gateway model now.",
150
- ),
151
- "pi-config-changed": (
152
- "检查期间 Pi 配置发生变化,请重新检查。",
153
- "Pi's configuration changed during the check. Check again.",
154
- ),
155
- "pi-extensions-unavailable": (
156
- "Pi 无法加载扩展(0.1.0.dev39 之前安装的 Pi 缺少依赖),请重新运行 stack apply。",
157
- "Pi cannot load extensions (a Pi installed before 0.1.0.dev39 lacks its dependencies). "
158
- "Run stack apply again to replace it.",
159
- ),
160
- "binding-unavailable": (
161
- "无法安全验证 Pi 配置或本机状态,请检查本地模型安装,或先改用其他 AI 运行时。",
162
- "Pi's configuration or this computer's state could not be verified safely. Check the "
163
- "local model installation or choose another AI runtime.",
109
+ "ports-in-use": (
110
+ "这台电脑的硬件可以运行本地模型,但本地模型需要的本地端口都已被其他程序占用({detail})。"
111
+ "请关闭占用这些端口的程序后重新检查。",
112
+ "This computer's hardware can run local models, but every local port the local models "
113
+ "can use is held by other programs ({detail}). Close the programs that hold them, then "
114
+ "check again.",
164
115
  ),
165
116
  # The plan summary: the model, where it runs and what it needs.
166
117
  "summary": (