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