@simplexai/localmodels-linux-x64 0.1.0-dev.43 → 0.1.0-dev.44

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 (40) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +39 -38
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/auth_proxy.py +285 -82
  5. package/modules/localmodels/bifrost_models.py +9 -2
  6. package/modules/localmodels/bifrost_provider.py +42 -7
  7. package/modules/localmodels/debug_mode.py +2 -18
  8. package/modules/localmodels/engines.py +19 -6
  9. package/modules/localmodels/gateway_bifrost.py +10 -1
  10. package/modules/localmodels/harness.py +3 -1
  11. package/modules/localmodels/library_convert.py +491 -57
  12. package/modules/localmodels/library_gateway.py +15 -7
  13. package/modules/localmodels/library_pricing.py +159 -31
  14. package/modules/localmodels/library_status.py +29 -4
  15. package/modules/localmodels/probe.py +42 -9
  16. package/modules/localmodels/runtime_args.py +2 -1
  17. package/modules/localmodels/runtime_auth.py +75 -25
  18. package/modules/localmodels/runtime_cli.py +9 -9
  19. package/modules/localmodels/runtime_install.py +55 -22
  20. package/modules/localmodels/runtime_io.py +76 -210
  21. package/modules/localmodels/runtime_process.py +15 -7
  22. package/modules/localmodels/runtime_windows_acl.py +196 -0
  23. package/modules/localmodels/source_byok.py +116 -30
  24. package/modules/localmodels/source_byok_probe.py +57 -141
  25. package/modules/localmodels/source_cli.py +11 -17
  26. package/modules/localmodels/stack.py +12 -1
  27. package/modules/localmodels/stack_client_settings.py +8 -1
  28. package/modules/localmodels/stack_compose.py +1 -0
  29. package/modules/localmodels/stack_route.py +1 -5
  30. package/modules/localmodels/stack_up.py +20 -1
  31. package/modules/localmodels/vision.py +2 -1
  32. package/modules/localmodels/web/view/view.css +1 -1
  33. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/METADATA +1 -1
  34. package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/RECORD +36 -35
  35. package/package.json +1 -1
  36. package/tool.json +1 -1
  37. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/WHEEL +0 -0
  38. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/entry_points.txt +0 -0
  39. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/licenses/NOTICE +0 -0
  40. /package/modules/{simplex_localmodels-0.1.0.dev43.dist-info → simplex_localmodels-0.1.0.dev44.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -33,6 +33,7 @@ from localmodels import (
33
33
  harness_probe,
34
34
  hosts,
35
35
  library_state,
36
+ vision,
36
37
  )
37
38
  from localmodels import catalog as cat
38
39
  from localmodels.library_model import LibraryError, display_name, split_id
@@ -376,6 +377,19 @@ def _pi_free(provider: str) -> None:
376
377
  raise _fail(f"pi already has a provider {provider} this tool did not add")
377
378
 
378
379
 
380
+ def model_facts(model: str, entry: cat.CatalogEntry, plan: Plan) -> bifrost_models.LlmFacts:
381
+ """The LLM facts pi's models.json needs for a library deployment plan."""
382
+ levels = list(entry.reasoning_efforts or cat.EFFORT_LEVELS)
383
+ context = int(str(plan["launch"].get("window") or 0)) or bifrost_models.DEFAULT_CONTEXT
384
+ return {
385
+ "display": display_name(entry.display_name, split_id(model)[1]),
386
+ "context": context,
387
+ "efforts": levels,
388
+ "defaultEffort": bifrost_models.default_effort(levels),
389
+ "vision": vision.reads_pictures(plan["launch"]),
390
+ }
391
+
392
+
379
393
  def _register(
380
394
  model: str,
381
395
  entry: cat.CatalogEntry,
@@ -416,13 +430,7 @@ def _register(
416
430
  try:
417
431
  if listed_as not in bifrost_models.listed(record["addr"]):
418
432
  raise _fail(f"Bifrost does not list {listed_as}")
419
- levels = list(entry.reasoning_efforts or cat.EFFORT_LEVELS)
420
- facts_: bifrost_models.LlmFacts = {
421
- "display": display_name(entry.display_name, split_id(model)[1]),
422
- "context": context or bifrost_models.DEFAULT_CONTEXT,
423
- "efforts": levels,
424
- "defaultEffort": bifrost_models.default_effort(levels),
425
- }
433
+ facts_ = model_facts(model, entry, plan)
426
434
  base = f"http://{record['addr']}"
427
435
  pi_entry = bifrost_models.pi_provider(facts_, gateway_model, base)["models"][0]
428
436
  if not shared: # the stack's own pi entry already names localmodels-agent
@@ -2,10 +2,12 @@
2
2
 
3
3
  Every figure comes from ``deploy.build_plan`` in the stack's agent posture (the estimator and
4
4
  context policy ``stack plan`` uses): a model's memory is its plan's ``vram_bytes`` (on a Mac its
5
- ``unified_bytes``), its window the plan's. Fit is judged on capacity (every card empty), so it
6
- does not move as other models load; whether a model can load *now* is the same planner on the
7
- free memory less what loading models have reserved. The catalog shown is the chat models
8
- ``validated`` for this platform; a model already on disk stays listed.
5
+ ``unified_bytes``), its window the plan's. Fit is judged on loadable capacity (loaded library
6
+ models unloaded, keeping macOS's idle baseline and observed desktop/WDDM GPU overhead), so it does
7
+ not move as models load and never admits a model whose plan exceeds its pool; whether a model can
8
+ load *now* is the same planner on the free memory less what loading models have reserved. The
9
+ catalog shown is the chat models ``validated`` for this platform; a model already on disk stays
10
+ listed.
9
11
  """
10
12
 
11
13
  from __future__ import annotations
@@ -14,22 +16,41 @@ import copy
14
16
  import functools
15
17
  import os
16
18
  import shutil
17
- from collections.abc import Iterable
19
+ from collections.abc import Iterable, Mapping
18
20
  from dataclasses import dataclass
19
21
  from pathlib import Path
20
22
  from typing import Any
21
23
 
22
- from localmodels import budget, deploy, hosts, llm_rank, metal, plan_envelope, stack_hardware
24
+ from localmodels import (
25
+ budget,
26
+ context_policy,
27
+ deploy,
28
+ hosts,
29
+ llm_rank,
30
+ metal,
31
+ plan_envelope,
32
+ stack_hardware,
33
+ vision,
34
+ )
23
35
  from localmodels import catalog as cat
24
36
  from localmodels.context_policy import AgentPosture
25
- from localmodels.estimator import AGENT_VRAM_RESERVE_BYTES, METAL_VRAM_RESERVE_BYTES
37
+ from localmodels.estimator import (
38
+ AGENT_VRAM_RESERVE_BYTES,
39
+ METAL_VRAM_RESERVE_BYTES,
40
+ PhysicsRefusal,
41
+ )
26
42
  from localmodels.library_model import LibraryError, Reason, display_name, split_id
27
- from localmodels.probe import HostFacts
43
+ from localmodels.probe import GPU, HostFacts
28
44
  from localmodels.records import Plan
29
45
  from localmodels.stack_plan import platform_error
30
46
 
31
47
  POOL_RAM_FRACTION = 0.8 # a "system" pool's budget: RAM x 0.8 (contract v2)
32
48
  UNIFIED_RESERVE_BYTES = metal.HOST_KEEP_BYTES + METAL_VRAM_RESERVE_BYTES
49
+ # Cap on observed non-model GPU VRAM kept back as a desktop/WDDM baseline on Windows and
50
+ # display-active GPUs: keeps real desktop overhead (Windows 11 WDDM + DWM + Linger, ~2.2-2.5 GiB)
51
+ # from pretending the card is empty, without letting a transient game or foreign server hide
52
+ # models that fit once that program closes.
53
+ DESKTOP_VRAM_BASELINE_CAP_BYTES = 3 * metal.GIB
33
54
 
34
55
 
35
56
  @functools.cache
@@ -187,12 +208,61 @@ def pool_of(plan: Plan) -> str:
187
208
  return "system"
188
209
 
189
210
 
190
- def capacity(facts: HostFacts) -> HostFacts:
191
- """``facts`` with every card and the RAM empty: what fit is judged on."""
211
+ def _owned_gpu_bytes(facts: HostFacts, gpu: GPU, reclaimable: Mapping[str, int] | None) -> int:
212
+ pool = f"gpu:{gpu['index']}"
213
+ from_records = max(0, int((reclaimable or {}).get(pool, 0)))
214
+ services = facts.get("services")
215
+ procs = (services.get("compute_processes") if services else None) or []
216
+ from_procs = sum(
217
+ int(p.get("used_bytes") or 0)
218
+ for p in procs
219
+ if p["gpu_uuid"] == gpu["uuid"] and p.get("owned") is True
220
+ )
221
+ return max(from_records, from_procs)
222
+
223
+
224
+ def _foreign_gpu_bytes(facts: HostFacts, gpu: GPU) -> int:
225
+ services = facts.get("services")
226
+ procs = (services.get("compute_processes") if services else None) or []
227
+ return sum(
228
+ int(p.get("used_bytes") or 0)
229
+ for p in procs
230
+ if p["gpu_uuid"] == gpu["uuid"] and budget.foreign_work(p, facts)
231
+ )
232
+
233
+
234
+ def _gpu_capacity_free(facts: HostFacts, gpu: GPU, reclaimable: Mapping[str, int] | None) -> int:
235
+ """Loadable VRAM on ``gpu`` once owned models and transient foreign work clear, keeping
236
+ observed desktop/WDDM baseline occupancy on Windows and display-active GPUs."""
237
+ total = gpu["total_bytes"]
238
+ if facts.get("platform") != "win32" and not gpu.get("display_active"):
239
+ return total
240
+ taken = max(gpu["used_bytes"], max(0, total - gpu["free_bytes"]))
241
+ desktop_used = max(
242
+ 0, taken - _owned_gpu_bytes(facts, gpu, reclaimable) - _foreign_gpu_bytes(facts, gpu)
243
+ )
244
+ baseline = min(desktop_used, DESKTOP_VRAM_BASELINE_CAP_BYTES)
245
+ return min(total, max(gpu["free_bytes"], total - baseline))
246
+
247
+
248
+ def capacity(facts: HostFacts, *, reclaimable: Mapping[str, int] | None = None) -> HostFacts:
249
+ """``facts`` at loadable capacity once loaded library models are unloaded: keeps macOS's
250
+ idle baseline (``metal.in_use``) on Apple Silicon and observed desktop/WDDM baseline VRAM
251
+ on Windows and display-active GPUs instead of pretending zero OS/desktop overhead."""
192
252
  seen = copy.deepcopy(facts)
193
253
  for gpu in seen.get("gpus") or []:
194
- gpu["free_bytes"], gpu["used_bytes"] = gpu["total_bytes"], 0
195
- seen["ram"]["available_bytes"] = seen["ram"]["total_bytes"]
254
+ free = _gpu_capacity_free(facts, gpu, reclaimable)
255
+ gpu["free_bytes"], gpu["used_bytes"] = free, max(0, gpu["total_bytes"] - free)
256
+ ram = seen["ram"]
257
+ if metal.supported(seen):
258
+ total = ram["total_bytes"]
259
+ idle = max(0, total - metal.in_use(total))
260
+ ram["available_bytes"] = min(total, max(ram["available_bytes"], idle))
261
+ if ram.get("pressure_level") is not None:
262
+ ram["pressure_level"] = 1
263
+ ram.pop("pressure_kept_bytes", None)
264
+ else:
265
+ ram["available_bytes"] = ram["total_bytes"]
196
266
  seen["llama_servers"] = []
197
267
  seen["disk"] = {**seen["disk"], "free_bytes": None}
198
268
  if services := seen.get("services"):
@@ -246,7 +316,7 @@ def price(
246
316
  if problem := metal.problem(facts):
247
317
  raise LiveMemoryUnavailable(problem)
248
318
  facts, _ = metal.pressured(facts)
249
- return deploy.build_plan(
319
+ plan = deploy.build_plan(
250
320
  hosts.LOCAL_ID,
251
321
  facts,
252
322
  deploy.PlanOptions(
@@ -262,6 +332,20 @@ def price(
262
332
  entries=catalog,
263
333
  resolver=deploy.catalog_pins,
264
334
  )
335
+ total = pool_total(facts, pool)
336
+ used = memory_bytes(plan)
337
+ if used > total:
338
+ refused = PhysicsRefusal(
339
+ needed_bytes=used,
340
+ available_bytes=total,
341
+ message=f"{model.id} needs {used} bytes, exceeding pool {pool} total {total} bytes",
342
+ )
343
+ raise deploy.AgentMemoryError(
344
+ refused.message,
345
+ refused,
346
+ "unified memory" if pool == "unified" else "GPU memory",
347
+ )
348
+ return plan
265
349
 
266
350
 
267
351
  def memory_bytes(plan: Plan) -> int:
@@ -284,7 +368,28 @@ class Priced:
284
368
  load_free_bytes: int = 0 # pool-aligned free memory on the planned pool
285
369
 
286
370
 
287
- def live_fit(
371
+ def _min_pool_need(model: Model, pool: str, exc: deploy.AgentMemoryError) -> int:
372
+ """Exact pool-aligned free bytes required at the agent floor when ``available_bytes`` clamped
373
+ to zero inside ``agent_budget`` or ``vision.priced``."""
374
+ if gpu_index(pool) is not None:
375
+ return exc.needed_bytes + AGENT_VRAM_RESERVE_BYTES
376
+ if pool == "unified":
377
+ profile = model.entry.profile(model.variant)
378
+ mac_posture = context_policy.posture_for(posture(), "metal")
379
+ host_side = context_policy.cache_floor_bytes(
380
+ mac_posture, profile
381
+ ) + context_policy.metal_host_bytes(profile, mac_posture)
382
+ vision_extra = (
383
+ vision.llama_device_bytes(model.entry.mmproj, "gpu")
384
+ if model.entry.mmproj is not None
385
+ and vision.llama_reader_enabled(model.entry.mmproj, mac_posture.vision)
386
+ else 0
387
+ )
388
+ return exc.needed_bytes + vision_extra + host_side
389
+ return exc.needed_bytes
390
+
391
+
392
+ def _live_plan(
288
393
  facts: HostFacts,
289
394
  model: Model,
290
395
  pool: str,
@@ -293,24 +398,43 @@ def live_fit(
293
398
  reserved: dict[str, int],
294
399
  *,
295
400
  fallback_need: int = 0,
296
- ) -> tuple[bool, int, int]:
297
- """Check whether ``model`` fits ``pool`` in live memory right now.
298
-
299
- Returns ``(fits_now, load_need_bytes, load_free_bytes)`` aligned with ``pool_free`` so row
300
- and dialog figures match the pool summary while preserving the exact live deficit.
301
- """
401
+ ) -> tuple[Plan | None, int, int]:
302
402
  now = live(facts, reserved)
303
403
  if pool not in pools(now):
304
- return False, max(fallback_need, 1), 0
404
+ return None, max(fallback_need, 1), 0
305
405
  free = pool_free(now, pool)
306
406
  try:
307
- price(now, model, pool, base_dir, catalog, require_live=True)
407
+ plan = price(now, model, pool, base_dir, catalog, require_live=True)
308
408
  except deploy.AgentMemoryError as exc:
309
409
  deficit = max(1, exc.needed_bytes - exc.available_bytes)
310
- return False, free + deficit, free
410
+ need = free + deficit
411
+ if exc.available_bytes == 0:
412
+ need = max(need, _min_pool_need(model, pool, exc))
413
+ return None, need, free
311
414
  except plan_envelope.PlanError:
312
- return False, max(fallback_need, free + 1), free
313
- return True, 0, free
415
+ return None, max(fallback_need, free + 1), free
416
+ return plan, 0, free
417
+
418
+
419
+ def live_fit(
420
+ facts: HostFacts,
421
+ model: Model,
422
+ pool: str,
423
+ base_dir: str,
424
+ catalog: tuple[cat.CatalogEntry, ...],
425
+ reserved: dict[str, int],
426
+ *,
427
+ fallback_need: int = 0,
428
+ ) -> tuple[bool, int, int]:
429
+ """Check whether ``model`` fits ``pool`` in live memory right now.
430
+
431
+ Returns ``(fits_now, load_need_bytes, load_free_bytes)`` aligned with ``pool_free`` so row
432
+ and dialog figures match the pool summary while preserving the exact live deficit.
433
+ """
434
+ plan, load_need, load_free = _live_plan(
435
+ facts, model, pool, base_dir, catalog, reserved, fallback_need=fallback_need
436
+ )
437
+ return plan is not None, load_need, load_free
314
438
 
315
439
 
316
440
  def judge(
@@ -319,10 +443,14 @@ def judge(
319
443
  base_dir: str,
320
444
  catalog: tuple[cat.CatalogEntry, ...],
321
445
  reserved: dict[str, int],
446
+ *,
447
+ reclaimable: Mapping[str, int] | None = None,
322
448
  ) -> Priced:
323
- """Fit on capacity; the planned pool is the card with the most free memory that fits now,
324
- else (nothing has room now) the freest card that fits at all, else the unified pool."""
325
- cap, now = capacity(facts), live(facts, reserved)
449
+ """Fit on loadable capacity; the planned pool is the card with the most free memory that
450
+ fits now, else (nothing has room now) the freest card that fits at all, else the unified pool.
451
+ When the model fits live now, its live plan is returned so displayed context and memory match
452
+ what ``library load`` will actually allocate."""
453
+ cap, now = capacity(facts, reclaimable=reclaimable), live(facts, reserved)
326
454
  order = sorted(pools(facts), key=lambda p: -pool_free(now, p))
327
455
  fallback: Priced | None = None
328
456
  shortfall: tuple[int, int] | None = None
@@ -339,11 +467,11 @@ def judge(
339
467
  except plan_envelope.PlanError:
340
468
  continue
341
469
  fit = "unified" if pool == "unified" else "gpu"
342
- fits, load_need, load_free = live_fit(
470
+ live_plan, load_need, load_free = _live_plan(
343
471
  facts, model, pool, base_dir, catalog, reserved, fallback_need=memory_bytes(plan)
344
472
  )
345
- if fits:
346
- return Priced(fit, pool, plan, True, load_free_bytes=load_free)
473
+ if live_plan is not None:
474
+ return Priced(fit, pool, live_plan, True, load_free_bytes=load_free)
347
475
  if fallback is None:
348
476
  fallback = Priced(
349
477
  fit, pool, plan, False, load_need_bytes=load_need, load_free_bytes=load_free
@@ -31,6 +31,7 @@ from localmodels.library_model import (
31
31
  DownloadSource,
32
32
  Holder,
33
33
  Host,
34
+ LibraryError,
34
35
  Load,
35
36
  LoadStep,
36
37
  MemoryPressure,
@@ -80,6 +81,7 @@ class Library:
80
81
  jobs: dict[str, tuple[Job, bool]]
81
82
  catalog: tuple[cat.CatalogEntry, ...]
82
83
  priced: dict[str, Priced] = field(default_factory=dict)
84
+ _health: dict[str, bool] = field(default_factory=dict, repr=False)
83
85
 
84
86
  @classmethod
85
87
  def read(cls, facts: HostFacts, base_dir: str) -> Library:
@@ -92,7 +94,9 @@ class Library:
92
94
  )
93
95
 
94
96
  def healthy(self, base_url: str) -> bool:
95
- return answering(base_url)
97
+ if base_url not in self._health:
98
+ self._health[base_url] = answering(base_url)
99
+ return self._health[base_url]
96
100
 
97
101
  def reserved(self) -> dict[str, int]:
98
102
  """Memory loading models hold before the probe can see it, per pool."""
@@ -102,6 +106,18 @@ class Library:
102
106
  found[job["pool"]] = found.get(job["pool"], 0) + job["memory_bytes"]
103
107
  return found
104
108
 
109
+ def reclaimable(self) -> dict[str, int]:
110
+ """Memory loaded library models hold in ``facts`` now, freed if unloaded, per pool."""
111
+ found: dict[str, int] = {}
112
+ for record in self.records.values():
113
+ if record["state"] != "loaded":
114
+ continue
115
+ if not self.healthy(str(record["plan"]["endpoint"]["base_url"])):
116
+ continue
117
+ pool = record["pool"]
118
+ found[pool] = found.get(pool, 0) + library_pricing.memory_bytes(record["plan"])
119
+ return found
120
+
105
121
  def models(self) -> list[Model]:
106
122
  rows = library_pricing.shown(self.facts, self.catalog)
107
123
  known = {m.id for m in rows}
@@ -109,14 +125,19 @@ class Library:
109
125
  if model_id not in known:
110
126
  try:
111
127
  rows.append(library_pricing.find(model_id, self.catalog))
112
- except ValueError:
128
+ except (ValueError, LibraryError):
113
129
  continue
114
130
  return rows
115
131
 
116
132
  def judge(self, model: Model) -> Priced:
117
133
  if model.id not in self.priced:
118
134
  self.priced[model.id] = library_pricing.judge(
119
- self.facts, model, self.base_dir, self.catalog, self.reserved()
135
+ self.facts,
136
+ model,
137
+ self.base_dir,
138
+ self.catalog,
139
+ self.reserved(),
140
+ reclaimable=self.reclaimable(),
120
141
  )
121
142
  return self.priced[model.id]
122
143
 
@@ -156,7 +177,11 @@ def _plan_of(lib: Library, model: Model, record: Record | None, priced: Priced)
156
177
  if job is not None and alive and job["pool"] != priced.pool:
157
178
  try:
158
179
  return library_pricing.price(
159
- library_pricing.capacity(lib.facts), model, job["pool"], lib.base_dir, lib.catalog
180
+ library_pricing.capacity(lib.facts, reclaimable=lib.reclaimable()),
181
+ model,
182
+ job["pool"],
183
+ lib.base_dir,
184
+ lib.catalog,
160
185
  )
161
186
  except plan_envelope.PlanError:
162
187
  return priced.plan
@@ -202,6 +202,7 @@ _VERSION_RE = re.compile(r"version:\s*(\d+)\s*\(([0-9a-f]+)\)")
202
202
  _SEMVER_RE = re.compile(r"version:\s*([\w.\-]+)\s*\(build\s*(\d+),\s*commit\s*([0-9a-f]+)\)")
203
203
  SERVICE_PORTS = (8080, 9931, 18100, 18321, 18331, 18351, 18352, 18370)
204
204
  _CONTAINER_CGROUP_RE = re.compile(r"docker|kubepods|containerd|libpod|lxc|crio")
205
+ _CUDA_VERSION_RE = re.compile(r"CUDA(?:\s+UMD)?\s+Version\s*:\s*(\d+(?:\.\d+)*)", re.IGNORECASE)
205
206
  HOST_LIBRARIES = ("libgomp.so.1",)
206
207
  DETAIL_FIELDS = ("compute_cap", "memory.reserved", "display_active") # nvidia-smi names
207
208
  _UNLIMITED = 1 << 60 # cgroup v1 reports "no limit" as a page-aligned LONG_MAX
@@ -338,6 +339,43 @@ def parse_gpu_csv(text: str) -> list[GPU]:
338
339
  return gpus
339
340
 
340
341
 
342
+ def parse_cuda_version(text: str) -> str:
343
+ """Driver-supported CUDA version from ``nvidia-smi`` banner or ``-q`` text, or empty."""
344
+ match = _CUDA_VERSION_RE.search(text)
345
+ return match.group(1) if match else ""
346
+
347
+
348
+ def _load_cuda_driver() -> ctypes.CDLL | None:
349
+ names: tuple[str, ...] = (
350
+ ("nvcuda.dll",)
351
+ if sys.platform == "win32"
352
+ else ("libcuda.so.1", "libcuda.so", "/usr/lib/wsl/lib/libcuda.so.1")
353
+ if sys.platform.startswith("linux")
354
+ else ()
355
+ )
356
+ for name in names:
357
+ try:
358
+ return ctypes.CDLL(name)
359
+ except OSError:
360
+ continue
361
+ return None
362
+
363
+
364
+ def _cuda_driver_version() -> str:
365
+ """Driver-supported CUDA version via ``cuDriverGetVersion()`` (e.g. 13050 -> '13.5')."""
366
+ cuda = _load_cuda_driver()
367
+ if cuda is None:
368
+ return ""
369
+ try:
370
+ version = ctypes.c_int()
371
+ if cuda.cuDriverGetVersion(ctypes.byref(version)) != 0 or version.value < 1000:
372
+ return ""
373
+ major, rem = divmod(version.value, 1000)
374
+ return f"{major}.{rem // 10}"
375
+ except (OSError, AttributeError):
376
+ return ""
377
+
378
+
341
379
  def _nvidia(errors: list[dict[str, str]]) -> tuple[dict[str, str] | None, list[GPU]]:
342
380
  exe = _nvidia_smi()
343
381
  if exe is None:
@@ -351,20 +389,15 @@ def _nvidia(errors: list[dict[str, str]]) -> tuple[dict[str, str] | None, list[G
351
389
  errors.append({"source": "nvidia-smi", "error": (err or out).strip()[:300]})
352
390
  return None, []
353
391
  gpus = parse_gpu_csv(out)
354
- m = re.search(r"CUDA Version:\s*([\d.]+)", _run([exe])[1])
392
+ cuda_version = _cuda_driver_version() or parse_cuda_version(_run([exe])[1])
355
393
  drv = gpus[0]["driver_version"] if gpus else ""
356
- return {"driver_version": drv, "cuda_version": m.group(1) if m else ""}, gpus
394
+ return {"driver_version": drv, "cuda_version": cuda_version}, gpus
357
395
 
358
396
 
359
397
  def _cuda_pool() -> CudaPool | None:
360
398
  """Allocator pool and INTEGRATED attribute of CUDA device 0 via driver library, or None."""
361
- for name in ("libcuda.so.1", "libcuda.so", "nvcuda.dll"):
362
- try:
363
- cuda = ctypes.CDLL(name)
364
- break
365
- except OSError:
366
- continue
367
- else:
399
+ cuda = _load_cuda_driver()
400
+ if cuda is None:
368
401
  return None
369
402
  try:
370
403
  dev, total, attr, byref = ctypes.c_int(), ctypes.c_size_t(), ctypes.c_int(), ctypes.byref
@@ -32,7 +32,8 @@ DOCS: dict[str, tuple[str, str, list[tuple[str, str]]]] = {
32
32
  'openai-compatible; openai-compatible also needs "baseUrl" (https, or http on loopback)\n'
33
33
  'and "modelId", and for Codex "wireApi": "responses". Optional "contextWindow" is an\n'
34
34
  "integer from 1 to 2147483647; otherwise probe /props then /models (5 s each, no\n"
35
- "redirects or environment proxies), falling back to 32768 if unavailable. Other keys\n"
35
+ "redirects or environment proxies), falling back to 32768 if unavailable. Optional\n"
36
+ '"vision" is a boolean; otherwise /props or /models determines image input. Other keys\n'
36
37
  "are refused. Codex\n"
37
38
  "takes openai or openai-compatible, Claude anthropic, pi any of them.",
38
39
  [
@@ -204,6 +204,7 @@ def _validate_config(runtime: str, value: dict[str, Any]) -> None:
204
204
  "modelId",
205
205
  "wireApi",
206
206
  "contextWindow",
207
+ "vision",
207
208
  }:
208
209
  raise ValueError("Invalid runtime credentials")
209
210
  provider = value.get("provider")
@@ -220,7 +221,9 @@ def _validate_config(runtime: str, value: dict[str, Any]) -> None:
220
221
  ):
221
222
  raise ValueError("Invalid runtime credentials")
222
223
  if provider != "openai-compatible":
223
- if any(field in value for field in ("baseUrl", "modelId", "wireApi", "contextWindow")):
224
+ if any(
225
+ field in value for field in ("baseUrl", "modelId", "wireApi", "contextWindow", "vision")
226
+ ):
224
227
  raise ValueError("Invalid runtime model config")
225
228
  return
226
229
  if "contextWindow" in value and (
@@ -228,6 +231,8 @@ def _validate_config(runtime: str, value: dict[str, Any]) -> None:
228
231
  or not 1 <= value["contextWindow"] <= MAX_CONTEXT_WINDOW
229
232
  ):
230
233
  raise ValueError("contextWindow must be an integer between 1 and 2147483647")
234
+ if "vision" in value and type(value["vision"]) is not bool:
235
+ raise ValueError("vision must be a boolean")
231
236
  base = value.get("baseUrl")
232
237
  model = value.get("modelId")
233
238
  if (
@@ -318,11 +323,59 @@ def _verify_config(value: dict[str, Any]) -> None:
318
323
  ) from None
319
324
 
320
325
 
321
- def _context_window(value: dict[str, Any]) -> int:
326
+ def _props_metadata(result: dict[str, Any]) -> tuple[int | None, bool | None]:
327
+ settings = result.get("default_generation_settings")
328
+ raw_context = settings.get("n_ctx") if isinstance(settings, dict) else None
329
+ context = (
330
+ raw_context if type(raw_context) is int and 1 <= raw_context <= MAX_CONTEXT_WINDOW else None
331
+ )
332
+ modalities = result.get("modalities")
333
+ raw_vision = modalities.get("vision") if isinstance(modalities, dict) else None
334
+ vision = raw_vision if isinstance(raw_vision, bool) else None
335
+ return context, vision
336
+
337
+
338
+ def _model_vision(model: dict[str, Any]) -> bool:
339
+ if model.get("vision") is True:
340
+ return True
341
+ for key in ("modalities", "capabilities"):
342
+ section = model.get(key)
343
+ if isinstance(section, dict) and section.get("vision") is True:
344
+ return True
345
+ architecture = model.get("architecture")
346
+ for candidate in (
347
+ model.get("input_modalities"),
348
+ architecture.get("input_modalities") if isinstance(architecture, dict) else None,
349
+ ):
350
+ if isinstance(candidate, list) and "image" in candidate:
351
+ return True
352
+ return False
353
+
354
+
355
+ def _models_metadata(result: dict[str, Any], model_id: object) -> tuple[int | None, bool | None]:
356
+ models = result.get("data")
357
+ if not isinstance(models, list):
358
+ return None, None
359
+ matched = next(
360
+ (model for model in models if isinstance(model, dict) and model.get("id") == model_id),
361
+ None,
362
+ )
363
+ if matched is None:
364
+ return None, None
365
+ raw_context = matched.get("max_model_len")
366
+ context = (
367
+ raw_context if type(raw_context) is int and 1 <= raw_context <= MAX_CONTEXT_WINDOW else None
368
+ )
369
+ return context, _model_vision(matched)
370
+
371
+
372
+ def _endpoint_metadata(value: dict[str, Any]) -> tuple[int, bool]:
373
+ explicit_vision: bool | None = bool(value["vision"]) if "vision" in value else None
322
374
  if "contextWindow" in value:
323
- return int(value["contextWindow"])
375
+ return int(value["contextWindow"]), bool(explicit_vision)
324
376
  base = value["baseUrl"].rstrip("/")
325
377
  opener = http_local.no_proxy_opener(allow_redirects=False)
378
+ probed_vision: bool | None = None
326
379
  for url in (base.removesuffix("/v1") + "/props", base + "/models"):
327
380
  try:
328
381
  request = urllib.request.Request(
@@ -337,26 +390,20 @@ def _context_window(value: dict[str, Any]) -> int:
337
390
  result = json.loads(body)
338
391
  if not isinstance(result, dict):
339
392
  continue
340
- if url.endswith("/props"):
341
- settings = result.get("default_generation_settings")
342
- context = settings.get("n_ctx") if isinstance(settings, dict) else None
343
- else:
344
- models = result.get("data")
345
- if not isinstance(models, list):
346
- continue
347
- context = next(
348
- (
349
- model.get("max_model_len")
350
- for model in models
351
- if isinstance(model, dict) and model.get("id") == value["modelId"]
352
- ),
353
- None,
393
+ context, found_vision = (
394
+ _props_metadata(result)
395
+ if url.endswith("/props")
396
+ else _models_metadata(result, value.get("modelId"))
397
+ )
398
+ if found_vision is not None and probed_vision is None:
399
+ probed_vision = found_vision
400
+ if context is not None:
401
+ return context, (
402
+ explicit_vision if explicit_vision is not None else bool(probed_vision)
354
403
  )
355
- if type(context) is int and 1 <= context <= MAX_CONTEXT_WINDOW:
356
- return context
357
404
  except (OSError, ValueError, http.client.HTTPException, RecursionError):
358
405
  continue
359
- return 32768
406
+ return 32768, (explicit_vision if explicit_vision is not None else bool(probed_vision))
360
407
 
361
408
 
362
409
  def owned_files(directory: Path) -> dict[str, str]:
@@ -463,9 +510,10 @@ def save_config(root: Path, runtime: str, value: dict[str, Any]) -> None:
463
510
  save_api_key(root, runtime, value["provider"], value["apiKey"])
464
511
  _record_acceptance(root / "runtime" / runtime)
465
512
  return
466
- context_window = _context_window(value)
513
+ context_window, supports_vision = _endpoint_metadata(value)
514
+ modalities = ["text", "image"] if supports_vision else ["text"]
467
515
  if runtime == "codex":
468
- _save_codex_model(root, value, context_window)
516
+ _save_codex_model(root, value, context_window, modalities)
469
517
  _record_acceptance(root / "runtime" / runtime)
470
518
  return
471
519
  directory = root / "runtime" / "pi"
@@ -484,7 +532,7 @@ def save_config(root: Path, runtime: str, value: dict[str, Any]) -> None:
484
532
  "id": value["modelId"],
485
533
  "name": value["modelId"],
486
534
  "reasoning": False,
487
- "input": ["text"],
535
+ "input": modalities,
488
536
  "contextWindow": context_window,
489
537
  "maxTokens": 4096,
490
538
  "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
@@ -502,7 +550,9 @@ def save_config(root: Path, runtime: str, value: dict[str, Any]) -> None:
502
550
  _record_acceptance(directory)
503
551
 
504
552
 
505
- def _save_codex_model(root: Path, value: dict[str, Any], context_window: int) -> None:
553
+ def _save_codex_model(
554
+ root: Path, value: dict[str, Any], context_window: int, modalities: list[str]
555
+ ) -> None:
506
556
  directory = root / "runtime" / "codex"
507
557
  _prepare_profile(directory, ("auth.json", "config.toml", "models.json", "model.json"))
508
558
  _write_private(directory / "auth.json", {"OPENAI_API_KEY": value["apiKey"]})
@@ -532,7 +582,7 @@ def _save_codex_model(root: Path, value: dict[str, Any], context_window: int) ->
532
582
  "context_window": context_window,
533
583
  "effective_context_window_percent": 95,
534
584
  "experimental_supported_tools": [],
535
- "input_modalities": ["text"],
585
+ "input_modalities": modalities,
536
586
  }
537
587
  ]
538
588
  },