@simplexai/localmodels-linux-arm64 0.1.0-dev.59 → 0.1.0-dev.61
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +126 -107
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +107 -44
- package/modules/localmodels/apple_sensors.py +431 -0
- package/modules/localmodels/auth_proxy.py +185 -19
- package/modules/localmodels/bifrost_admin.py +30 -0
- package/modules/localmodels/bifrost_checks.py +2 -2
- package/modules/localmodels/bifrost_config.py +132 -9
- package/modules/localmodels/bifrost_models.py +1 -1
- package/modules/localmodels/catalog.json +509 -54
- package/modules/localmodels/catalog.py +21 -4
- package/modules/localmodels/catalog_add.py +42 -11
- package/modules/localmodels/catalog_license.py +2 -0
- package/modules/localmodels/catalog_recipes.py +2 -0
- package/modules/localmodels/cli_parser.py +6 -2
- package/modules/localmodels/context_policy.py +40 -4
- package/modules/localmodels/custom_hub.py +983 -0
- package/modules/localmodels/custom_hub_http.py +579 -0
- package/modules/localmodels/custom_probe.py +451 -0
- package/modules/localmodels/debug_mode.py +13 -0
- package/modules/localmodels/debug_stub_server.py +156 -1
- package/modules/localmodels/deploy.py +38 -7
- package/modules/localmodels/deploy_steps.py +5 -0
- package/modules/localmodels/download-mirrors.json +20 -0
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
- package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
- package/modules/localmodels/engines-whisper-b5454.json +120 -1
- package/modules/localmodels/engines.py +38 -8
- package/modules/localmodels/estimator.py +60 -7
- package/modules/localmodels/gateway.py +48 -3
- package/modules/localmodels/gateway_app_bifrost.py +18 -18
- package/modules/localmodels/gateway_bifrost.py +102 -16
- package/modules/localmodels/gateway_cli.py +14 -80
- package/modules/localmodels/gateway_server.py +88 -16
- package/modules/localmodels/gguf.py +6 -0
- package/modules/localmodels/gpu_specs.py +35 -1
- package/modules/localmodels/harness.py +1 -2
- package/modules/localmodels/hf_repo.py +12 -4
- package/modules/localmodels/host_sensors.py +704 -0
- package/modules/localmodels/install.py +4 -4
- package/modules/localmodels/library_cli.py +181 -3
- package/modules/localmodels/library_custom.py +831 -0
- package/modules/localmodels/library_elastic.py +35 -7
- package/modules/localmodels/library_gateway.py +94 -32
- package/modules/localmodels/library_jobs.py +76 -11
- package/modules/localmodels/library_kept.py +50 -6
- package/modules/localmodels/library_model.py +254 -2
- package/modules/localmodels/library_pricing.py +83 -4
- package/modules/localmodels/library_serve.py +178 -60
- package/modules/localmodels/library_smoke.py +315 -0
- package/modules/localmodels/library_state.py +77 -1
- package/modules/localmodels/library_status.py +126 -4
- package/modules/localmodels/npm_transport.py +4 -58
- package/modules/localmodels/nvml_ctypes.py +431 -0
- package/modules/localmodels/plan_envelope.py +14 -6
- package/modules/localmodels/recommend_cli.py +2 -1
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/remote_ops.py +120 -665
- package/modules/localmodels/remote_ops_common.py +729 -0
- package/modules/localmodels/remote_ops_download.py +396 -241
- package/modules/localmodels/remote_ops_mirrors.py +26 -65
- package/modules/localmodels/remote_ops_prepare.py +43 -35
- package/modules/localmodels/remote_ops_ranges.py +98 -65
- package/modules/localmodels/remote_ops_remove.py +30 -22
- package/modules/localmodels/remote_ops_service.py +103 -95
- package/modules/localmodels/remote_ops_verify.py +113 -65
- package/modules/localmodels/runtime-lock.json +19 -19
- package/modules/localmodels/runtime_cli.py +15 -5
- package/modules/localmodels/runtime_io.py +54 -1
- package/modules/localmodels/service_control.py +32 -1
- package/modules/localmodels/service_wiring.py +2 -3
- package/modules/localmodels/service_worker.py +6 -2
- package/modules/localmodels/services_cli.py +35 -27
- package/modules/localmodels/source_byok.py +3 -5
- package/modules/localmodels/speech-sv.txt +93 -0
- package/modules/localmodels/speech_admission.py +437 -0
- package/modules/localmodels/speech_catalog.py +170 -0
- package/modules/localmodels/speech_cli.py +273 -0
- package/modules/localmodels/speech_jobs.py +772 -0
- package/modules/localmodels/speech_model.py +404 -0
- package/modules/localmodels/speech_serve.py +287 -0
- package/modules/localmodels/speech_server.py +837 -0
- package/modules/localmodels/speech_state.py +697 -0
- package/modules/localmodels/speech_worker_sensevoice.py +255 -0
- package/modules/localmodels/speech_workers.py +783 -0
- package/modules/localmodels/stack.py +0 -33
- package/modules/localmodels/stack_auto.py +5 -3
- package/modules/localmodels/stack_aux_gpu.py +45 -4
- package/modules/localmodels/stack_capacity.py +77 -8
- package/modules/localmodels/stack_cli.py +16 -1
- package/modules/localmodels/stack_compose.py +1 -1
- package/modules/localmodels/stack_down.py +24 -1
- package/modules/localmodels/stack_hardware.py +57 -88
- package/modules/localmodels/stack_hardware_text.py +4 -59
- package/modules/localmodels/stack_lifecycle.py +2 -2
- package/modules/localmodels/stack_memory.py +14 -3
- package/modules/localmodels/stack_suite.py +9 -10
- package/modules/localmodels/stack_summary.py +4 -4
- package/modules/localmodels/stack_view.py +77 -53
- package/modules/localmodels/stack_view_demo.py +36 -5
- package/modules/localmodels/stack_view_events.py +147 -12
- package/modules/localmodels/stack_view_gpu.py +97 -17
- package/modules/localmodels/stack_view_llm.py +16 -1
- package/modules/localmodels/stack_view_measure.py +4 -1
- package/modules/localmodels/stack_view_schema.py +54 -8
- package/modules/localmodels/stack_view_serve.py +40 -3
- package/modules/localmodels/stack_view_slots.py +89 -10
- package/modules/localmodels/stack_view_telemetry.py +163 -0
- package/modules/localmodels/stack_view_text.py +5 -2
- package/modules/localmodels/stack_view_tick.py +658 -0
- package/modules/localmodels/stack_view_words.py +4 -0
- package/modules/localmodels/{strata-poly-serve-0.2.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
- package/modules/localmodels/suite.py +3 -1
- package/modules/localmodels/telemetry_math.py +538 -0
- package/modules/localmodels/transport.py +3 -2
- package/modules/localmodels/tui_views.py +2 -2
- package/modules/localmodels/web/view/view.js +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +123 -104
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/bifrost_datasheet.py +0 -53
- package/modules/localmodels/bifrost_provider.py +0 -88
- package/modules/localmodels/bifrost_unit.py +0 -99
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +0 -94
- package/modules/localmodels/gateway_switch.py +0 -51
- package/modules/localmodels/library_floor.py +0 -78
- package/modules/localmodels/service_stop.py +0 -52
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
"""Zero-sudo Apple Silicon hardware telemetry (AppleSMC, vm_stat/sysctl, IOAccelerator).
|
|
2
|
+
|
|
3
|
+
Never invokes ``sudo`` or ``powermetrics``. On non-macOS hosts or whenever a private IOKit/SMC
|
|
4
|
+
framework or sensor is unavailable or permission-denied, each sensor degrades independently to
|
|
5
|
+
``value: None, basis: "none"``. IOReport channel sampling is currently inactive without private
|
|
6
|
+
entitlements and reports ``basis: "none"``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import ctypes
|
|
12
|
+
import re
|
|
13
|
+
import struct
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
from typing import Any, TypedDict
|
|
17
|
+
|
|
18
|
+
_IOREPORT_LIB = "/usr/lib/libIOReport.dylib"
|
|
19
|
+
_IOKIT_LIB = "/System/Library/Frameworks/IOKit.framework/IOKit"
|
|
20
|
+
_CF_LIB = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"
|
|
21
|
+
|
|
22
|
+
# AppleSMC user-client constants (IOConnectCallStructMethod selector 2 = KERNEL_INDEX_SMC)
|
|
23
|
+
_KERNEL_INDEX_SMC = 2
|
|
24
|
+
_SMC_CMD_READ_KEYINFO = 9
|
|
25
|
+
_SMC_CMD_READ_BYTES = 5
|
|
26
|
+
# Candidate Apple Silicon GPU/SoC die temperature SMC keys (tried in order; first valid wins)
|
|
27
|
+
_SMC_TEMP_KEYS = (b"Tg05", b"Tg0D", b"Tp01", b"Tp09", b"TC0P", b"TC0C")
|
|
28
|
+
_PRESSURE_LABELS = {1: "nominal", 2: "elevated", 4: "critical"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SensorReading(TypedDict):
|
|
32
|
+
value: float | None
|
|
33
|
+
basis: str # live | none
|
|
34
|
+
note: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ExternalGpuHolder(TypedDict):
|
|
38
|
+
name: str
|
|
39
|
+
pid: int
|
|
40
|
+
bytes: int
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class AppleTelemetry(TypedDict):
|
|
44
|
+
gpu_util_pct: SensorReading
|
|
45
|
+
power_w: SensorReading
|
|
46
|
+
temp_c: SensorReading
|
|
47
|
+
memory_pressure: str # nominal | elevated | critical | unknown
|
|
48
|
+
memory_pressure_basis: str # live | none
|
|
49
|
+
swap_used_bytes: int | None
|
|
50
|
+
gpu_in_use_bytes: int | None
|
|
51
|
+
holders: list[ExternalGpuHolder]
|
|
52
|
+
collector: str
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _missing(note: str) -> SensorReading:
|
|
56
|
+
return {"value": None, "basis": "none", "note": note}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _live(value: float, note: str, digits: int = 1) -> SensorReading:
|
|
60
|
+
return {"value": round(value, digits), "basis": "live", "note": note}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def decode_smc_temperature(data_type: bytes, raw: bytes) -> float | None:
|
|
64
|
+
"""Decode an AppleSMC temperature payload (``sp78`` fixed-point or IEEE ``flt ``)."""
|
|
65
|
+
if data_type == b"sp78" and len(raw) >= 2:
|
|
66
|
+
signed = struct.unpack(">h", raw[:2])[0]
|
|
67
|
+
temp = signed / 256.0
|
|
68
|
+
elif data_type == b"flt " and len(raw) >= 4:
|
|
69
|
+
temp = float(struct.unpack("<f", raw[:4])[0])
|
|
70
|
+
else:
|
|
71
|
+
return None
|
|
72
|
+
return round(temp, 1) if -20.0 <= temp <= 130.0 else None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_ioreport_gpu_residency(state_ticks: dict[str, int]) -> float | None:
|
|
76
|
+
"""Compute GPU active residency % from IOReport state residency ticks.
|
|
77
|
+
|
|
78
|
+
Idle/off states (``IDLE``, ``OFF``, ``DOWN``) are excluded from the active numerator.
|
|
79
|
+
"""
|
|
80
|
+
if not state_ticks:
|
|
81
|
+
return None
|
|
82
|
+
total = 0
|
|
83
|
+
active = 0
|
|
84
|
+
for state, ticks in state_ticks.items():
|
|
85
|
+
if ticks < 0:
|
|
86
|
+
continue
|
|
87
|
+
total += ticks
|
|
88
|
+
upper = state.strip().upper()
|
|
89
|
+
if upper not in ("IDLE", "OFF", "DOWN", ""):
|
|
90
|
+
active += ticks
|
|
91
|
+
if total <= 0:
|
|
92
|
+
return None
|
|
93
|
+
return round(min(100.0, max(0.0, (active / total) * 100.0)), 1)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def parse_ioreport_power_w(energy_nj: float, elapsed_s: float) -> float | None:
|
|
97
|
+
"""Convert IOReport energy delta (nanojoules) over ``elapsed_s`` seconds into watts."""
|
|
98
|
+
if elapsed_s <= 0 or energy_nj < 0:
|
|
99
|
+
return None
|
|
100
|
+
watts = (energy_nj / 1e9) / elapsed_s
|
|
101
|
+
return round(watts, 2) if 0.0 <= watts <= 500.0 else None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def parse_pressure_level(text: str) -> tuple[str, str]:
|
|
105
|
+
"""Map macOS ``kern.memorystatus_vm_pressure_level`` integer to canonical level + basis."""
|
|
106
|
+
try:
|
|
107
|
+
code = int(text.strip())
|
|
108
|
+
except ValueError:
|
|
109
|
+
return "unknown", "none"
|
|
110
|
+
label = _PRESSURE_LABELS.get(code)
|
|
111
|
+
return (label, "live") if label is not None else ("unknown", "none")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def parse_swap_used_bytes(text: str) -> int | None:
|
|
115
|
+
"""Parse ``sysctl -n vm.swapusage`` used bytes."""
|
|
116
|
+
match = re.search(r"used\s*=\s*([\d.]+)\s*([KMG])", text)
|
|
117
|
+
if not match:
|
|
118
|
+
return None
|
|
119
|
+
scale = {"K": 1 << 10, "M": 1 << 20, "G": 1 << 30}[match.group(2)]
|
|
120
|
+
return int(float(match.group(1)) * scale)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
_CREATOR_RE = re.compile(r'"IOUserClientCreator"\s*=\s*"pid\s+(\d+),\s*([^"]+)"')
|
|
124
|
+
_ALLOC_RE = re.compile(r'"(?:In use system memory|Alloc system memory|phys_footprint)"\s*=\s*(\d+)')
|
|
125
|
+
_NODE_HEADER_MARKER = "+-o "
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _ioreg_indent(line: str) -> int:
|
|
129
|
+
idx = 0
|
|
130
|
+
while idx < len(line) and line[idx] in " |":
|
|
131
|
+
idx += 1
|
|
132
|
+
return idx
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def parse_ioaccelerator_holders(
|
|
136
|
+
text: str,
|
|
137
|
+
*,
|
|
138
|
+
exclude_pids: set[int] | None = None,
|
|
139
|
+
min_bytes: int = 16 << 20,
|
|
140
|
+
limit: int = 8,
|
|
141
|
+
) -> list[ExternalGpuHolder]:
|
|
142
|
+
"""Extract external processes holding GPU memory from ``ioreg -r -c AGXAccelerator`` output."""
|
|
143
|
+
skip = exclude_pids or set()
|
|
144
|
+
by_pid: dict[int, tuple[str, int]] = {}
|
|
145
|
+
current_pid: int | None = None
|
|
146
|
+
current_name = ""
|
|
147
|
+
creator_indent: int | None = None
|
|
148
|
+
for line in text.splitlines():
|
|
149
|
+
if _NODE_HEADER_MARKER in line:
|
|
150
|
+
current_pid = None
|
|
151
|
+
current_name = ""
|
|
152
|
+
creator_indent = None
|
|
153
|
+
continue
|
|
154
|
+
indent = _ioreg_indent(line)
|
|
155
|
+
stripped = line[indent:].strip()
|
|
156
|
+
if creator_indent is not None and stripped.startswith("}") and indent < creator_indent:
|
|
157
|
+
current_pid = None
|
|
158
|
+
current_name = ""
|
|
159
|
+
creator_indent = None
|
|
160
|
+
continue
|
|
161
|
+
creator = _CREATOR_RE.search(line)
|
|
162
|
+
if creator:
|
|
163
|
+
current_pid = int(creator.group(1))
|
|
164
|
+
current_name = creator.group(2).strip()[:128]
|
|
165
|
+
creator_indent = indent
|
|
166
|
+
continue
|
|
167
|
+
if current_pid is not None:
|
|
168
|
+
alloc = _ALLOC_RE.search(line)
|
|
169
|
+
if alloc:
|
|
170
|
+
size = int(alloc.group(1))
|
|
171
|
+
if current_pid not in skip and size > 0:
|
|
172
|
+
prev_name, prev_size = by_pid.get(current_pid, (current_name, 0))
|
|
173
|
+
by_pid[current_pid] = (prev_name or current_name, max(prev_size, size))
|
|
174
|
+
ranked = sorted(
|
|
175
|
+
((name, pid, size) for pid, (name, size) in by_pid.items() if size >= min_bytes),
|
|
176
|
+
key=lambda row: (-row[2], row[0].lower()),
|
|
177
|
+
)
|
|
178
|
+
return [{"name": name, "pid": pid, "bytes": size} for name, pid, size in ranked[:limit]]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class _SmcKeyDataVers(ctypes.Structure):
|
|
182
|
+
_fields_ = [
|
|
183
|
+
("major", ctypes.c_uint8),
|
|
184
|
+
("minor", ctypes.c_uint8),
|
|
185
|
+
("build", ctypes.c_uint8),
|
|
186
|
+
("reserved", ctypes.c_uint8),
|
|
187
|
+
("release", ctypes.c_uint16),
|
|
188
|
+
]
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class _SmcKeyDataPLimit(ctypes.Structure):
|
|
192
|
+
_fields_ = [
|
|
193
|
+
("version", ctypes.c_uint16),
|
|
194
|
+
("length", ctypes.c_uint16),
|
|
195
|
+
("cpuPLimit", ctypes.c_uint32),
|
|
196
|
+
("gpuPLimit", ctypes.c_uint32),
|
|
197
|
+
("memPLimit", ctypes.c_uint32),
|
|
198
|
+
]
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class _SmcKeyDataKeyInfo(ctypes.Structure):
|
|
202
|
+
_fields_ = [
|
|
203
|
+
("dataSize", ctypes.c_uint32),
|
|
204
|
+
("dataType", ctypes.c_uint32),
|
|
205
|
+
("dataAttributes", ctypes.c_uint8),
|
|
206
|
+
]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class _SmcKeyData(ctypes.Structure):
|
|
210
|
+
_fields_ = [
|
|
211
|
+
("key", ctypes.c_uint32),
|
|
212
|
+
("vers", _SmcKeyDataVers),
|
|
213
|
+
("pLimitData", _SmcKeyDataPLimit),
|
|
214
|
+
("keyInfo", _SmcKeyDataKeyInfo),
|
|
215
|
+
("result", ctypes.c_uint8),
|
|
216
|
+
("status", ctypes.c_uint8),
|
|
217
|
+
("data8", ctypes.c_uint8),
|
|
218
|
+
("data32", ctypes.c_uint32),
|
|
219
|
+
("bytes", ctypes.c_uint8 * 32),
|
|
220
|
+
]
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _smc_fourcc(key: bytes) -> int:
|
|
224
|
+
return int.from_bytes(key[:4], "big")
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def mach_task_self(libc: Any | None = None) -> int:
|
|
228
|
+
"""Return the current macOS Mach task port without calling the C macro ``mach_task_self()``."""
|
|
229
|
+
lib = ctypes.cdll.LoadLibrary("/usr/lib/libSystem.B.dylib") if libc is None else libc
|
|
230
|
+
try:
|
|
231
|
+
return int(ctypes.c_uint.in_dll(lib, "mach_task_self_").value)
|
|
232
|
+
except (ValueError, OSError, TypeError, AttributeError):
|
|
233
|
+
trap = lib.task_self_trap
|
|
234
|
+
trap.argtypes = []
|
|
235
|
+
trap.restype = ctypes.c_uint
|
|
236
|
+
return int(trap())
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _bind_iokit(iokit: Any) -> None:
|
|
240
|
+
iokit.IOServiceMatching.argtypes = [ctypes.c_char_p]
|
|
241
|
+
iokit.IOServiceMatching.restype = ctypes.c_void_p
|
|
242
|
+
iokit.IOServiceGetMatchingService.argtypes = [ctypes.c_uint, ctypes.c_void_p]
|
|
243
|
+
iokit.IOServiceGetMatchingService.restype = ctypes.c_uint
|
|
244
|
+
iokit.IOServiceOpen.argtypes = [
|
|
245
|
+
ctypes.c_uint,
|
|
246
|
+
ctypes.c_uint,
|
|
247
|
+
ctypes.c_uint,
|
|
248
|
+
ctypes.POINTER(ctypes.c_uint),
|
|
249
|
+
]
|
|
250
|
+
iokit.IOServiceOpen.restype = ctypes.c_int
|
|
251
|
+
iokit.IOConnectCallStructMethod.argtypes = [
|
|
252
|
+
ctypes.c_uint,
|
|
253
|
+
ctypes.c_uint32,
|
|
254
|
+
ctypes.c_void_p,
|
|
255
|
+
ctypes.c_size_t,
|
|
256
|
+
ctypes.c_void_p,
|
|
257
|
+
ctypes.POINTER(ctypes.c_size_t),
|
|
258
|
+
]
|
|
259
|
+
iokit.IOConnectCallStructMethod.restype = ctypes.c_int
|
|
260
|
+
iokit.IOServiceClose.argtypes = [ctypes.c_uint]
|
|
261
|
+
iokit.IOServiceClose.restype = ctypes.c_int
|
|
262
|
+
iokit.IOObjectRelease.argtypes = [ctypes.c_uint]
|
|
263
|
+
iokit.IOObjectRelease.restype = ctypes.c_int
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def read_smc_temperature() -> SensorReading:
|
|
267
|
+
"""Read Apple Silicon die temperature via IOKit ``AppleSMC`` without sudo."""
|
|
268
|
+
if sys.platform != "darwin":
|
|
269
|
+
return _missing("AppleSMC is available on macOS only")
|
|
270
|
+
try:
|
|
271
|
+
iokit = ctypes.cdll.LoadLibrary(_IOKIT_LIB)
|
|
272
|
+
_bind_iokit(iokit)
|
|
273
|
+
matching = iokit.IOServiceMatching(b"AppleSMC")
|
|
274
|
+
if not matching:
|
|
275
|
+
return _missing("AppleSMC service not found")
|
|
276
|
+
service = int(iokit.IOServiceGetMatchingService(0, ctypes.c_void_p(matching)))
|
|
277
|
+
if not service:
|
|
278
|
+
return _missing("AppleSMC service unavailable")
|
|
279
|
+
try:
|
|
280
|
+
conn = ctypes.c_uint(0)
|
|
281
|
+
mach_self = mach_task_self()
|
|
282
|
+
if iokit.IOServiceOpen(service, mach_self, 0, ctypes.byref(conn)) != 0:
|
|
283
|
+
return _missing("AppleSMC IOServiceOpen refused")
|
|
284
|
+
try:
|
|
285
|
+
for key in _SMC_TEMP_KEYS:
|
|
286
|
+
reading = _read_smc_key(iokit, conn.value, key)
|
|
287
|
+
if reading is not None:
|
|
288
|
+
return _live(reading, "AppleSMC die temperature")
|
|
289
|
+
finally:
|
|
290
|
+
iokit.IOServiceClose(conn.value)
|
|
291
|
+
finally:
|
|
292
|
+
iokit.IOObjectRelease(service)
|
|
293
|
+
except (OSError, AttributeError, ValueError):
|
|
294
|
+
return _missing("AppleSMC unavailable")
|
|
295
|
+
return _missing("AppleSMC temperature key unavailable")
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _read_smc_key(iokit: Any, conn: int, key: bytes) -> float | None:
|
|
299
|
+
inp = _SmcKeyData()
|
|
300
|
+
out = _SmcKeyData()
|
|
301
|
+
inp.key = _smc_fourcc(key)
|
|
302
|
+
inp.data8 = _SMC_CMD_READ_KEYINFO
|
|
303
|
+
out_size = ctypes.c_size_t(ctypes.sizeof(out))
|
|
304
|
+
rc = iokit.IOConnectCallStructMethod(
|
|
305
|
+
conn,
|
|
306
|
+
_KERNEL_INDEX_SMC,
|
|
307
|
+
ctypes.byref(inp),
|
|
308
|
+
ctypes.sizeof(inp),
|
|
309
|
+
ctypes.byref(out),
|
|
310
|
+
ctypes.byref(out_size),
|
|
311
|
+
)
|
|
312
|
+
if rc != 0 or out.keyInfo.dataSize == 0 or out.keyInfo.dataSize > 32:
|
|
313
|
+
return None
|
|
314
|
+
dtype = out.keyInfo.dataType.to_bytes(4, "big")
|
|
315
|
+
inp.keyInfo.dataSize = out.keyInfo.dataSize
|
|
316
|
+
inp.data8 = _SMC_CMD_READ_BYTES
|
|
317
|
+
out_size = ctypes.c_size_t(ctypes.sizeof(out))
|
|
318
|
+
rc = iokit.IOConnectCallStructMethod(
|
|
319
|
+
conn,
|
|
320
|
+
_KERNEL_INDEX_SMC,
|
|
321
|
+
ctypes.byref(inp),
|
|
322
|
+
ctypes.sizeof(inp),
|
|
323
|
+
ctypes.byref(out),
|
|
324
|
+
ctypes.byref(out_size),
|
|
325
|
+
)
|
|
326
|
+
if rc != 0:
|
|
327
|
+
return None
|
|
328
|
+
raw = bytes(out.bytes[: out.keyInfo.dataSize])
|
|
329
|
+
return decode_smc_temperature(dtype, raw)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def read_ioreport_gpu_and_power() -> tuple[SensorReading, SensorReading]:
|
|
333
|
+
"""Read Apple Silicon GPU residency (%) and package power (W) via user-space IOReport.
|
|
334
|
+
|
|
335
|
+
Degrades gracefully to ``basis: "none"`` when ``libIOReport.dylib`` or channels are unavailable.
|
|
336
|
+
"""
|
|
337
|
+
if sys.platform != "darwin":
|
|
338
|
+
return (
|
|
339
|
+
_missing("IOReport GPU residency is available on macOS only"),
|
|
340
|
+
_missing("IOReport package power is available on macOS only"),
|
|
341
|
+
)
|
|
342
|
+
try:
|
|
343
|
+
ioreport = ctypes.cdll.LoadLibrary(_IOREPORT_LIB)
|
|
344
|
+
cf = ctypes.cdll.LoadLibrary(_CF_LIB)
|
|
345
|
+
# Verify required entry points exist before invoking private symbols.
|
|
346
|
+
for sym in (
|
|
347
|
+
"IOReportCopyChannelsInGroup",
|
|
348
|
+
"IOReportCreateSubscription",
|
|
349
|
+
"IOReportCreateSamples",
|
|
350
|
+
"IOReportCreateSamplesDelta",
|
|
351
|
+
):
|
|
352
|
+
if not hasattr(ioreport, sym):
|
|
353
|
+
return _missing("IOReport symbol unavailable"), _missing(
|
|
354
|
+
"IOReport symbol unavailable"
|
|
355
|
+
)
|
|
356
|
+
if not hasattr(cf, "CFStringCreateWithCString") or not hasattr(cf, "CFRelease"):
|
|
357
|
+
return _missing("CoreFoundation unavailable"), _missing("CoreFoundation unavailable")
|
|
358
|
+
except OSError:
|
|
359
|
+
return _missing("libIOReport unavailable"), _missing("libIOReport unavailable")
|
|
360
|
+
# Private IOReport dictionary iteration requires CFAllocator/CFArray callbacks that vary across
|
|
361
|
+
# macOS releases; fail closed to basis="none" rather than risking a segfault or invoking sudo.
|
|
362
|
+
return (
|
|
363
|
+
_missing("IOReport channel telemetry unavailable without entitlements"),
|
|
364
|
+
_missing("IOReport power telemetry unavailable without entitlements"),
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _sysctl(key: str) -> str | None:
|
|
369
|
+
if sys.platform != "darwin":
|
|
370
|
+
return None
|
|
371
|
+
try:
|
|
372
|
+
proc = subprocess.run(
|
|
373
|
+
["/usr/sbin/sysctl", "-n", key],
|
|
374
|
+
capture_output=True,
|
|
375
|
+
text=True,
|
|
376
|
+
timeout=1.5,
|
|
377
|
+
check=False,
|
|
378
|
+
)
|
|
379
|
+
return proc.stdout if proc.returncode == 0 else None
|
|
380
|
+
except (OSError, subprocess.SubprocessError):
|
|
381
|
+
return None
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _ioreg_agx() -> str | None:
|
|
385
|
+
if sys.platform != "darwin":
|
|
386
|
+
return None
|
|
387
|
+
try:
|
|
388
|
+
proc = subprocess.run(
|
|
389
|
+
["/usr/sbin/ioreg", "-r", "-c", "AGXAccelerator"],
|
|
390
|
+
capture_output=True,
|
|
391
|
+
text=True,
|
|
392
|
+
timeout=1.5,
|
|
393
|
+
check=False,
|
|
394
|
+
)
|
|
395
|
+
return proc.stdout if proc.returncode == 0 else None
|
|
396
|
+
except (OSError, subprocess.SubprocessError):
|
|
397
|
+
return None
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def read_memory_pressure() -> tuple[str, str, int | None]:
|
|
401
|
+
"""Read macOS unified memory pressure level, basis, and swap usage via sysctl."""
|
|
402
|
+
raw_level = _sysctl("kern.memorystatus_vm_pressure_level")
|
|
403
|
+
level, basis = parse_pressure_level(raw_level) if raw_level is not None else ("unknown", "none")
|
|
404
|
+
raw_swap = _sysctl("vm.swapusage")
|
|
405
|
+
swap_bytes = parse_swap_used_bytes(raw_swap) if raw_swap is not None else None
|
|
406
|
+
return level, basis, swap_bytes
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def read_telemetry(*, exclude_pids: set[int] | None = None) -> AppleTelemetry:
|
|
410
|
+
"""Collect zero-sudo Apple Silicon telemetry; every unavailable field reports basis='none'."""
|
|
411
|
+
gpu_util, power_w = read_ioreport_gpu_and_power()
|
|
412
|
+
temp_c = read_smc_temperature()
|
|
413
|
+
level, pressure_basis, swap_bytes = read_memory_pressure()
|
|
414
|
+
agx_text = _ioreg_agx()
|
|
415
|
+
in_use: int | None = None
|
|
416
|
+
holders: list[ExternalGpuHolder] = []
|
|
417
|
+
if agx_text:
|
|
418
|
+
matches = [int(m) for m in re.findall(r'"In use system memory"\s*=\s*(\d+)', agx_text)]
|
|
419
|
+
in_use = max(matches) if matches else None
|
|
420
|
+
holders = parse_ioaccelerator_holders(agx_text, exclude_pids=exclude_pids)
|
|
421
|
+
return {
|
|
422
|
+
"gpu_util_pct": gpu_util,
|
|
423
|
+
"power_w": power_w,
|
|
424
|
+
"temp_c": temp_c,
|
|
425
|
+
"memory_pressure": level,
|
|
426
|
+
"memory_pressure_basis": pressure_basis,
|
|
427
|
+
"swap_used_bytes": swap_bytes,
|
|
428
|
+
"gpu_in_use_bytes": in_use,
|
|
429
|
+
"holders": holders,
|
|
430
|
+
"collector": "AppleSMC · sysctl · IOAccelerator",
|
|
431
|
+
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
"""API-key front for a loopback server that has no authentication of its own (whisper-server).
|
|
2
2
|
|
|
3
|
-
Copied beside a deployment and run by its service:
|
|
3
|
+
Copied beside a deployment and run by its service:
|
|
4
|
+
``python3 auth_proxy.py [--watchdog-ppid PID] PORT KEY_FILE -- CMD``.
|
|
4
5
|
It starts CMD with ``{upstream_port}`` replaced by a free loopback port, then serves PORT on
|
|
5
6
|
127.0.0.1: a request without ``Authorization: Bearer <key>`` gets 401, anything else is passed
|
|
6
7
|
on to CMD and its answer returned. The proxy exits when CMD does, with its exit code, and stops
|
|
7
|
-
CMD when the service stops it
|
|
8
|
-
|
|
8
|
+
CMD when the service stops it (or when the optional parent-PID watchdog detects that its parent
|
|
9
|
+
process died). CMD still listens unauthenticated on its own loopback port; the proxy makes the
|
|
10
|
+
documented port require the key like every other suite service.
|
|
9
11
|
|
|
10
12
|
Standard library only; runs on the target host's python3 (3.8 or newer).
|
|
11
13
|
"""
|
|
@@ -16,6 +18,7 @@ import hmac
|
|
|
16
18
|
import http.client
|
|
17
19
|
import http.server
|
|
18
20
|
import io
|
|
21
|
+
import os
|
|
19
22
|
import selectors
|
|
20
23
|
import signal
|
|
21
24
|
import socket
|
|
@@ -25,6 +28,7 @@ import threading
|
|
|
25
28
|
import time
|
|
26
29
|
from email.message import Message
|
|
27
30
|
from pathlib import Path
|
|
31
|
+
from typing import Callable
|
|
28
32
|
|
|
29
33
|
# Hop-by-hop headers and those this proxy sets itself.
|
|
30
34
|
DROPPED = {
|
|
@@ -41,11 +45,117 @@ DROPPED = {
|
|
|
41
45
|
}
|
|
42
46
|
TIMEOUT_S = 900
|
|
43
47
|
KILL_AFTER_S = 10.0 # the backend's time to exit on SIGTERM before SIGKILL
|
|
48
|
+
WATCHDOG_PPID_ENV = "LOCALMODELS_WATCHDOG_PPID"
|
|
49
|
+
WATCHDOG_INTERVAL_S = 2.0
|
|
44
50
|
|
|
45
51
|
|
|
46
52
|
DISCARD_MAX = 256 << 20 # a refused upload larger than this is cut off, not read
|
|
47
53
|
|
|
48
54
|
|
|
55
|
+
def resolve_watchdog_ppid(cli_value: int | None) -> int | None:
|
|
56
|
+
"""Resolve the expected parent PID from CLI flag or environment variable.
|
|
57
|
+
|
|
58
|
+
Precedence: ``--watchdog-ppid`` (CLI) > ``LOCALMODELS_WATCHDOG_PPID`` (env).
|
|
59
|
+
Missing, non-integer, or ``<= 1`` values return ``None`` (watchdog disabled).
|
|
60
|
+
"""
|
|
61
|
+
if cli_value is not None:
|
|
62
|
+
return cli_value if cli_value > 1 else None
|
|
63
|
+
raw = os.environ.get(WATCHDOG_PPID_ENV)
|
|
64
|
+
if not raw:
|
|
65
|
+
return None
|
|
66
|
+
try:
|
|
67
|
+
parsed = int(raw)
|
|
68
|
+
except ValueError:
|
|
69
|
+
return None
|
|
70
|
+
return parsed if parsed > 1 else None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _watchdog_loop(
|
|
74
|
+
expected_ppid: int,
|
|
75
|
+
interval: float,
|
|
76
|
+
on_orphan: Callable[[int, int], None],
|
|
77
|
+
stop_event: threading.Event,
|
|
78
|
+
) -> None:
|
|
79
|
+
while not stop_event.wait(interval):
|
|
80
|
+
getppid: Callable[[], int] | None = getattr(os, "getppid", None)
|
|
81
|
+
if getppid is None:
|
|
82
|
+
return
|
|
83
|
+
try:
|
|
84
|
+
observed = getppid()
|
|
85
|
+
except OSError:
|
|
86
|
+
return
|
|
87
|
+
if observed != expected_ppid:
|
|
88
|
+
on_orphan(expected_ppid, observed)
|
|
89
|
+
return
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def install_parent_watchdog(
|
|
93
|
+
expected_ppid: int | None,
|
|
94
|
+
on_orphan: Callable[[int, int], None],
|
|
95
|
+
*,
|
|
96
|
+
interval: float = WATCHDOG_INTERVAL_S,
|
|
97
|
+
) -> threading.Event | None:
|
|
98
|
+
"""Poll ``os.getppid()`` in a daemon thread and fire ``on_orphan`` if the parent changes.
|
|
99
|
+
|
|
100
|
+
No-op when ``expected_ppid`` is ``None`` or ``<= 1``, or on platforms lacking ``os.getppid``.
|
|
101
|
+
Polls immediately at install time to catch a supervisor that died between spawn and startup.
|
|
102
|
+
Returns a ``threading.Event`` that disarms the watchdog when set, or ``None`` if no thread
|
|
103
|
+
was started (disabled or already orphaned).
|
|
104
|
+
"""
|
|
105
|
+
if expected_ppid is None or expected_ppid <= 1:
|
|
106
|
+
return None
|
|
107
|
+
getppid: Callable[[], int] | None = getattr(os, "getppid", None)
|
|
108
|
+
if getppid is None:
|
|
109
|
+
return None
|
|
110
|
+
try:
|
|
111
|
+
observed = getppid()
|
|
112
|
+
except OSError:
|
|
113
|
+
return None
|
|
114
|
+
if observed != expected_ppid:
|
|
115
|
+
on_orphan(expected_ppid, observed)
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
stop_event = threading.Event()
|
|
119
|
+
poll_interval = max(0.01, float(interval))
|
|
120
|
+
thread = threading.Thread(
|
|
121
|
+
target=_watchdog_loop,
|
|
122
|
+
name="auth-proxy-parent-watchdog",
|
|
123
|
+
args=(expected_ppid, poll_interval, on_orphan, stop_event),
|
|
124
|
+
daemon=True,
|
|
125
|
+
)
|
|
126
|
+
thread.start()
|
|
127
|
+
return stop_event
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _parse_args(argv: list[str]) -> tuple[int, str, list[str], int | None] | None:
|
|
131
|
+
cli_ppid: int | None = None
|
|
132
|
+
index = 0
|
|
133
|
+
while index < len(argv) and argv[index].startswith("--") and argv[index] != "--":
|
|
134
|
+
arg = argv[index]
|
|
135
|
+
if arg == "--watchdog-ppid":
|
|
136
|
+
if index + 1 >= len(argv):
|
|
137
|
+
return None
|
|
138
|
+
raw = argv[index + 1]
|
|
139
|
+
index += 2
|
|
140
|
+
elif arg.startswith("--watchdog-ppid="):
|
|
141
|
+
raw = arg.split("=", 1)[1]
|
|
142
|
+
index += 1
|
|
143
|
+
else:
|
|
144
|
+
return None
|
|
145
|
+
try:
|
|
146
|
+
cli_ppid = int(raw)
|
|
147
|
+
except ValueError:
|
|
148
|
+
return None
|
|
149
|
+
rest = argv[index:]
|
|
150
|
+
if len(rest) < 4 or rest[2] != "--":
|
|
151
|
+
return None
|
|
152
|
+
try:
|
|
153
|
+
port = int(rest[0])
|
|
154
|
+
except ValueError:
|
|
155
|
+
return None
|
|
156
|
+
return port, rest[1], rest[3:], cli_ppid
|
|
157
|
+
|
|
158
|
+
|
|
49
159
|
def _http_version(version: str) -> tuple[int, int]:
|
|
50
160
|
"""Numeric (major, minor) of an HTTP request version string, defaulting to (1, 0)."""
|
|
51
161
|
if not version.startswith("HTTP/"):
|
|
@@ -403,16 +513,59 @@ def handler(
|
|
|
403
513
|
return Forward
|
|
404
514
|
|
|
405
515
|
|
|
516
|
+
def _kill_if_running(child: subprocess.Popen[bytes]) -> None:
|
|
517
|
+
if child.poll() is None:
|
|
518
|
+
try:
|
|
519
|
+
child.kill()
|
|
520
|
+
except OSError:
|
|
521
|
+
pass
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def _terminate_if_running(child: subprocess.Popen[bytes]) -> None:
|
|
525
|
+
if child.poll() is None:
|
|
526
|
+
try:
|
|
527
|
+
child.terminate()
|
|
528
|
+
except OSError:
|
|
529
|
+
pass
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _stop_child(child: subprocess.Popen[bytes]) -> None:
|
|
533
|
+
if child.poll() is not None:
|
|
534
|
+
return
|
|
535
|
+
_terminate_if_running(child)
|
|
536
|
+
# whisper-server b5454 can hang on SIGTERM; it must not keep this proxy and its port up.
|
|
537
|
+
killer = threading.Timer(KILL_AFTER_S, _kill_if_running, args=(child,))
|
|
538
|
+
killer.daemon = True
|
|
539
|
+
killer.start()
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def _log_orphan(expected: int, observed: int) -> None:
|
|
543
|
+
try:
|
|
544
|
+
print(
|
|
545
|
+
f"auth_proxy: parent watchdog triggered "
|
|
546
|
+
f"(expected_ppid={expected}, observed_ppid={observed}); shutting down",
|
|
547
|
+
file=sys.stderr,
|
|
548
|
+
flush=True,
|
|
549
|
+
)
|
|
550
|
+
except OSError:
|
|
551
|
+
pass
|
|
552
|
+
|
|
553
|
+
|
|
406
554
|
def main(argv: list[str]) -> int:
|
|
407
|
-
|
|
408
|
-
|
|
555
|
+
parsed = _parse_args(argv)
|
|
556
|
+
if parsed is None:
|
|
557
|
+
print(
|
|
558
|
+
"usage: auth_proxy.py [--watchdog-ppid PID] PORT KEY_FILE -- CMD [ARG...]",
|
|
559
|
+
file=sys.stderr,
|
|
560
|
+
)
|
|
409
561
|
return 2
|
|
410
|
-
port, key_file, cmd =
|
|
562
|
+
port, key_file, cmd, cli_ppid = parsed
|
|
411
563
|
with open(key_file, encoding="utf-8") as f:
|
|
412
564
|
key = f.read().strip()
|
|
413
565
|
if not key:
|
|
414
566
|
print("auth_proxy: empty key file", file=sys.stderr)
|
|
415
567
|
return 2
|
|
568
|
+
expected_ppid = resolve_watchdog_ppid(cli_ppid)
|
|
416
569
|
upstream = free_port()
|
|
417
570
|
# Whisper's conversion scratch files belong beside its deployment key, never in
|
|
418
571
|
# the controller's inherited (possibly sealed) installation directory.
|
|
@@ -423,31 +576,44 @@ def main(argv: list[str]) -> int:
|
|
|
423
576
|
server = http.server.ThreadingHTTPServer(("127.0.0.1", port), handler(key, upstream))
|
|
424
577
|
server.daemon_threads = True
|
|
425
578
|
|
|
426
|
-
def kill_if_running() -> None:
|
|
427
|
-
if child.poll() is None:
|
|
428
|
-
child.kill()
|
|
429
|
-
|
|
430
579
|
def stop(*_: object) -> None:
|
|
431
|
-
child
|
|
432
|
-
# whisper-server b5454 can hang on SIGTERM; it must not keep this proxy and its port up.
|
|
433
|
-
killer = threading.Timer(KILL_AFTER_S, kill_if_running)
|
|
434
|
-
killer.daemon = True
|
|
435
|
-
killer.start()
|
|
580
|
+
_stop_child(child)
|
|
436
581
|
|
|
437
582
|
signal.signal(signal.SIGTERM, stop)
|
|
438
583
|
signal.signal(signal.SIGINT, stop)
|
|
439
584
|
|
|
585
|
+
state_lock = threading.Lock()
|
|
586
|
+
orphaned = False
|
|
587
|
+
serve_entered = False
|
|
588
|
+
|
|
589
|
+
def on_orphan(expected: int, observed: int) -> None:
|
|
590
|
+
nonlocal orphaned
|
|
591
|
+
_log_orphan(expected, observed)
|
|
592
|
+
stop()
|
|
593
|
+
with state_lock:
|
|
594
|
+
orphaned = True
|
|
595
|
+
should_shutdown = serve_entered
|
|
596
|
+
if should_shutdown:
|
|
597
|
+
threading.Thread(target=server.shutdown, daemon=True).start()
|
|
598
|
+
|
|
440
599
|
def watch() -> None:
|
|
441
600
|
child.wait()
|
|
442
601
|
server.shutdown()
|
|
443
602
|
|
|
444
|
-
|
|
603
|
+
watchdog_stop = install_parent_watchdog(expected_ppid, on_orphan, interval=WATCHDOG_INTERVAL_S)
|
|
445
604
|
try:
|
|
446
|
-
|
|
605
|
+
with state_lock:
|
|
606
|
+
should_serve = not orphaned
|
|
607
|
+
if should_serve:
|
|
608
|
+
serve_entered = True
|
|
609
|
+
if should_serve:
|
|
610
|
+
threading.Thread(target=watch, daemon=True).start()
|
|
611
|
+
server.serve_forever()
|
|
447
612
|
finally:
|
|
613
|
+
if watchdog_stop is not None:
|
|
614
|
+
watchdog_stop.set()
|
|
448
615
|
server.server_close()
|
|
449
|
-
|
|
450
|
-
child.terminate()
|
|
616
|
+
_terminate_if_running(child)
|
|
451
617
|
code = child.wait()
|
|
452
618
|
return code if code >= 0 else 128 - code
|
|
453
619
|
|