@simplexai/localmodels-darwin-x64 0.1.0-dev.60 → 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.
Files changed (74) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +73 -60
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +5 -3
  5. package/modules/localmodels/auth_proxy.py +185 -19
  6. package/modules/localmodels/catalog.json +363 -0
  7. package/modules/localmodels/catalog.py +1 -1
  8. package/modules/localmodels/catalog_add.py +5 -5
  9. package/modules/localmodels/catalog_license.py +2 -0
  10. package/modules/localmodels/catalog_recipes.py +2 -0
  11. package/modules/localmodels/cli_parser.py +6 -2
  12. package/modules/localmodels/context_policy.py +40 -4
  13. package/modules/localmodels/debug_mode.py +13 -0
  14. package/modules/localmodels/debug_stub_server.py +156 -1
  15. package/modules/localmodels/deploy.py +11 -2
  16. package/modules/localmodels/download-mirrors.json +12 -0
  17. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  18. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  19. package/modules/localmodels/gateway_app_bifrost.py +14 -14
  20. package/modules/localmodels/gateway_bifrost.py +4 -1
  21. package/modules/localmodels/gateway_cli.py +14 -80
  22. package/modules/localmodels/gateway_server.py +88 -16
  23. package/modules/localmodels/gpu_specs.py +35 -1
  24. package/modules/localmodels/harness.py +1 -2
  25. package/modules/localmodels/hf_repo.py +12 -4
  26. package/modules/localmodels/install.py +4 -4
  27. package/modules/localmodels/library_serve.py +69 -13
  28. package/modules/localmodels/npm_transport.py +4 -58
  29. package/modules/localmodels/recommend_cli.py +2 -1
  30. package/modules/localmodels/remote_ops.py +120 -713
  31. package/modules/localmodels/remote_ops_common.py +729 -0
  32. package/modules/localmodels/remote_ops_download.py +397 -381
  33. package/modules/localmodels/remote_ops_mirrors.py +26 -65
  34. package/modules/localmodels/remote_ops_prepare.py +43 -35
  35. package/modules/localmodels/remote_ops_ranges.py +98 -62
  36. package/modules/localmodels/remote_ops_remove.py +30 -22
  37. package/modules/localmodels/remote_ops_service.py +102 -95
  38. package/modules/localmodels/remote_ops_verify.py +94 -63
  39. package/modules/localmodels/runtime_cli.py +15 -5
  40. package/modules/localmodels/runtime_io.py +54 -1
  41. package/modules/localmodels/speech-sv.txt +93 -0
  42. package/modules/localmodels/speech_admission.py +437 -0
  43. package/modules/localmodels/speech_catalog.py +170 -0
  44. package/modules/localmodels/speech_cli.py +273 -0
  45. package/modules/localmodels/speech_jobs.py +772 -0
  46. package/modules/localmodels/speech_model.py +404 -0
  47. package/modules/localmodels/speech_serve.py +287 -0
  48. package/modules/localmodels/speech_server.py +837 -0
  49. package/modules/localmodels/speech_state.py +697 -0
  50. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  51. package/modules/localmodels/speech_workers.py +783 -0
  52. package/modules/localmodels/stack.py +0 -33
  53. package/modules/localmodels/stack_auto.py +5 -3
  54. package/modules/localmodels/stack_aux_gpu.py +45 -4
  55. package/modules/localmodels/stack_capacity.py +77 -8
  56. package/modules/localmodels/stack_cli.py +16 -1
  57. package/modules/localmodels/stack_compose.py +1 -1
  58. package/modules/localmodels/stack_down.py +24 -1
  59. package/modules/localmodels/stack_hardware.py +57 -88
  60. package/modules/localmodels/stack_hardware_text.py +4 -59
  61. package/modules/localmodels/stack_memory.py +13 -3
  62. package/modules/localmodels/stack_suite.py +9 -10
  63. package/modules/localmodels/stack_summary.py +4 -4
  64. package/modules/localmodels/stack_view_llm.py +1 -1
  65. package/modules/localmodels/transport.py +3 -2
  66. package/modules/localmodels/tui_views.py +2 -2
  67. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
  68. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +70 -57
  69. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
  70. package/package.json +1 -1
  71. package/tool.json +1 -1
  72. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
  73. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
  74. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,729 @@
