@simplexai/localmodels-darwin-arm64 0.1.0-dev.48 → 0.1.0-dev.50

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 (83) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +82 -72
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/budget.py +40 -14
  5. package/modules/localmodels/catalog.json +473 -36
  6. package/modules/localmodels/debug_mode.py +25 -0
  7. package/modules/localmodels/deploy.py +3 -0
  8. package/modules/localmodels/download-mirrors.json +47 -0
  9. package/modules/localmodels/engines-b12588-mix-c0c3de8.json +13 -1
  10. package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +79 -0
  11. package/modules/localmodels/engines.py +31 -6
  12. package/modules/localmodels/gateway.py +23 -6
  13. package/modules/localmodels/gateway_bifrost.py +6 -2
  14. package/modules/localmodels/harness.py +8 -2
  15. package/modules/localmodels/harness_gateway.py +78 -17
  16. package/modules/localmodels/harness_probe.py +5 -1
  17. package/modules/localmodels/hosts.py +52 -5
  18. package/modules/localmodels/library_floor.py +76 -0
  19. package/modules/localmodels/library_jobs.py +60 -7
  20. package/modules/localmodels/library_model.py +38 -2
  21. package/modules/localmodels/library_poly.py +272 -0
  22. package/modules/localmodels/library_pricing.py +251 -79
  23. package/modules/localmodels/library_serve.py +27 -4
  24. package/modules/localmodels/library_state.py +16 -0
  25. package/modules/localmodels/library_status.py +46 -18
  26. package/modules/localmodels/library_vram.py +123 -0
  27. package/modules/localmodels/llm_rank.py +42 -1
  28. package/modules/localmodels/magpie_windows.py +312 -0
  29. package/modules/localmodels/probe.py +39 -37
  30. package/modules/localmodels/process_identity.py +26 -33
  31. package/modules/localmodels/process_identity_darwin.py +189 -0
  32. package/modules/localmodels/process_identity_linux.py +62 -30
  33. package/modules/localmodels/recommend.py +3 -1
  34. package/modules/localmodels/remote_ops.py +11 -0
  35. package/modules/localmodels/remote_ops_download.py +30 -5
  36. package/modules/localmodels/remote_ops_service.py +15 -46
  37. package/modules/localmodels/reuse.py +13 -6
  38. package/modules/localmodels/runtime_io.py +32 -18
  39. package/modules/localmodels/service_probe.py +1 -1
  40. package/modules/localmodels/setup_inspection.py +97 -80
  41. package/modules/localmodels/setup_inspection_harness.py +147 -0
  42. package/modules/localmodels/setup_text.py +24 -0
  43. package/modules/localmodels/setup_upgrade.py +155 -0
  44. package/modules/localmodels/stack.py +3 -1
  45. package/modules/localmodels/stack_auto.py +6 -2
  46. package/modules/localmodels/stack_clients.py +1 -1
  47. package/modules/localmodels/stack_compose.py +5 -1
  48. package/modules/localmodels/stack_down.py +25 -16
  49. package/modules/localmodels/stack_hardware.py +17 -3
  50. package/modules/localmodels/stack_picks.py +28 -13
  51. package/modules/localmodels/stack_remove.py +3 -1
  52. package/modules/localmodels/stack_route.py +5 -1
  53. package/modules/localmodels/stack_suite.py +29 -8
  54. package/modules/localmodels/stack_view_access.py +238 -58
  55. package/modules/localmodels/stack_view_hub.py +12 -7
  56. package/modules/localmodels/stack_view_serve.py +13 -6
  57. package/modules/localmodels/strata-poly-serve-0.2.19-poly.1.txt +428 -0
  58. package/modules/localmodels/strata_poly_server.py +14 -2
  59. package/modules/localmodels/suite.py +19 -3
  60. package/modules/localmodels/tool_archive.py +4 -0
  61. package/modules/localmodels/transport.py +3 -1
  62. package/modules/localmodels/tui.py +4 -1
  63. package/modules/localmodels/tui_dialogs.py +42 -9
  64. package/modules/localmodels/tui_modals.py +63 -16
  65. package/modules/localmodels/tui_screen.py +80 -53
  66. package/modules/localmodels/tui_views.py +36 -6
  67. package/modules/localmodels/vision.py +4 -2
  68. package/modules/localmodels/web/index.html +996 -300
  69. package/modules/localmodels/web/sizecalc/app.js +616 -88
  70. package/modules/localmodels/web/sizecalc/page.html +239 -106
  71. package/modules/localmodels/web/view/fleet.js +25 -2
  72. package/modules/localmodels/web/view/nav.js +19 -3
  73. package/modules/localmodels/web/view/view.css +110 -22
  74. package/modules/localmodels/web/view/view.js +40 -22
  75. package/modules/localmodels/win_probe.py +204 -0
  76. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/METADATA +1 -1
  77. package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/RECORD +79 -69
  78. package/package.json +1 -1
  79. package/tool.json +1 -1
  80. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/WHEEL +0 -0
  81. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/entry_points.txt +0 -0
  82. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/NOTICE +0 -0
  83. /package/modules/{simplex_localmodels-0.1.0.dev48.dist-info → simplex_localmodels-0.1.0.dev50.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -12,10 +12,13 @@ from typing import cast
12
12
 
13
13
  from localmodels import (
14
14
  __version__,
15
+ debug_mode,
15
16
  hosts,
17
+ library_floor,
16
18
  library_gateway,
17
19
  library_pricing,
18
20
  library_state,
21
+ library_vram,
19
22
  metal,
20
23
  plan_envelope,
21
24
  suite,
@@ -27,6 +30,7 @@ from localmodels.library_model import (
27
30
  LOAD_STEPS_PUBLIC,
28
31
  STATUS_SCHEMA,
29
32
  Availability,
33
+ DebugInfo,
30
34
  Download,
31
35
  DownloadSource,
32
36
  Holder,
@@ -146,7 +150,9 @@ def _state(lib: Library, model: str, record: Record | None) -> tuple[str, Proble
146
150
  job, alive = lib.jobs.get(model, (None, False))
147
151
  if job is not None and alive:
148
152
  return ("downloading" if job["kind"] == "download" else "loading"), None
149
- if job is not None: # its process ended without clearing it
153
+ if job is not None: # its process ended without clearing it, or it failed and kept its partials
154
+ if isinstance(err := job.get("error"), dict) and isinstance(err.get("code"), str):
155
+ return "failed", {"code": err["code"], "detail": str(err.get("detail") or "")}
150
156
  code = "DOWNLOAD_FAILED" if job["kind"] == "download" else "ENGINE_START_FAILED"
151
157
  return "failed", {"code": code, "detail": f"the {job['kind']} process ended early"}
152
158
  if record is None:
@@ -297,7 +303,14 @@ def row(lib: Library, model: Model) -> Row:
297
303
  state, problem = _state(lib, model.id, record)
298
304
  plan = _plan_of(lib, model, record, priced)
299
305
  job, alive = lib.jobs.get(model.id, (None, False))
300
- memory = library_pricing.memory_bytes(plan) if plan is not None else 0
306
+ fallback_memory, fallback_window, fallback_vision, fallback_download = (
307
+ library_floor.floor_metadata(
308
+ lib.facts, model, priced.need_bytes, memory_kind=priced.memory_kind
309
+ )
310
+ if plan is None
311
+ else (0, 0, False, 0)
312
+ )
313
+ memory = library_pricing.memory_bytes(plan) if plan is not None else fallback_memory
301
314
  if record is None and job is not None and alive:
302
315
  memory = job["memory_bytes"] or memory
303
316
  if record is not None and record["state"] != "loaded" and record.get("memory_bytes"):
@@ -315,11 +328,13 @@ def row(lib: Library, model: Model) -> Row:
315
328
  "name": model.name,
316
329
  "description": model.entry.description,
317
330
  "quant": model.variant.quant,
318
- "context_tokens": int(str(launch.get("window") or 0)),
319
- "vision": vision.reads_pictures(launch),
331
+ "context_tokens": int(str(launch.get("window") or 0))
332
+ if plan is not None
333
+ else fallback_window,
334
+ "vision": vision.reads_pictures(launch) if plan is not None else fallback_vision,
320
335
  "download_bytes": sum(f["size_bytes"] for f in plan["files"])
321
336
  if plan is not None
322
- else sum(f.size_bytes for f in model.variant.files),
337
+ else fallback_download,
323
338
  "memory_bytes": memory,
324
339
  "fit": priced.fit, # type: ignore[typeddict-item]
325
340
  "recommended": False,
@@ -401,20 +416,22 @@ def pools(lib: Library, rows: list[Row]) -> list[Pool]:
401
416
  }
402
417
  )
403
418
  now = library_pricing.live(lib.facts, lib.reserved())
419
+ gpu_pool_count = sum(1 for p in holders if p.startswith("gpu:"))
404
420
  found: list[Pool] = []
405
421
  for pool, held in holders.items():
406
422
  total = library_pricing.pool_total(lib.facts, pool)
407
423
  free = library_pricing.pool_free(now, pool)
408
424
  used = min(total, max(0, total - free))
409
- found.append(
410
- {
411
- "id": pool,
412
- "total_bytes": total,
413
- "used_bytes": used,
414
- "holders": held,
415
- "reserve_bytes": library_pricing.pool_reserve(now, pool),
416
- }
417
- )
425
+ entry: Pool = {
426
+ "id": pool,
427
+ "total_bytes": total,
428
+ "used_bytes": used,
429
+ "holders": held,
430
+ "reserve_bytes": library_pricing.pool_reserve(now, pool),
431
+ }
432
+ if ext := library_vram.pool_external_holders(lib.facts, pool, gpu_pool_count):
433
+ entry["external_holders"] = ext
434
+ found.append(entry)
418
435
  return found
419
436
 
420
437
 
@@ -436,11 +453,19 @@ def host(lib: Library) -> Host:
436
453
  os_info.get("distro")
437
454
  or " ".join(str(os_info.get(k) or "") for k in ("system", "release")).strip()
438
455
  )
439
- engine = next((p.plan["engine"] for p in lib.priced.values() if p.plan is not None), None)
456
+ engines = [p.plan["engine"] for p in lib.priced.values() if p.plan is not None]
457
+ engine = next(
458
+ (e for e in engines if not str(e.get("build") or "").startswith("strata")),
459
+ engines[0] if engines else None,
460
+ )
440
461
  backend = {"cuda": "CUDA", "metal": "Metal", "cpu": "CPU"}
441
462
  engine_label = "llama.cpp"
442
463
  if engine is not None:
443
- engine_label = f"llama.cpp {engine.get('build') or ''}".strip()
464
+ build = str(engine.get("build") or "")
465
+ if build.startswith("strata-poly-"):
466
+ engine_label = f"PolyStrata {build.removeprefix('strata-poly-')}".strip()
467
+ else:
468
+ engine_label = f"llama.cpp {build}".strip()
444
469
  if (kind := engine.get("backend")) in backend:
445
470
  engine_label += f" · {backend[str(kind)]}"
446
471
  found: Host = {
@@ -481,10 +506,10 @@ def build(lib: Library) -> Status:
481
506
  and r["availability"]["downloadable"]
482
507
  and r.get("fits_now") is True
483
508
  ]
484
- chosen = library_pricing.recommend(now, candidates)
509
+ chosen = library_pricing.recommend(now, candidates, lib.base_dir)
485
510
  for r in rows:
486
511
  r["recommended"] = r["id"] == chosen
487
- return {
512
+ status_doc: Status = {
488
513
  "schema": STATUS_SCHEMA,
489
514
  "tool_version": __version__,
490
515
  "observed_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
@@ -492,6 +517,9 @@ def build(lib: Library) -> Status:
492
517
  "pools": pools(lib, rows),
493
518
  "models": rows,
494
519
  }
520
+ if (debug_info := debug_mode.status_info()) is not None:
521
+ status_doc["debug"] = cast(DebugInfo, debug_info)
522
+ return status_doc
495
523
 
496
524
 
497
525
  def model_row(lib: Library, model_id: str) -> Row:
@@ -0,0 +1,123 @@
1
+ """Desktop/WDDM GPU VRAM guidance shared by model library status and Quick Install."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ from collections.abc import Callable, Mapping, Sequence
7
+
8
+ from localmodels import budget, plan_envelope, win_probe
9
+ from localmodels.library_model import ExternalHolder
10
+ from localmodels.probe import GPU, HostFacts
11
+
12
+
13
+ def _owned_gpu_bytes(facts: HostFacts, gpu: GPU, reclaimable: Mapping[str, int] | None) -> int:
14
+ pool = f"gpu:{gpu['index']}"
15
+ from_records = max(0, int((reclaimable or {}).get(pool, 0)))
16
+ services = facts.get("services")
17
+ procs = (services.get("compute_processes") if services else None) or []
18
+ from_procs = sum(
19
+ int(p.get("used_bytes") or 0)
20
+ for p in procs
21
+ if p["gpu_uuid"] == gpu["uuid"] and p.get("owned") is True
22
+ )
23
+ return max(from_records, from_procs)
24
+
25
+
26
+ def _foreign_gpu_bytes(facts: HostFacts, gpu: GPU) -> int:
27
+ services = facts.get("services")
28
+ procs = (services.get("compute_processes") if services else None) or []
29
+ return sum(
30
+ int(p.get("used_bytes") or 0)
31
+ for p in procs
32
+ if p["gpu_uuid"] == gpu["uuid"] and budget.foreign_work(p, facts)
33
+ )
34
+
35
+
36
+ def gpu_capacity_free(
37
+ facts: HostFacts,
38
+ gpu: GPU,
39
+ reclaimable: Mapping[str, int] | None,
40
+ desktop_cap: int = budget.DESKTOP_VRAM_BASELINE_CAP_BYTES,
41
+ ) -> int:
42
+ """Loadable VRAM on ``gpu`` once owned models and transient foreign work clear, keeping
43
+ observed desktop/WDDM baseline occupancy on Windows and display-active GPUs."""
44
+ total = gpu["total_bytes"]
45
+ if facts.get("platform") != "win32" and not gpu.get("display_active"):
46
+ return total
47
+ taken = max(gpu["used_bytes"], max(0, total - gpu["free_bytes"]))
48
+ desktop_used = max(
49
+ 0, taken - _owned_gpu_bytes(facts, gpu, reclaimable) - _foreign_gpu_bytes(facts, gpu)
50
+ )
51
+ baseline = min(desktop_used, desktop_cap)
52
+ return min(total, max(gpu["free_bytes"], total - baseline))
53
+
54
+
55
+ def closeable_gpu_apps(facts: HostFacts) -> list[win_probe.GpuAppMemory]:
56
+ """Closeable desktop GPU apps from Windows CIM, excluding owned localmodels PIDs."""
57
+ raw_procs = facts.get("gpu_processes") or []
58
+ if not raw_procs:
59
+ return []
60
+ services = facts.get("services")
61
+ owned_pids = {
62
+ int(p["pid"])
63
+ for p in ((services.get("compute_processes") if services else None) or [])
64
+ if p.get("owned") is True
65
+ }
66
+ found: list[win_probe.GpuAppMemory] = []
67
+ for proc in raw_procs:
68
+ pids = [int(pid) for pid in proc["pids"] if int(pid) not in owned_pids]
69
+ if pids and proc["bytes"] > 0:
70
+ found.append({"name": proc["name"], "pids": pids, "bytes": int(proc["bytes"])})
71
+ return found
72
+
73
+
74
+ def pool_external_holders(facts: HostFacts, pool: str, gpu_pool_count: int) -> list[ExternalHolder]:
75
+ """External closeable desktop GPU apps attributable to ``pool`` (single GPU or display GPU)."""
76
+ if not pool.startswith("gpu:"):
77
+ return []
78
+ index = int(pool.split(":", 1)[1])
79
+ gpu = next((g for g in facts.get("gpus") or [] if g["index"] == index), None)
80
+ if gpu is None or (gpu_pool_count > 1 and not gpu.get("display_active")):
81
+ return []
82
+ return [
83
+ {"name": app["name"], "bytes": app["bytes"], "pids": app["pids"]}
84
+ for app in closeable_gpu_apps(facts)
85
+ ]
86
+
87
+
88
+ def idle_desktop_capacity(facts: HostFacts, cap: HostFacts) -> HostFacts | None:
89
+ """``cap`` with desktop/WDDM discrete GPUs raised to the 1 GiB idle floor, or None when no
90
+ card gains headroom over ``cap``."""
91
+ if facts.get("platform") != "win32" and not any(
92
+ g.get("display_active") for g in facts.get("gpus") or []
93
+ ):
94
+ return None
95
+ roomy = copy.deepcopy(cap)
96
+ gained = False
97
+ for gpu in roomy.get("gpus") or []:
98
+ idle = max(0, gpu["total_bytes"] - budget.IDLE_USED_BYTES)
99
+ if gpu["free_bytes"] < idle:
100
+ gpu["free_bytes"], gpu["used_bytes"] = idle, gpu["total_bytes"] - idle
101
+ gained = True
102
+ return roomy if gained else None
103
+
104
+
105
+ def fits_idle_desktop(
106
+ facts: HostFacts,
107
+ cap: HostFacts,
108
+ pools: Sequence[str],
109
+ try_price: Callable[[HostFacts, str], object],
110
+ ) -> bool:
111
+ """True when ``try_price`` succeeds on any discrete GPU once desktop VRAM nears 1 GiB idle."""
112
+ roomy = idle_desktop_capacity(facts, cap)
113
+ if roomy is None:
114
+ return False
115
+ for pool in pools:
116
+ if not pool.startswith("gpu:"):
117
+ continue
118
+ try:
119
+ try_price(roomy, pool)
120
+ return True
121
+ except plan_envelope.PlanError:
122
+ continue
123
+ return False
@@ -13,7 +13,7 @@ from __future__ import annotations
13
13
  from collections.abc import Iterable, Mapping
14
14
  from dataclasses import dataclass
15
15
 
16
- from localmodels import metal, vision
16
+ from localmodels import engines, metal, vision
17
17
  from localmodels.budget import HARNESS_RAM, RAM_FLOOR, host_ram
18
18
  from localmodels.catalog import (
19
19
  CatalogEntry,
@@ -27,6 +27,7 @@ from localmodels.catalog import (
27
27
  )
28
28
  from localmodels.context_policy import AGENT, AgentPosture
29
29
  from localmodels.estimator import HardwareBudget, PhysicsRefusal, llama_host_bytes
30
+ from localmodels.plan_envelope import PlanError
30
31
  from localmodels.probe import HostFacts
31
32
 
32
33
  # Installed SimplexAI scores closer than this are a tie (model-scoring.md; AIHOT: 3 points or more
@@ -64,6 +65,20 @@ def strata_bar(llama_score: int, options: Mapping[str, object]) -> int:
64
65
  return llama_score + TIE_BAND
65
66
 
66
67
 
68
+ def strata_recipe_bar(
69
+ llama_score: int, options: Mapping[str, object], *, prefer_over_llama: bool = False
70
+ ) -> int:
71
+ """The installed score one Strata/PolyStrata recipe must reach to replace the llama.cpp pick:
72
+ a recipe marked ``prefer_over_llama`` (such as PolyStrata Inkling 2 Mini on CUDA 13+, which
73
+ offers higher-precision quants and faster decode/prefill on NVIDIA cards) wins ties against
74
+ llama.cpp under ``smartest``, while keeping ``--prefer fastest`` on llama.cpp when one fits."""
75
+ if options.get("prefer") == "fastest" and llama_score >= 0:
76
+ return 1 << 30
77
+ if prefer_over_llama:
78
+ return max(0, llama_score)
79
+ return llama_score + TIE_BAND
80
+
81
+
67
82
  PRODUCT_DEFAULTS = {
68
83
  ("win32", "cuda", "NVIDIA RTX Spark N1X"): "qwen3.8-27b",
69
84
  }
@@ -133,10 +148,36 @@ def listed_default(facts: HostFacts, fits: list[tuple[str, int]]) -> str | None:
133
148
  return rungs[0] if rungs and keeps_default(others) else None
134
149
 
135
150
 
151
+ def _engine_supported(entry: CatalogEntry, facts: HostFacts) -> bool:
152
+ """When an entry pins a non-default engine lock, skip it in auto selection if this host
153
+ cannot run that lock while the default lock does run here (e.g. Linux arm64 CUDA, minimal
154
+ containers without libgomp1, or Windows drivers on CUDA 12.4-12.7)."""
155
+ if not entry.engine:
156
+ return True
157
+ backend = (
158
+ "metal"
159
+ if metal.supported(facts)
160
+ else "cuda"
161
+ if any(g["vendor"] == "nvidia" for g in facts.get("gpus") or [])
162
+ else "cpu"
163
+ )
164
+ try:
165
+ engines.select_engine_build(facts, backend, engines.engine_lock_path(entry.engine))
166
+ except PlanError:
167
+ try:
168
+ engines.select_engine_build(facts, backend)
169
+ except PlanError:
170
+ return True
171
+ return False
172
+ return True
173
+
174
+
136
175
  def automatic_here(entry: CatalogEntry, facts: HostFacts) -> bool:
137
176
  """Validated entries and the scoped Mac ladder / Windows fallback candidates."""
138
177
  if entry.id in MAC_LADDER_REPLACES and mac_ladder(facts) is not None:
139
178
  return False
179
+ if not _engine_supported(entry, facts):
180
+ return False
140
181
  return (
141
182
  mac_rung(entry, facts)
142
183
  or windows_fallback(entry, facts)
@@ -0,0 +1,312 @@
1
+ """Windows multi-hop successor adoption for private ``magpie serve`` instances.
2
+
3
+ Controller-side (Layer 4): ``process_windows`` stays self-contained Python 3.8 inside
4
+ ``BUNDLES["remote_ops"]`` so it cannot import ``runtime_io``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ctypes
10
+ import json
11
+ import os
12
+ import posixpath
13
+ import stat
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from localmodels import process_identity, process_windows, runtime_io
18
+
19
+
20
+ def _read_windows_argv0(text: str) -> tuple[str, int]:
21
+ """Read argv[0] per Windows CommandLineToArgvW (quotes toggle; backslashes are literal)."""
22
+ index, length, in_quotes = 0, len(text), False
23
+ buf: list[str] = []
24
+ while index < length:
25
+ ch = text[index]
26
+ if ch == '"':
27
+ in_quotes = not in_quotes
28
+ elif ch in " \t" and not in_quotes:
29
+ break
30
+ else:
31
+ buf.append(ch)
32
+ index += 1
33
+ return "".join(buf), index
34
+
35
+
36
+ def _read_windows_arg(text: str, index: int) -> tuple[str, int]:
37
+ """Read one non-argv[0] argument per Windows CommandLineToArgvW backslash/quote rules."""
38
+ length, in_quotes = len(text), False
39
+ buf: list[str] = []
40
+ while index < length:
41
+ ch = text[index]
42
+ if ch in " \t" and not in_quotes:
43
+ break
44
+ if ch == "\\":
45
+ slashes = 0
46
+ while index < length and text[index] == "\\":
47
+ slashes += 1
48
+ index += 1
49
+ if index < length and text[index] == '"':
50
+ buf.append("\\" * (slashes // 2))
51
+ if slashes % 2:
52
+ buf.append('"')
53
+ else:
54
+ in_quotes = not in_quotes
55
+ index += 1
56
+ else:
57
+ buf.append("\\" * slashes)
58
+ elif ch == '"':
59
+ if in_quotes and index + 1 < length and text[index + 1] == '"':
60
+ buf.append('"')
61
+ index += 2
62
+ else:
63
+ in_quotes = not in_quotes
64
+ index += 1
65
+ else:
66
+ buf.append(ch)
67
+ index += 1
68
+ return "".join(buf), index
69
+
70
+
71
+ def split_windows_cmdline(cmdline: str) -> list[str]:
72
+ """Parse a Windows command line into argv tokens following CommandLineToArgvW rules."""
73
+ text = cmdline.lstrip(" \t")
74
+ if not text:
75
+ return []
76
+ arg0, index = _read_windows_argv0(text)
77
+ args = [arg0]
78
+ length = len(text)
79
+ while index < length:
80
+ while index < length and text[index] in " \t":
81
+ index += 1
82
+ if index >= length:
83
+ break
84
+ arg, index = _read_windows_arg(text, index)
85
+ args.append(arg)
86
+ return args
87
+
88
+
89
+ def _is_magpie_serve_argv(argv: list[str]) -> bool:
90
+ """True only when ``serve`` is the actual Magpie subcommand (argv[1]), not a path segment."""
91
+ return len(argv) >= 2 and argv[1].lower() == "serve"
92
+
93
+
94
+ def _parse_windows_env_block(raw: bytes) -> dict[str, str]:
95
+ """Decode a Windows UTF-16LE double-NUL-terminated environment block (uppercased keys)."""
96
+ if len(raw) % 2:
97
+ raw = raw[:-1]
98
+ env: dict[str, str] = {}
99
+ for entry in raw.decode("utf-16-le", errors="replace").split("\x00"):
100
+ if not entry:
101
+ break
102
+ if "=" not in entry or entry.startswith("="):
103
+ continue
104
+ key, _, value = entry.partition("=")
105
+ env[key.upper()] = value
106
+ return env
107
+
108
+
109
+ def _read_remote_ptr(read_mem: Any, handle: Any, addr: int, ptr_size: int) -> int | None:
110
+ val = ctypes.c_size_t(0)
111
+ got = ctypes.c_size_t(0)
112
+ if not read_mem(handle, addr, ctypes.byref(val), ptr_size, ctypes.byref(got)):
113
+ return None
114
+ return int(val.value) if got.value == ptr_size else None
115
+
116
+
117
+ def process_environment(pid: int) -> dict[str, str] | None:
118
+ """Windows: read PID's PEB environment block via NtQueryInformationProcess + ReadProcessMemory.
119
+ Returns uppercased env mapping, or None when unavailable or off Windows."""
120
+ load: Any = getattr(ctypes, "WinDLL", None)
121
+ if load is None:
122
+ return None
123
+ from ctypes import wintypes
124
+
125
+ class BasicInfo(ctypes.Structure):
126
+ _fields_ = [
127
+ ("Reserved1", ctypes.c_void_p),
128
+ ("PebBaseAddress", ctypes.c_void_p),
129
+ ("Reserved2", ctypes.c_void_p * 2),
130
+ ("UniqueProcessId", ctypes.c_void_p),
131
+ ("Reserved3", ctypes.c_void_p),
132
+ ]
133
+
134
+ kernel, _ = process_identity._api()
135
+ ntdll = load("ntdll")
136
+ query = ntdll.NtQueryInformationProcess
137
+ query.argtypes = (
138
+ wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.ULONG, ctypes.POINTER(wintypes.ULONG)
139
+ ) # fmt: skip
140
+ query.restype = ctypes.c_long
141
+ read_mem = kernel.ReadProcessMemory
142
+ read_mem.argtypes = (
143
+ wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)
144
+ ) # fmt: skip
145
+ read_mem.restype = wintypes.BOOL
146
+ # PROCESS_QUERY_INFORMATION (0x0400) | PROCESS_VM_READ (0x0010)
147
+ handle = kernel.OpenProcess(0x0410, False, pid)
148
+ if not handle:
149
+ return None
150
+ try:
151
+ info = BasicInfo()
152
+ ret_len = wintypes.ULONG(0)
153
+ if query(handle, 0, ctypes.byref(info), ctypes.sizeof(info), ctypes.byref(ret_len)) != 0:
154
+ return None
155
+ if not info.PebBaseAddress:
156
+ return None
157
+ ptr_size = ctypes.sizeof(ctypes.c_size_t)
158
+ params_ptr = _read_remote_ptr(
159
+ read_mem, handle, int(info.PebBaseAddress) + (0x20 if ptr_size == 8 else 0x10), ptr_size
160
+ )
161
+ if not params_ptr:
162
+ return None
163
+ env_ptr = _read_remote_ptr(
164
+ read_mem, handle, params_ptr + (0x80 if ptr_size == 8 else 0x48), ptr_size
165
+ )
166
+ env_size = _read_remote_ptr(
167
+ read_mem, handle, params_ptr + (0x3F0 if ptr_size == 8 else 0x290), ptr_size
168
+ )
169
+ if not env_ptr or not env_size:
170
+ return None
171
+ to_read = min(env_size, 1 << 20)
172
+ buf = ctypes.create_string_buffer(to_read)
173
+ got = ctypes.c_size_t(0)
174
+ if not read_mem(handle, env_ptr, buf, to_read, ctypes.byref(got)) or got.value < 2:
175
+ return None
176
+ return _parse_windows_env_block(buf.raw[: got.value])
177
+ except OSError:
178
+ return None
179
+ finally:
180
+ kernel.CloseHandle(handle)
181
+
182
+
183
+ def _norm_path(value: str | Path) -> str:
184
+ text = str(value).strip()
185
+ if not text:
186
+ return ""
187
+ if os.name == "nt":
188
+ return os.path.normcase(os.path.realpath(text)).replace("\\", "/").rstrip("/")
189
+ slashed = text.replace("\\", "/")
190
+ if (len(slashed) >= 2 and slashed[1] == ":") or slashed.startswith("//"):
191
+ prefix = "//" if slashed.startswith("//") else ""
192
+ return (
193
+ (prefix + posixpath.normpath(slashed.lstrip("/") if prefix else slashed))
194
+ .rstrip("/")
195
+ .lower()
196
+ )
197
+ return os.path.realpath(slashed).rstrip("/").lower()
198
+
199
+
200
+ def _env_matches_gateway_home(env: dict[str, str], gateway_home: str | Path) -> bool:
201
+ """True only when the process environment positively targets this private ``gateway_home``."""
202
+ home_norm = _norm_path(gateway_home)
203
+ cfg_norm = _norm_path(Path(gateway_home) / ".config" / "magpie")
204
+ if not home_norm:
205
+ return False
206
+ upper = {k.upper(): v for k, v in env.items()}
207
+ if cfg := upper.get("MAGPIE_CONFIG_DIR", "").strip():
208
+ return _norm_path(cfg) == cfg_norm
209
+ userprofile = upper.get("USERPROFILE", "").strip()
210
+ if userprofile:
211
+ return _norm_path(userprofile) == home_norm
212
+ home = upper.get("HOME", "").strip()
213
+ return bool(home) and _norm_path(home) == home_norm
214
+
215
+
216
+ def _non_link_stat(path: Path) -> os.stat_result | None:
217
+ try:
218
+ info = path.lstat()
219
+ except OSError:
220
+ return None
221
+ if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:
222
+ return None
223
+ return info
224
+
225
+
226
+ def _serving_lock_pid(gateway_home: str | Path) -> int | None:
227
+ """PID stored in private non-symlink ``gateway.serving.lock`` if readable; None otherwise."""
228
+ home = Path(gateway_home)
229
+ for parent in (home, home / ".config", home / ".config" / "magpie"):
230
+ pinfo = _non_link_stat(parent)
231
+ if pinfo is None or not stat.S_ISDIR(pinfo.st_mode):
232
+ return None
233
+ lock = home / ".config" / "magpie" / "gateway.serving.lock"
234
+ info = _non_link_stat(lock)
235
+ if info is None or not stat.S_ISREG(info.st_mode):
236
+ return None
237
+ try:
238
+ if os.name == "nt":
239
+ runtime_io.private_permissions(lock)
240
+ raw = lock.read_text(encoding="utf-8").strip()
241
+ except (OSError, ValueError):
242
+ return None
243
+ if raw.isdigit():
244
+ return int(raw)
245
+ try:
246
+ doc = json.loads(raw)
247
+ except ValueError:
248
+ return None
249
+ pid = doc.get("pid") if isinstance(doc, dict) else None
250
+ return pid if isinstance(pid, int) and not isinstance(pid, bool) and pid > 0 else None
251
+
252
+
253
+ def magpie_successor_pid(
254
+ saved: process_identity.Identity,
255
+ program: str,
256
+ port: int,
257
+ gateway_home: str | Path | None = None,
258
+ ) -> int | None:
259
+ """Windows: identify a single verified multi-hop successor of an owned ``magpie serve``
260
+ listening on the approved ``port`` (for example after periodic self-restarts broke the
261
+ 1-hop parent-PID chain). Fails closed: requires positive proof linking the listener to
262
+ ``gateway_home`` (private ``gateway.serving.lock`` PID match or matching PEB environment)."""
263
+ if gateway_home is None:
264
+ return None
265
+ listeners = process_identity.listener_pids(port)
266
+ if not listeners or len(listeners) != 1:
267
+ return None
268
+ cand = next(iter(listeners))
269
+ if cand <= 0:
270
+ return None
271
+ found = process_identity._windows_inspect(cand)
272
+ if found is None or found["uid"] != 0 or int(found["started"]) <= int(saved["started"]):
273
+ return None
274
+ if not process_identity._windows_command_matches(cand, [program]):
275
+ return None
276
+ cmdline = process_windows.command_line(cand)
277
+ if cmdline is not None and not _is_magpie_serve_argv(split_windows_cmdline(cmdline)):
278
+ return None
279
+ lock_pid = _serving_lock_pid(gateway_home)
280
+ if lock_pid is not None:
281
+ return cand if lock_pid == cand else None
282
+ if cmdline is None:
283
+ return None
284
+ proc_env = process_environment(cand)
285
+ if proc_env is None or not _env_matches_gateway_home(proc_env, gateway_home):
286
+ return None
287
+ return cand
288
+
289
+
290
+ def adopt_magpie_successor(
291
+ pid_file: str | Path,
292
+ program: str,
293
+ port: int | None = None,
294
+ gateway_home: str | Path | None = None,
295
+ ) -> bool:
296
+ """Adopt a restarted Windows ``magpie serve``: 1-hop child first, then multi-hop listener."""
297
+ if process_identity.adopt_successor(pid_file, program):
298
+ return True
299
+ if not process_identity._windows() or port is None:
300
+ return False
301
+ path = Path(pid_file)
302
+ try:
303
+ saved = process_identity._recorded(path)
304
+ if saved is None or process_identity._windows_inspect(saved["pid"]) is not None:
305
+ return False
306
+ cand = magpie_successor_pid(saved, program, port, gateway_home)
307
+ if cand is None:
308
+ return False
309
+ process_identity.save(path, cand)
310
+ return True
311
+ except (OSError, ValueError, RuntimeError):
312
+ return False