1
+ #!/usr/bin/env python3
2
+ """Shared L0 primitives, contracts and HTTP/service helpers for the remote_ops bundle.
3
+
4
+ Self-contained (standard library only, Python 3.8+): shipped inside ``transport.BUNDLES`` ahead
5
+ of the ``remote_ops_*`` action handlers so every handler imports downward from this leaf module
6
+ without forming an import cycle or reaching back into ``remote_ops``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import hashlib
13
+ import ipaddress
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import socket
19
+ import subprocess
20
+ import sys
21
+ import tarfile
22
+ import time
23
+ import urllib.error
24
+ import urllib.parse
25
+ import urllib.request
26
+ import zipfile
27
+ from collections.abc import Iterator
28
+ from typing import Any, TypedDict, cast
29
+
30
+ try:
31
+ from localmodels import process_identity
32
+ except ImportError: # run as a bare file from this directory
33
+ import process_identity # type: ignore[import-not-found,no-redef]
34
+
35
+
36
+ class _Source(TypedDict):
37
+ source: str # public label: huggingface, hf-mirror, modelscope, npm, npmmirror or custom
38
+ url: str
39
+
40
+
41
+ class Source(_Source, total=False):
42
+ member: str # an npm package holding the file: its path inside the package tarball
43
+
44
+
45
+ class Download(TypedDict):
46
+ url: str
47
+ dest: str
48
+ sha256: str
49
+ size_bytes: int
50
+
51
+
52
+ class Reusable(Download, total=False):
53
+ reuse: str # a copy already on the host; hard-linked only after its SHA256 matches
54
+ mirrors: list[Source] # other sources of the same pinned bytes; the fastest is used
55
+ generated: bool # a pinned output materialized by the approved preparation descriptor
56
+
57
+
58
+ class NpmCopy(TypedDict):
59
+ package: str # an npm package whose file ``name`` is this archive, byte for byte
60
+ version: str
61
+
62
+
63
+ class _Archive(TypedDict):
64
+ name: str
65
+ url: str
66
+ sha256: str
67
+ size_bytes: int
68
+
69
+
70
+ class Archive(_Archive, total=False):
71
+ npm_copy: NpmCopy
72
+ # Only these paths of the archive are unpacked (prefixes, after its top folder is dropped):
73
+ # a source archive whose deepest paths would pass Windows' 260-character limit.
74
+ members: list[str]
75
+
76
+
77
+ class ServiceParams(TypedDict): # all start, stop and status need; the base of the rest
78
+ deploy_dir: str
79
+ service: str
80
+ service_kind: str
81
+ port: int
82
+ api_key: str
83
+
84
+
85
+ class _Engine(TypedDict):
86
+ dir: str
87
+ assets: list[Archive]
88
+
89
+
90
+ class EngineParams(_Engine, total=False):
91
+ binary: str # the executable the engine archive must contain (default llama-server)
92
+ region: str # cn or global: the order of the download sources (region.py)
93
+
94
+
95
+ class StrataPreparation(TypedDict):
96
+ kind: str
97
+ engine_dir: str
98
+ model_dir: str
99
+ gguf: str
100
+ pack: str
101
+ experts_bin: bool
102
+ gguf_py: Archive
103
+ mtp_revision: str
104
+ download_bytes: int
105
+ scratch_bytes: int
106
+ hf_endpoint: str
107
+
108
+
109
+ class _DownloadParams(TypedDict):
110
+ files: list[Reusable]
111
+
112
+
113
+ class DownloadParams(_DownloadParams, total=False):
114
+ preparation: StrataPreparation
115
+ region: str # cn or global: the order of the download sources (region.py)
116
+ auth_headers: dict[str, str] # host -> Authorization header value (in-memory only via stdin)
117
+
118
+
119
+ class _Install(ServiceParams):
120
+ argv: list[str]
121
+ env: dict[str, str]
122
+ record: object
123
+
124
+
125
+ class InstallParams(_Install, total=False):
126
+ limits: dict[str, str] # systemd [Service] resource settings, e.g. MemoryMax
127
+ slice: str # the systemd --user slice the unit runs in, with its own limits
128
+ slice_limits: dict[str, str]
129
+ config_files: dict[str, str] # {path: content}, e.g. a Strata serve profile
130
+ autostart: bool # False skips systemd --user enable on boot
131
+
132
+
133
+ class _Verify(ServiceParams):
134
+ model_alias: str
135
+ contract: str
136
+
137
+
138
+ class VerifyParams(_Verify, total=False):
139
+ timeout_s: float
140
+ health: dict[str, object] # {"path": "/health", "auth": true}
141
+ fixture: dict[str, object] # acceptance input: STT audio to download, TTS sentences
142
+ input_tokens: int # served just under it, refused (not truncated) just over it
143
+ vision: bool # the LLM loads a picture reader: a synthetic picture must be read too
144
+ window: int # stack agent LLM: /props n_ctx must be at least the planned window
145
+ weights_on_gpu: bool # none stay in host memory: Windows gets back what they were read through
146
+ smoke: bool # minimal smoke-test completion ("Reply with OK.", max_tokens=16)
147
+
148
+
149
+ class RemoveParams(ServiceParams, total=False):
150
+ dry_run: bool # only list what a purge deletes
151
+ purge_files: list[str] # model files a purge may delete besides the deployment dir
152
+ purge: list[str] # the listed files the operator approved deleting
153
+ config_files: list[str] # files install wrote from the plan's config_files
154
+ preparation_dir: str # the recorded model root whose failed preparation a purge may list
155
+
156
+
157
+ CHUNK = 8 << 20
158
+ PROGRESS_EVERY_S = 2.0
159
+ TOUCH_PROMPT = "What is the capital of France? Reply with exactly one word."
160
+ TOUCH_EXPECT = "paris"
161
+ CRASH_RESTARTS = 3
162
+ STOP_GRACE_S = 15.0 # a nohup service's time to exit on each signal of stop
163
+ READY = ("ok",) # what llama.cpp, whisper.cpp and Strata report once the model is loaded
164
+ JSON = "application/json"
165
+ # A System One decision model must call an outage an outage (decision-quant README example).
166
+ DECISION_STATE = "Checkout is failing for every customer."
167
+ DECISION_QUESTION = {"type": "noul", "instructions": "Is a service down?"}
168
+ EMBED_QUERY = "How do I reset my account password?"
169
+ EMBED_NEAR = "Steps to change a forgotten login password."
170
+ EMBED_FAR = "The recipe needs two cups of flour and an egg."
171
+ RERANK_QUERY = "What is the capital of France?"
172
+ RERANK_DOCS = [
173
+ "Bananas are rich in potassium.",
174
+ "Paris is the capital and largest city of France.",
175
+ "The Pacific is the largest ocean on Earth.",
176
+ ]
177
+ RERANK_RELEVANT = 1
178
+ PRIVATE_SUFFIXES = (".local", ".lan", ".internal", ".intranet", ".corp", ".home.arpa")
179
+
180
+ _REQUEST_ID: str | None = None
181
+ _step: dict[str, int] = {}
182
+ _SECRET_RE = re.compile(
183
+ r"(?:Bearer\s+\S+|hf_[A-Za-z0-9]{6,}|ms[-_][A-Za-z0-9_-]{6,})",
184
+ re.IGNORECASE,
185
+ )
186
+
187
+
188
+ def set_request_id(trace: object) -> None:
189
+ """Record the controller's request id (injected into remote_ops.py by transport.py)."""
190
+ global _REQUEST_ID
191
+ _REQUEST_ID = str(trace) if trace else None
192
+
193
+
194
+ def emit(event: str, **fields: object) -> None:
195
+ fields["event"] = event
196
+ sys.stdout.write(json.dumps(fields, ensure_ascii=False) + "\n")
197
+ sys.stdout.flush()
198
+
199
+
200
+ def step_fields(done: int) -> dict[str, int]:
201
+ """The component-wide counters of a download event: file i of n, bytes on disk of all."""
202
+ if not _step:
203
+ return {}
204
+ return {
205
+ "file_index": _step["index"],
206
+ "file_count": _step["count"],
207
+ "component_done": _step["before"] + done,
208
+ "component_total": _step["total"],
209
+ }
210
+
211
+
212
+ def state_path(part: str) -> str:
213
+ return part + ".ranges"
214
+
215
+
216
+ def load_ranges(part: str, size: int) -> list[list[int]] | None:
217
+ try:
218
+ state = json.loads(read_text(state_path(part)))
219
+ segments = [[int(a), int(b), int(c)] for a, b, c in state["segments"]]
220
+ except (OSError, ValueError, KeyError, TypeError):
221
+ return None
222
+ if state.get("size") != size or not os.path.exists(part) or os.path.getsize(part) != size:
223
+ return None
224
+ if any(not 0 <= start <= done <= end <= size for start, end, done in segments):
225
+ return None
226
+ return segments
227
+
228
+
229
+ def save_ranges(part: str, size: int, segments: list[list[int]]) -> None:
230
+ path = state_path(part)
231
+ write_text(path + ".tmp", json.dumps({"size": size, "segments": segments}))
232
+ os.replace(path + ".tmp", path)
233
+
234
+
235
+ def kept_bytes(part: str, size: int) -> int:
236
+ """Bytes of ``part`` already downloaded: its ranges record when it has one, else its size."""
237
+ segments = load_ranges(part, size)
238
+ if segments is not None:
239
+ return size - sum(end - done for _, end, done in segments)
240
+ return os.path.getsize(part) if os.path.exists(part) else 0
241
+
242
+
243
+ def discard(part: str) -> None:
244
+ for path in (part, state_path(part), state_path(part) + ".tmp", part + ".tmp", part + ".npm"):
245
+ try:
246
+ os.remove(path)
247
+ except FileNotFoundError:
248
+ pass
249
+
250
+
251
+ def clear_link(target: str) -> None:
252
+ """Remove an existing file or symlink before tar.extract recreates a link member."""
253
+ if os.path.islink(target) or os.path.isfile(target):
254
+ os.unlink(target)
255
+
256
+
257
+ def each_file(files: list[tuple[str, int]]) -> Iterator[int]:
258
+ """Yield each file's position in order, tracking it for step_fields until the step ends."""
259
+ sizes = [size for _, size in files]
260
+ kept = [
261
+ size
262
+ if os.path.isfile(path) and os.path.getsize(path) == size
263
+ else min(size, kept_bytes(path + ".part", size))
264
+ for path, size in files
265
+ ]
266
+ try:
267
+ for i in range(len(sizes)):
268
+ _step.update(
269
+ index=i + 1,
270
+ count=len(sizes),
271
+ before=sum(sizes[:i]) + sum(kept[i + 1 :]),
272
+ total=sum(sizes),
273
+ )
274
+ yield i
275
+ finally:
276
+ _step.clear()
277
+
278
+
279
+ def home(value: str) -> str:
280
+ return os.path.expanduser(value) if value.startswith("~/") else value
281
+
282
+
283
+ def non_public(url: str) -> bool:
284
+ """A source that is not on the public internet: plain http, an IP literal in a private,
285
+ loopback or link-local range, or a single-label or private-suffix host name. Such a source
286
+ (a LAN registry, a user's own mirror) is never republished and is tried first, being near."""
287
+ parts = urllib.parse.urlsplit(url)
288
+ host = (parts.hostname or "").lower()
289
+ if parts.scheme != "https" or not host:
290
+ return True
291
+ try:
292
+ address = ipaddress.ip_address(host)
293
+ except ValueError:
294
+ return "." not in host or host.endswith(PRIVATE_SUFFIXES)
295
+ return not address.is_global
296
+
297
+
298
+ def expand(path: str) -> str:
299
+ return os.path.abspath(os.path.expanduser(path))
300
+
301
+
302
+ def read_text(path: str) -> str:
303
+ with open(path, encoding="utf-8") as f:
304
+ return f.read()
305
+
306
+
307
+ def write_text(path: str, text: str) -> None:
308
+ with open(path, "w", encoding="utf-8") as f:
309
+ f.write(text)
310
+ narrow(f.fileno(), 0o022)
311
+
312
+
313
+ def narrow(fd: int, bits: int) -> None:
314
+ """Clear ``bits`` from an open file's mode. The umask applies only when a file is created, so
315
+ a unit or slice an older release wrote under umask 0002 would otherwise stay group-writable
316
+ when it is rewritten; a mode is only ever narrowed."""
317
+ if not hasattr(os, "fchmod"): # Windows
318
+ return
319
+ mode = os.fstat(fd).st_mode & 0o7777
320
+ if mode & bits:
321
+ os.fchmod(fd, mode & ~bits)
322
+
323
+
324
+ def sha256_file(path: str, label: str) -> str:
325
+ digest = hashlib.sha256()
326
+ total = os.path.getsize(path)
327
+ done, last = 0, 0.0
328
+ with open(path, "rb") as f:
329
+ for chunk in iter(lambda: f.read(CHUNK), b""):
330
+ digest.update(chunk)
331
+ done += len(chunk)
332
+ if time.monotonic() - last > PROGRESS_EVERY_S:
333
+ last = time.monotonic()
334
+ emit("progress", phase="verify", file=label, done=done, total=total)
335
+ return digest.hexdigest()
336
+
337
+
338
+ def cache_blob(sha256: str) -> str | None:
339
+ root = os.environ.get("LOCALMODELS_CACHE_DIR", "").strip()
340
+ if not root or len(sha256) != 64:
341
+ return None
342
+ return os.path.join(expand(root), sha256)
343
+
344
+
345
+ def restore_cached(dest: str, sha256: str, size: int, label: str) -> bool:
346
+ cached = cache_blob(sha256)
347
+ if not cached or not os.path.isfile(cached) or os.path.getsize(cached) != size:
348
+ return False
349
+ receipt = cached + ".sha256"
350
+ if not (os.path.isfile(receipt) and read_text(receipt).strip() == sha256):
351
+ if sha256_file(cached, label) != sha256:
352
+ return False
353
+ write_text(receipt, sha256)
354
+ tmp = f"{dest}.cache.{os.getpid()}"
355
+ with contextlib.suppress(OSError):
356
+ os.unlink(tmp)
357
+ try:
358
+ if os.stat(cached).st_dev == os.stat(os.path.dirname(dest)).st_dev:
359
+ os.link(cached, tmp)
360
+ else:
361
+ shutil.copyfile(cached, tmp)
362
+ os.replace(tmp, dest)
363
+ except OSError:
364
+ with contextlib.suppress(OSError):
365
+ os.unlink(tmp)
366
+ return False
367
+ write_text(dest + ".sha256", sha256)
368
+ emit(
369
+ "progress",
370
+ phase="download",
371
+ file=label,
372
+ done=size,
373
+ total=size,
374
+ bytes_per_s=size,
375
+ source="cache",
376
+ connections=0,
377
+ **step_fields(size),
378
+ )
379
+ emit("log", message="reused verified local cache for " + label)
380
+ return True
381
+
382
+
383
+ def store_cached(dest: str, sha256: str, size: int) -> None:
384
+ cached = cache_blob(sha256)
385
+ if not cached or (os.path.isfile(cached) and os.path.getsize(cached) == size):
386
+ return
387
+ with contextlib.suppress(OSError):
388
+ os.makedirs(os.path.dirname(cached), mode=0o700, exist_ok=True)
389
+ tmp = f"{cached}.tmp.{os.getpid()}"
390
+ if os.stat(dest).st_dev == os.stat(os.path.dirname(cached)).st_dev:
391
+ os.link(dest, tmp)
392
+ else:
393
+ shutil.copyfile(dest, tmp)
394
+ os.replace(tmp, cached)
395
+ write_text(cached + ".sha256", sha256)
396
+
397
+
398
+ def redact_text(text: str) -> str:
399
+ """Strip Bearer credentials and hub token patterns from logs and errors."""
400
+ return _SECRET_RE.sub("[REDACTED]", text)
401
+
402
+
403
+ def gguf_magic_ok(path: str, label: str) -> bool:
404
+ """Verify the 4-byte GGUF magic header for .gguf files."""
405
+ if not label.lower().endswith(".gguf"):
406
+ return True
407
+ try:
408
+ with open(path, "rb") as handle:
409
+ return handle.read(4) == b"GGUF"
410
+ except OSError:
411
+ return False
412
+
413
+
414
+ def existing_verified(dest: str, marker: str, sha256: str, size: int, label: str) -> bool:
415
+ if not sha256:
416
+ if (
417
+ size > 0
418
+ and os.path.exists(dest)
419
+ and os.path.getsize(dest) == size
420
+ and gguf_magic_ok(dest, label)
421
+ ):
422
+ emit("log", message="verified, skipping " + label)
423
+ return True
424
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
425
+ return False
426
+ if os.path.exists(dest) and os.path.exists(marker) and read_text(marker).strip() == sha256:
427
+ emit("log", message="verified, skipping " + label)
428
+ return True
429
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
430
+ if (
431
+ os.path.exists(dest)
432
+ and os.path.getsize(dest) == size
433
+ and sha256_file(dest, label) == sha256
434
+ ):
435
+ write_text(marker, sha256)
436
+ store_cached(dest, sha256, size)
437
+ return True
438
+ return restore_cached(dest, sha256, size, label)
439
+
440
+
441
+ def check_part(part: str, sha256: str, size: int, label: str, source_name: str) -> Exception | None:
442
+ got_size = os.path.getsize(part)
443
+ if size <= 0 or got_size != size:
444
+ return RuntimeError(f"{label} size mismatch: {got_size} != {size}")
445
+ if not sha256:
446
+ if not gguf_magic_ok(part, label):
447
+ emit("log", message=f"{label} from {source_name} failed the GGUF magic check")
448
+ return RuntimeError(f"{label} is not a valid GGUF file (bad magic)")
449
+ return None
450
+ actual = sha256_file(part, label)
451
+ if actual != sha256:
452
+ emit("log", message=f"{label} from {source_name} failed the SHA256 check")
453
+ return RuntimeError(f"{label} SHA256 mismatch: {actual} != {sha256}")
454
+ return None
455
+
456
+
457
+ def _relative(name: str) -> str:
458
+ while name.startswith("./"):
459
+ name = name[2:]
460
+ return name
461
+
462
+
463
+ def _unzip(archive: str, directory: str, members: tuple[str, ...] = ()) -> None:
464
+ """A Windows release zip: regular files only, each kept inside ``directory``."""
465
+ with zipfile.ZipFile(archive) as bundle:
466
+ names = [_relative(i.filename.replace("\\", "/")) for i in bundle.infolist()]
467
+ tops = {n.split("/", 1)[0] for n in names if n}
468
+ strip = len(tops) == 1 and any("/" in n for n in names)
469
+ for info, name in zip(bundle.infolist(), names):
470
+ if strip:
471
+ name = name.split("/", 1)[1] if "/" in name else ""
472
+ if members and not name.startswith(members):
473
+ continue
474
+ if not name or info.is_dir() or name.startswith("/") or ".." in name.split("/"):
475
+ continue
476
+ if ":" in name or (info.external_attr >> 16) & 0o170000 == 0o120000:
477
+ continue # a drive letter or a symlink entry
478
+ target = os.path.join(directory, *name.split("/"))
479
+ os.makedirs(os.path.dirname(target), exist_ok=True)
480
+ with bundle.open(info) as source, open(target, "wb") as dest:
481
+ shutil.copyfileobj(source, dest)
482
+
483
+
484
+ def unpack(archive: str, directory: str, keep: tuple[str, ...] = ()) -> None:
485
+ """Extract into ``directory``, dropping the archive's single top folder when it has one;
486
+ ``keep``: only the paths under these prefixes (Archive.members). A wheel is a zip
487
+ (PolyStrata's Windows build takes cuBLAS from NVIDIA's)."""
488
+ if archive.endswith((".zip", ".whl")):
489
+ _unzip(archive, directory, keep)
490
+ return
491
+ with tarfile.open(archive) as tar:
492
+ members = tar.getmembers()
493
+ tops = {m.name.lstrip("./").split("/", 1)[0] for m in members if m.name.lstrip("./")}
494
+ strip = len(tops) == 1 and any("/" in m.name.lstrip("./") for m in members)
495
+ for member in members:
496
+ name = member.name.lstrip("./")
497
+ if strip:
498
+ name = name.split("/", 1)[1] if "/" in name else ""
499
+ if keep and not name.startswith(keep):
500
+ continue
501
+ if not name or name.startswith("/") or ".." in name.split("/"):
502
+ continue
503
+ if member.issym() or member.islnk():
504
+ target = member.linkname
505
+ if target.startswith("/") or ".." in target.split("/")[:-1]:
506
+ continue
507
+ if member.islnk() and strip:
508
+ member.linkname = target.lstrip("./").split("/", 1)[-1]
509
+ member.name = name
510
+ if member.isdir():
511
+ member.mode |= 0o700
512
+ elif member.isfile():
513
+ member.mode |= 0o200
514
+ if member.issym() or member.islnk():
515
+ clear_link(os.path.join(directory, name))
516
+ tar.extract(member, directory)
517
+
518
+
519
+ _AUTH_HEADERS: dict[str, str] = {}
520
+ _BLOCKED_AUTH_HOSTS = frozenset({"hf-mirror.com", "www.hf-mirror.com"})
521
+ _LOCAL_SUFFIXES = (".localhost", ".local", ".internal", ".home.arpa")
522
+ _STDLIB_URLOPEN = urllib.request.urlopen
523
+ ALLOW_INSECURE_LOOPBACK_FOR_TESTS = False
524
+
525
+
526
+ def set_auth_headers(headers: dict[str, str] | None) -> None:
527
+ """Set in-memory host-scoped Authorization headers for the active download step."""
528
+ _AUTH_HEADERS.clear()
529
+ if headers:
530
+ for host, value in headers.items():
531
+ clean_host = str(host).strip().lower()
532
+ clean_val = str(value).strip()
533
+ if clean_host and clean_val and clean_host not in _BLOCKED_AUTH_HOSTS:
534
+ _AUTH_HEADERS[clean_host] = clean_val
535
+
536
+
537
+ def _url_origin(raw_url: str) -> tuple[str, str, int]:
538
+ split = urllib.parse.urlsplit(raw_url)
539
+ scheme = split.scheme.lower()
540
+ host = (split.hostname or "").lower().rstrip(".")
541
+ port = split.port
542
+ if port is None:
543
+ port = 443 if scheme == "https" else (80 if scheme == "http" else 0)
544
+ return (scheme, host, port)
545
+
546
+
547
+ def _ip_blocked(raw_ip: str) -> bool:
548
+ addr = ipaddress.ip_address(raw_ip.split("%", 1)[0])
549
+ if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None:
550
+ addr = addr.ipv4_mapped
551
+ if not addr.is_global:
552
+ return True
553
+ return any(
554
+ (
555
+ addr.is_loopback,
556
+ addr.is_private,
557
+ addr.is_link_local,
558
+ addr.is_multicast,
559
+ addr.is_unspecified,
560
+ addr.is_reserved,
561
+ )
562
+ )
563
+
564
+
565
+ def validate_redirect_url(target_url: str) -> None:
566
+ """Require HTTPS and block loopback/private/link-local SSRF targets on redirects."""
567
+ scheme, host, port = _url_origin(target_url)
568
+ if scheme != "https" and not (ALLOW_INSECURE_LOOPBACK_FOR_TESTS and scheme == "http"):
569
+ raise urllib.error.URLError(f"redirect refused: non-HTTPS scheme {scheme!r}")
570
+ if not host:
571
+ raise urllib.error.URLError("redirect refused: missing target host")
572
+ if ALLOW_INSECURE_LOOPBACK_FOR_TESTS:
573
+ return
574
+ if host == "localhost" or any(host.endswith(suffix) for suffix in _LOCAL_SUFFIXES):
575
+ raise urllib.error.URLError(f"redirect refused: local hostname {host!r}")
576
+ try:
577
+ if _ip_blocked(host):
578
+ raise urllib.error.URLError(f"redirect refused: non-public IP {host!r}")
579
+ return
580
+ except ValueError:
581
+ pass
582
+ try:
583
+ records = socket.getaddrinfo(host, port or 443, type=socket.SOCK_STREAM)
584
+ except OSError as exc:
585
+ raise urllib.error.URLError(
586
+ f"redirect refused: DNS lookup failed for {host!r}: {exc}"
587
+ ) from None
588
+ if not records:
589
+ raise urllib.error.URLError(f"redirect refused: empty DNS answer for {host!r}")
590
+ for entry in records:
591
+ candidate_ip = str(entry[4][0])
592
+ try:
593
+ blocked = _ip_blocked(candidate_ip)
594
+ except ValueError:
595
+ raise urllib.error.URLError(f"redirect refused: invalid IP for {host!r}") from None
596
+ if blocked:
597
+ raise urllib.error.URLError(f"redirect refused: non-public IP for {host!r}")
598
+
599
+
600
+ class SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
601
+ """Enforce HTTPS + anti-SSRF on redirects and strip Authorization on any origin change."""
602
+
603
+ def redirect_request(
604
+ self,
605
+ req: urllib.request.Request,
606
+ fp: Any,
607
+ code: int,
608
+ msg: str,
609
+ headers: Any,
610
+ newurl: str,
611
+ ) -> urllib.request.Request | None:
612
+ resolved = urllib.parse.urljoin(req.full_url, newurl)
613
+ validate_redirect_url(resolved)
614
+ redirected = super().redirect_request(req, fp, code, msg, headers, newurl)
615
+ if redirected is None:
616
+ return None
617
+ if _url_origin(req.full_url) != _url_origin(resolved):
618
+ for bag in (redirected.headers, redirected.unredirected_hdrs):
619
+ for key in list(bag.keys()):
620
+ if key.lower() == "authorization":
621
+ del bag[key]
622
+ return redirected
623
+
624
+
625
+ def build_request(
626
+ url: str, start: int | None = None, end: int | None = None
627
+ ) -> urllib.request.Request:
628
+ request_obj = urllib.request.Request(url, headers={"User-Agent": "localmodels-deploy"})
629
+ if start is not None and end is not None:
630
+ request_obj.add_header("Range", f"bytes={start}-{end - 1}")
631
+ scheme, host, _ = _url_origin(url)
632
+ https_ok = scheme == "https" or (ALLOW_INSECURE_LOOPBACK_FOR_TESTS and scheme == "http")
633
+ if https_ok and host and host not in _BLOCKED_AUTH_HOSTS and host in _AUTH_HEADERS:
634
+ request_obj.add_header("Authorization", _AUTH_HEADERS[host])
635
+ return request_obj
636
+
637
+
638
+ def open_url(request_obj: urllib.request.Request, timeout: float) -> Any:
639
+ https_live = (
640
+ request_obj.full_url.lower().startswith("https://")
641
+ and urllib.request.urlopen is _STDLIB_URLOPEN
642
+ )
643
+ if request_obj.has_header("Authorization") or https_live:
644
+ return urllib.request.build_opener(SafeRedirectHandler()).open(request_obj, timeout=timeout)
645
+ return urllib.request.urlopen(request_obj, timeout=timeout)
646
+
647
+
648
+ def paths(p: ServiceParams) -> dict[str, str]:
649
+ root = expand(p["deploy_dir"])
650
+ return {
651
+ "root": root,
652
+ "script": os.path.join(root, "run.cmd" if sys.platform == "win32" else "run.sh"),
653
+ "log": os.path.join(root, "server.log"),
654
+ "key": os.path.join(root, "api-key"),
655
+ "pid": os.path.join(root, "server.pid"),
656
+ "spec": os.path.join(root, "deployment.json"),
657
+ "unit": expand("~/.config/systemd/user/{}.service".format(p["service"])),
658
+ }
659
+
660
+
661
+ def systemctl(*args: str) -> tuple[int, str]:
662
+ out = subprocess.run(
663
+ ["systemctl", "--user", *args], capture_output=True, text=True, check=False
664
+ )
665
+ return out.returncode, (out.stdout + out.stderr).strip()
666
+
667
+
668
+ def systemctl_ok(*args: str) -> None:
669
+ rc, out = systemctl(*args)
670
+ if rc != 0:
671
+ raise RuntimeError(f"systemctl {args[0]} failed: " + out)
672
+
673
+
674
+ # macOS and Windows have no /proc: their nohup services keep process identity receipts.
675
+ def receipts() -> bool:
676
+ return sys.platform in ("darwin", "win32")
677
+
678
+
679
+ def pid_alive(pid_path: str) -> int | None:
680
+ if receipts():
681
+ return process_identity.status(pid_path)[1]
682
+ try:
683
+ pid = int(read_text(pid_path).strip())
684
+ os.kill(pid, 0)
685
+ return pid
686
+ except (OSError, ValueError):
687
+ return None
688
+
689
+
690
+ def port_owner(port: int) -> bool:
691
+ """True when something already listens on 127.0.0.1:port."""
692
+ if sys.platform == "win32": # a refused loopback connect retries for seconds there
693
+ owners = process_identity.listener_pids(port)
694
+ return owners is None or bool(owners)
695
+ with socket.socket() as s:
696
+ s.settimeout(1)
697
+ return s.connect_ex(("127.0.0.1", port)) == 0
698
+
699
+
700
+ def request(url: str, api_key: str, data: bytes | None, kind: str, timeout: float) -> bytes:
701
+ """One request to a loopback service with the deployment key, past any proxy settings."""
702
+ headers = {"Authorization": "Bearer " + api_key, "Content-Type": kind}
703
+ if _REQUEST_ID:
704
+ headers["X-Request-ID"] = _REQUEST_ID
705
+ req = urllib.request.Request(url, data=data, headers=headers)
706
+ with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(
707
+ req, timeout=timeout
708
+ ) as r:
709
+ return cast(bytes, r.read())
710
+
711
+
712
+ def http_json(
713
+ url: str, api_key: str, body: object = None, timeout: float = 10
714
+ ) -> dict[str, object]:
715
+ data = json.dumps(body).encode() if body is not None else None
716
+ value = json.loads(request(url, api_key, data, JSON, timeout) or b"{}")
717
+ if not isinstance(value, dict):
718
+ raise ValueError("expected HTTP JSON object")
719
+ return cast("dict[str, object]", value)
720
+
721
+
722
+ def log_tail(service_paths: dict[str, str], lines: int = 30) -> str:
723
+ try:
724
+ with open(service_paths["log"], "rb") as f:
725
+ f.seek(0, 2)
726
+ f.seek(max(0, f.tell() - 16384))
727
+ return "\n".join(f.read().decode("utf-8", "replace").splitlines()[-lines:])
728
+ except OSError:
729
+ return ""