@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.
Files changed (79) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +78 -64
  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/custom_hub_http.py +27 -104
  14. package/modules/localmodels/debug_mode.py +13 -0
  15. package/modules/localmodels/debug_stub_server.py +156 -1
  16. package/modules/localmodels/deploy.py +11 -2
  17. package/modules/localmodels/download-mirrors.json +12 -0
  18. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  19. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  20. package/modules/localmodels/gateway_app_bifrost.py +14 -14
  21. package/modules/localmodels/gateway_bifrost.py +4 -1
  22. package/modules/localmodels/gateway_cli.py +14 -80
  23. package/modules/localmodels/gateway_server.py +88 -16
  24. package/modules/localmodels/gpu_specs.py +35 -1
  25. package/modules/localmodels/harness.py +1 -2
  26. package/modules/localmodels/hf_repo.py +12 -4
  27. package/modules/localmodels/install.py +4 -4
  28. package/modules/localmodels/library_jobs.py +4 -0
  29. package/modules/localmodels/library_serve.py +69 -13
  30. package/modules/localmodels/memcalc_load.py +9 -4
  31. package/modules/localmodels/npm_transport.py +4 -58
  32. package/modules/localmodels/recommend_cli.py +2 -1
  33. package/modules/localmodels/remote_ops.py +120 -713
  34. package/modules/localmodels/remote_ops_common.py +670 -0
  35. package/modules/localmodels/remote_ops_download.py +399 -381
  36. package/modules/localmodels/remote_ops_mirrors.py +27 -66
  37. package/modules/localmodels/remote_ops_prepare.py +43 -35
  38. package/modules/localmodels/remote_ops_ranges.py +102 -63
  39. package/modules/localmodels/remote_ops_redirect.py +393 -0
  40. package/modules/localmodels/remote_ops_remove.py +30 -22
  41. package/modules/localmodels/remote_ops_service.py +102 -95
  42. package/modules/localmodels/remote_ops_verify.py +94 -63
  43. package/modules/localmodels/runtime_cli.py +15 -5
  44. package/modules/localmodels/runtime_io.py +54 -1
  45. package/modules/localmodels/source_cli.py +136 -23
  46. package/modules/localmodels/speech-sv.txt +93 -0
  47. package/modules/localmodels/speech_admission.py +437 -0
  48. package/modules/localmodels/speech_catalog.py +170 -0
  49. package/modules/localmodels/speech_cli.py +273 -0
  50. package/modules/localmodels/speech_jobs.py +776 -0
  51. package/modules/localmodels/speech_model.py +404 -0
  52. package/modules/localmodels/speech_serve.py +287 -0
  53. package/modules/localmodels/speech_server.py +837 -0
  54. package/modules/localmodels/speech_state.py +697 -0
  55. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  56. package/modules/localmodels/speech_workers.py +783 -0
  57. package/modules/localmodels/stack.py +0 -33
  58. package/modules/localmodels/stack_auto.py +5 -3
  59. package/modules/localmodels/stack_aux_gpu.py +45 -4
  60. package/modules/localmodels/stack_capacity.py +77 -8
  61. package/modules/localmodels/stack_cli.py +16 -1
  62. package/modules/localmodels/stack_compose.py +1 -1
  63. package/modules/localmodels/stack_down.py +24 -1
  64. package/modules/localmodels/stack_hardware.py +57 -88
  65. package/modules/localmodels/stack_hardware_text.py +4 -59
  66. package/modules/localmodels/stack_memory.py +13 -3
  67. package/modules/localmodels/stack_suite.py +9 -10
  68. package/modules/localmodels/stack_summary.py +4 -4
  69. package/modules/localmodels/stack_view_llm.py +1 -1
  70. package/modules/localmodels/transport.py +4 -2
  71. package/modules/localmodels/tui_views.py +2 -2
  72. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/METADATA +1 -1
  73. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/RECORD +75 -61
  74. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/NOTICE +9 -0
  75. package/package.json +1 -1
  76. package/tool.json +1 -1
  77. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/WHEEL +0 -0
  78. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/entry_points.txt +0 -0
  79. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -6,181 +6,145 @@ ACTION`` exactly like probe.py, with the parameters prepended to the script sour
6
6
  ``_PARAMS_B64`` so the API key never appears in a process list. Every action is idempotent and
7
7
  reports JSON lines on stdout: {"event": "log"|"progress"|"result"|"error", ...}.
8
8
 
9
- The action handlers live in the sibling modules remote_ops_download, remote_ops_service,
10
- remote_ops_verify and remote_ops_remove; transport ships their helpers as one payload whose
11
- in-memory loader resolves the same ``from localmodels import ...`` this package uses. This
12
- entry module keeps the shared primitives (emit, fetch, unpack, paths, systemctl, http) and the
13
- TypedDict parameter contract; siblings reach them as ``remote_ops.<name>`` — late binding that
14
- keeps the bundle one patchable surface — and the moved handlers keep their ``remote_ops.*``
15
- names via the aliases above ACTIONS.
16
-
17
- The actions, their handlers and parameters are the Actions table below.
9
+ Shared primitives and parameter contracts live in the L0 leaf module ``remote_ops_common``; the
10
+ action handlers live in ``remote_ops_download``, ``remote_ops_service``, ``remote_ops_verify``
11
+ and ``remote_ops_remove`` and import strictly downward from ``remote_ops_common`` and lower
12
+ siblings. This entry module acts solely as the top-level dispatcher and public facade.
18
13
  """
19
14
 
20
15
  from __future__ import annotations
21
16
 
22
17
  import base64
23
- import contextlib
24
- import hashlib
25
- import ipaddress
26
18
  import json
27
19
  import os
28
- import re
29
- import shutil
30
- import socket
31
- import subprocess
32
20
  import sys
33
- import tarfile
34
- import time
35
- import urllib.error
36
- import urllib.parse
37
- import urllib.request
38
- import zipfile
39
- from collections.abc import Callable, Iterator
21
+ from collections.abc import Callable
40
22
  from typing import TypedDict, cast
41
23
 
42
- if __name__ == "__main__":
43
- # Run as a file: a sibling's bare ``import remote_ops`` must find this module, not a
44
- # second copy whose import would recurse through the whole bundle.
45
- sys.modules.setdefault("remote_ops", sys.modules["__main__"])
46
-
47
24
  try:
48
25
  from localmodels import (
49
26
  process_identity,
27
+ remote_ops_common,
50
28
  remote_ops_download,
51
29
  remote_ops_remove,
52
30
  remote_ops_service,
53
31
  remote_ops_verify,
54
32
  )
33
+ from localmodels.remote_ops_common import (
34
+ CRASH_RESTARTS as CRASH_RESTARTS,
35
+ )
36
+ from localmodels.remote_ops_common import (
37
+ DECISION_QUESTION as DECISION_QUESTION,
38
+ )
39
+ from localmodels.remote_ops_common import (
40
+ DECISION_STATE as DECISION_STATE,
41
+ )
42
+ from localmodels.remote_ops_common import (
43
+ EMBED_FAR as EMBED_FAR,
44
+ )
45
+ from localmodels.remote_ops_common import (
46
+ EMBED_NEAR as EMBED_NEAR,
47
+ )
48
+ from localmodels.remote_ops_common import (
49
+ EMBED_QUERY as EMBED_QUERY,
50
+ )
51
+ from localmodels.remote_ops_common import (
52
+ JSON as JSON,
53
+ )
54
+ from localmodels.remote_ops_common import (
55
+ PRIVATE_SUFFIXES as PRIVATE_SUFFIXES,
56
+ )
57
+ from localmodels.remote_ops_common import (
58
+ READY as READY,
59
+ )
60
+ from localmodels.remote_ops_common import (
61
+ RERANK_DOCS as RERANK_DOCS,
62
+ )
63
+ from localmodels.remote_ops_common import (
64
+ RERANK_QUERY as RERANK_QUERY,
65
+ )
66
+ from localmodels.remote_ops_common import (
67
+ RERANK_RELEVANT as RERANK_RELEVANT,
68
+ )
69
+ from localmodels.remote_ops_common import (
70
+ STOP_GRACE_S as STOP_GRACE_S,
71
+ )
72
+ from localmodels.remote_ops_common import (
73
+ TOUCH_EXPECT as TOUCH_EXPECT,
74
+ )
75
+ from localmodels.remote_ops_common import (
76
+ TOUCH_PROMPT as TOUCH_PROMPT,
77
+ )
78
+ from localmodels.remote_ops_common import (
79
+ Archive as Archive,
80
+ )
81
+ from localmodels.remote_ops_common import (
82
+ Download as Download,
83
+ )
84
+ from localmodels.remote_ops_common import (
85
+ DownloadParams as DownloadParams,
86
+ )
87
+ from localmodels.remote_ops_common import (
88
+ EngineParams as EngineParams,
89
+ )
90
+ from localmodels.remote_ops_common import (
91
+ InstallParams as InstallParams,
92
+ )
93
+ from localmodels.remote_ops_common import (
94
+ NpmCopy as NpmCopy,
95
+ )
96
+ from localmodels.remote_ops_common import (
97
+ RemoveParams as RemoveParams,
98
+ )
99
+ from localmodels.remote_ops_common import (
100
+ Reusable as Reusable,
101
+ )
102
+ from localmodels.remote_ops_common import (
103
+ ServiceParams as ServiceParams,
104
+ )
105
+ from localmodels.remote_ops_common import (
106
+ Source as Source,
107
+ )
108
+ from localmodels.remote_ops_common import (
109
+ StrataPreparation as StrataPreparation,
110
+ )
111
+ from localmodels.remote_ops_common import (
112
+ VerifyParams as VerifyParams,
113
+ )
114
+ from localmodels.remote_ops_common import (
115
+ each_file as each_file,
116
+ )
117
+ from localmodels.remote_ops_common import (
118
+ emit as emit,
119
+ )
120
+ from localmodels.remote_ops_common import (
121
+ gguf_magic_ok as gguf_magic_ok,
122
+ )
123
+ from localmodels.remote_ops_common import (
124
+ non_public as non_public,
125
+ )
126
+ from localmodels.remote_ops_common import (
127
+ receipts as receipts,
128
+ )
129
+ from localmodels.remote_ops_common import (
130
+ redact_text as redact_text,
131
+ )
132
+ from localmodels.remote_ops_common import (
133
+ step_fields as step_fields,
134
+ )
135
+ from localmodels.remote_ops_common import (
136
+ unpack as unpack,
137
+ )
138
+ from localmodels.remote_ops_download import fetch as fetch
55
139
  except ImportError: # run as a bare file; the siblings sit in this directory
56
140
  import process_identity # type: ignore[import-not-found,no-redef]
141
+ import remote_ops_common # type: ignore[import-not-found,no-redef]
57
142
  import remote_ops_download # type: ignore[import-not-found,no-redef]
58
143
  import remote_ops_remove # type: ignore[import-not-found,no-redef]
59
144
  import remote_ops_service # type: ignore[import-not-found,no-redef]
60
145
  import remote_ops_verify # type: ignore[import-not-found,no-redef]
61
146
 
62
147
 
63
- class _Source(TypedDict):
64
- source: str # public label: huggingface, hf-mirror, modelscope, npm, npmmirror or custom
65
- url: str
66
-
67
-
68
- class Source(_Source, total=False):
69
- member: str # an npm package holding the file: its path inside the package tarball
70
-
71
-
72
- class Download(TypedDict):
73
- url: str
74
- dest: str
75
- sha256: str
76
- size_bytes: int
77
-
78
-
79
- class Reusable(Download, total=False):
80
- reuse: str # a copy already on the host; hard-linked only after its SHA256 matches
81
- mirrors: list[Source] # other sources of the same pinned bytes; the fastest is used
82
- generated: bool # a pinned output materialized by the approved preparation descriptor
83
-
84
-
85
- class NpmCopy(TypedDict):
86
- package: str # an npm package whose file ``name`` is this archive, byte for byte
87
- version: str
88
-
89
-
90
- class _Archive(TypedDict):
91
- name: str
92
- url: str
93
- sha256: str
94
- size_bytes: int
95
-
96
-
97
- class Archive(_Archive, total=False):
98
- npm_copy: NpmCopy
99
- # Only these paths of the archive are unpacked (prefixes, after its top folder is dropped):
100
- # a source archive whose deepest paths would pass Windows' 260-character limit.
101
- members: list[str]
102
-
103
-
104
- class ServiceParams(TypedDict): # all start, stop and status need; the base of the rest
105
- deploy_dir: str
106
- service: str
107
- service_kind: str
108
- port: int
109
- api_key: str
110
-
111
-
112
- class _Engine(TypedDict):
113
- dir: str
114
- assets: list[Archive]
115
-
116
-
117
- class EngineParams(_Engine, total=False):
118
- binary: str # the executable the engine archive must contain (default llama-server)
119
- region: str # cn or global: the order of the download sources (region.py)
120
-
121
-
122
- class StrataPreparation(TypedDict):
123
- kind: str
124
- engine_dir: str
125
- model_dir: str
126
- gguf: str
127
- pack: str
128
- experts_bin: bool
129
- gguf_py: Archive
130
- mtp_revision: str
131
- download_bytes: int
132
- scratch_bytes: int
133
- hf_endpoint: str
134
-
135
-
136
- class _DownloadParams(TypedDict):
137
- files: list[Reusable]
138
-
139
-
140
- class DownloadParams(_DownloadParams, total=False):
141
- preparation: StrataPreparation
142
- region: str # cn or global: the order of the download sources (region.py)
143
- auth_headers: dict[str, str] # host -> Authorization header value (in-memory only via stdin)
144
-
145
-
146
- class _Install(ServiceParams):
147
- argv: list[str]
148
- env: dict[str, str]
149
- record: object
150
-
151
-
152
- class InstallParams(_Install, total=False):
153
- limits: dict[str, str] # systemd [Service] resource settings, e.g. MemoryMax
154
- slice: str # the systemd --user slice the unit runs in, with its own limits
155
- slice_limits: dict[str, str]
156
- config_files: dict[str, str] # {path: content}, e.g. a Strata serve profile
157
- autostart: bool # False skips systemd --user enable on boot
158
-
159
-
160
- class _Verify(ServiceParams):
161
- model_alias: str
162
- contract: str
163
-
164
-
165
- class VerifyParams(_Verify, total=False):
166
- timeout_s: float
167
- health: dict[str, object] # {"path": "/health", "auth": true}
168
- fixture: dict[str, object] # acceptance input: STT audio to download, TTS sentences
169
- input_tokens: int # served just under it, refused (not truncated) just over it
170
- vision: bool # the LLM loads a picture reader: a synthetic picture must be read too
171
- window: int # stack agent LLM: /props n_ctx must be at least the planned window
172
- weights_on_gpu: bool # none stay in host memory: Windows gets back what they were read through
173
- smoke: bool # minimal smoke-test completion ("Reply with OK.", max_tokens=16)
174
-
175
-
176
- class RemoveParams(ServiceParams, total=False):
177
- dry_run: bool # only list what a purge deletes
178
- purge_files: list[str] # model files a purge may delete besides the deployment dir
179
- purge: list[str] # the listed files the operator approved deleting
180
- config_files: list[str] # files install wrote from the plan's config_files
181
- preparation_dir: str # the recorded model root whose failed preparation a purge may list
182
-
183
-
184
148
  class Actions(TypedDict): # deploy.PerAction holds the parameter builders to these names
185
149
  engine: Callable[[EngineParams], None] # fetch pinned engine archives, verify, unpack once
186
150
  download: Callable[[DownloadParams], None] # fetch inputs and materialize pinned outputs
@@ -192,569 +156,10 @@ class Actions(TypedDict): # deploy.PerAction holds the parameter builders to th
192
156
  remove: Callable[[RemoveParams], None] # service files only; weights stay unless purged
193
157
 
194
158
 
195
- _CHUNK = 8 << 20
196
- _PROGRESS_EVERY_S = 2.0
197
- TOUCH_PROMPT = "What is the capital of France? Reply with exactly one word."
198
- TOUCH_EXPECT = "paris"
199
- CRASH_RESTARTS = 3
200
- STOP_GRACE_S = 15.0 # a nohup service's time to exit on each signal of stop
201
- READY = ("ok",) # what llama.cpp, whisper.cpp and Strata report once the model is loaded
202
- JSON = "application/json"
203
- # A System One decision model must call an outage an outage (decision-quant README example).
204
- DECISION_STATE = "Checkout is failing for every customer."
205
- DECISION_QUESTION = {"type": "noul", "instructions": "Is a service down?"}
206
- EMBED_QUERY = "How do I reset my account password?"
207
- EMBED_NEAR = "Steps to change a forgotten login password."
208
- EMBED_FAR = "The recipe needs two cups of flour and an egg."
209
- RERANK_QUERY = "What is the capital of France?"
210
- RERANK_DOCS = [
211
- "Bananas are rich in potassium.",
212
- "Paris is the capital and largest city of France.",
213
- "The Pacific is the largest ocean on Earth.",
214
- ]
215
- RERANK_RELEVANT = 1
216
-
217
-
218
- def emit(event: str, **fields: object) -> None:
219
- fields["event"] = event
220
- sys.stdout.write(json.dumps(fields, ensure_ascii=False) + "\n")
221
- sys.stdout.flush()
222
-
223
-
224
- # Where a multi-file step stands: act_download and act_engine set it around each file, so a
225
- # download event also counts the component's bytes across them. Files before this one are on
226
- # disk already.
227
- _step: dict[str, int] = {}
159
+ # Keep process_identity referenced as an attribute of this entry module for bare-file test fixtures.
160
+ _PROCESS_IDENTITY = process_identity
228
161
 
229
-
230
- def step_fields(done: int) -> dict[str, int]:
231
- """The component-wide counters of a download event: file i of n, bytes on disk of all."""
232
- if not _step:
233
- return {}
234
- return {
235
- "file_index": _step["index"],
236
- "file_count": _step["count"],
237
- "component_done": _step["before"] + done,
238
- "component_total": _step["total"],
239
- }
240
-
241
-
242
- def each_file(files: list[tuple[str, int]]) -> Iterator[int]:
243
- """Yield each file's position in order, tracking it for step_fields until the step ends."""
244
- sizes = [size for _, size in files]
245
- kept = [
246
- size
247
- if os.path.isfile(path) and os.path.getsize(path) == size
248
- else min(size, remote_ops_download.kept_bytes(path + ".part", size))
249
- for path, size in files
250
- ]
251
- try:
252
- for i in range(len(sizes)):
253
- _step.update(
254
- index=i + 1,
255
- count=len(sizes),
256
- before=sum(sizes[:i]) + sum(kept[i + 1 :]),
257
- total=sum(sizes),
258
- )
259
- yield i
260
- finally:
261
- _step.clear()
262
-
263
-
264
- def _home(value: str) -> str:
265
- return os.path.expanduser(value) if value.startswith("~/") else value
266
-
267
-
268
- PRIVATE_SUFFIXES = (".local", ".lan", ".internal", ".intranet", ".corp", ".home.arpa")
269
-
270
-
271
- def non_public(url: str) -> bool:
272
- """A source that is not on the public internet: plain http, an IP literal in a private,
273
- loopback or link-local range, or a single-label or private-suffix host name. Such a source
274
- (a LAN registry, a user's own mirror) is never republished and is tried first, being near."""
275
- parts = urllib.parse.urlsplit(url)
276
- host = (parts.hostname or "").lower()
277
- if parts.scheme != "https" or not host:
278
- return True
279
- try:
280
- address = ipaddress.ip_address(host)
281
- except ValueError:
282
- return "." not in host or host.endswith(PRIVATE_SUFFIXES)
283
- return not address.is_global
284
-
285
-
286
- def _expand(path: str) -> str:
287
- return os.path.abspath(os.path.expanduser(path))
288
-
289
-
290
- def _read(path: str) -> str:
291
- with open(path, encoding="utf-8") as f:
292
- return f.read()
293
-
294
-
295
- def _write(path: str, text: str) -> None:
296
- with open(path, "w", encoding="utf-8") as f:
297
- f.write(text)
298
- _narrow(f.fileno(), 0o022)
299
-
300
-
301
- def _narrow(fd: int, bits: int) -> None:
302
- """Clear ``bits`` from an open file's mode. The umask applies only when a file is created, so
303
- a unit or slice an older release wrote under umask 0002 would otherwise stay group-writable
304
- when it is rewritten; a mode is only ever narrowed."""
305
- if not hasattr(os, "fchmod"): # Windows
306
- return
307
- mode = os.fstat(fd).st_mode & 0o7777
308
- if mode & bits:
309
- os.fchmod(fd, mode & ~bits)
310
-
311
-
312
- def _sha256(path: str, label: str) -> str:
313
- digest = hashlib.sha256()
314
- total = os.path.getsize(path)
315
- done, last = 0, 0.0
316
- with open(path, "rb") as f:
317
- for chunk in iter(lambda: f.read(_CHUNK), b""):
318
- digest.update(chunk)
319
- done += len(chunk)
320
- if time.monotonic() - last > _PROGRESS_EVERY_S:
321
- last = time.monotonic()
322
- emit("progress", phase="verify", file=label, done=done, total=total)
323
- return digest.hexdigest()
324
-
325
-
326
- def _cache_blob(sha256: str) -> str | None:
327
- root = os.environ.get("LOCALMODELS_CACHE_DIR", "").strip()
328
- if not root or len(sha256) != 64:
329
- return None
330
- return os.path.join(_expand(root), sha256)
331
-
332
-
333
- def _restore_cached(dest: str, sha256: str, size: int, label: str) -> bool:
334
- cached = _cache_blob(sha256)
335
- if not cached or not os.path.isfile(cached) or os.path.getsize(cached) != size:
336
- return False
337
- receipt = cached + ".sha256"
338
- if not (os.path.isfile(receipt) and _read(receipt).strip() == sha256):
339
- if _sha256(cached, label) != sha256:
340
- return False
341
- _write(receipt, sha256)
342
- tmp = f"{dest}.cache.{os.getpid()}"
343
- with contextlib.suppress(OSError):
344
- os.unlink(tmp)
345
- try:
346
- if os.stat(cached).st_dev == os.stat(os.path.dirname(dest)).st_dev:
347
- os.link(cached, tmp)
348
- else:
349
- shutil.copyfile(cached, tmp)
350
- os.replace(tmp, dest)
351
- except OSError:
352
- with contextlib.suppress(OSError):
353
- os.unlink(tmp)
354
- return False
355
- _write(dest + ".sha256", sha256)
356
- emit(
357
- "progress",
358
- phase="download",
359
- file=label,
360
- done=size,
361
- total=size,
362
- bytes_per_s=size,
363
- source="cache",
364
- connections=0,
365
- **step_fields(size),
366
- )
367
- emit("log", message="reused verified local cache for " + label)
368
- return True
369
-
370
-
371
- def _store_cached(dest: str, sha256: str, size: int) -> None:
372
- cached = _cache_blob(sha256)
373
- if not cached or (os.path.isfile(cached) and os.path.getsize(cached) == size):
374
- return
375
- with contextlib.suppress(OSError):
376
- os.makedirs(os.path.dirname(cached), mode=0o700, exist_ok=True)
377
- tmp = f"{cached}.tmp.{os.getpid()}"
378
- if os.stat(dest).st_dev == os.stat(os.path.dirname(cached)).st_dev:
379
- os.link(dest, tmp)
380
- else:
381
- shutil.copyfile(dest, tmp)
382
- os.replace(tmp, cached)
383
- _write(cached + ".sha256", sha256)
384
-
385
-
386
- def _transfer_once(
387
- source: Source,
388
- part: str,
389
- size: int,
390
- label: str,
391
- ranged: bool,
392
- *,
393
- probed_bad: bool,
394
- allow_slow: bool,
395
- ) -> None:
396
- if source.get("member"):
397
- remote_ops_download.npm_transfer(source, part, size, label)
398
- return
399
- if probed_bad:
400
- if allow_slow:
401
- remote_ops_download.transfer(
402
- source, part, size, label, ranged, attempts=1, allow_slow_switch=True
403
- )
404
- else:
405
- remote_ops_download.transfer(source, part, size, label, ranged, attempts=1)
406
- return
407
- if allow_slow:
408
- remote_ops_download.transfer(source, part, size, label, ranged, allow_slow_switch=True)
409
- else:
410
- remote_ops_download.transfer(source, part, size, label, ranged)
411
-
412
-
413
- _SECRET_RE = re.compile(
414
- r"(?:Bearer\s+\S+|hf_[A-Za-z0-9]{6,}|ms[-_][A-Za-z0-9_-]{6,})",
415
- re.IGNORECASE,
416
- )
417
-
418
-
419
- def redact_text(text: str) -> str:
420
- """Strip Bearer credentials and hub token patterns from logs and errors."""
421
- return _SECRET_RE.sub("[REDACTED]", text)
422
-
423
-
424
- def gguf_magic_ok(path: str, label: str) -> bool:
425
- """Verify the 4-byte GGUF magic header for .gguf files."""
426
- if not label.lower().endswith(".gguf"):
427
- return True
428
- try:
429
- with open(path, "rb") as handle:
430
- return handle.read(4) == b"GGUF"
431
- except OSError:
432
- return False
433
-
434
-
435
- def _existing_verified(dest: str, marker: str, sha256: str, size: int, label: str) -> bool:
436
- if not sha256:
437
- if (
438
- size > 0
439
- and os.path.exists(dest)
440
- and os.path.getsize(dest) == size
441
- and gguf_magic_ok(dest, label)
442
- ):
443
- emit("log", message="verified, skipping " + label)
444
- return True
445
- os.makedirs(os.path.dirname(dest), exist_ok=True)
446
- return False
447
- if os.path.exists(dest) and os.path.exists(marker) and _read(marker).strip() == sha256:
448
- emit("log", message="verified, skipping " + label)
449
- return True
450
- os.makedirs(os.path.dirname(dest), exist_ok=True)
451
- if os.path.exists(dest) and os.path.getsize(dest) == size and _sha256(dest, label) == sha256:
452
- _write(marker, sha256)
453
- _store_cached(dest, sha256, size)
454
- return True
455
- return _restore_cached(dest, sha256, size, label)
456
-
457
-
458
- def fetch(
459
- url: str,
460
- dest: str,
461
- sha256: str,
462
- size: int,
463
- label: str,
464
- mirrors: list[Source] | None = None,
465
- region: str | None = None,
466
- ) -> str | None:
467
- """Download ``url`` (or another source of the same pinned bytes: ``mirrors`` and, given a
468
- ``region``, the alternates that region adds) to ``dest`` unless a verified copy exists.
469
- Resumes a .part file, from any source. Returns the region to switch to when the region's
470
- own side failed or was decisively outperformed by the other side (also reported as
471
- ``region_fallback`` on the log event), else None."""
472
- marker = dest + ".sha256"
473
- if _existing_verified(dest, marker, sha256, size, label):
474
- return None
475
- free = shutil.disk_usage(os.path.dirname(dest)).free
476
- part = dest + ".part"
477
- had_part = os.path.exists(part)
478
- have = remote_ops_download.kept_bytes(part, size)
479
- if have > size:
480
- remote_ops_download.discard(part)
481
- had_part, have = False, 0
482
- if size - have > free:
483
- raise RuntimeError(f"low disk space: {label} needs {size - have} more bytes, {free} free")
484
- sources: list[Source] = [{"source": remote_ops_download.source_name(url), "url": url}]
485
- sources += [m for m in mirrors or [] if m.get("url") and m["url"] != url]
486
- error: Exception | None = None
487
- failed: list[Source] = []
488
- slow_urls: set[str] = set()
489
- fresh_retried: set[str] = set()
490
- deferred_slow: list[tuple[Source, bool]] = []
491
- immediate: list[tuple[Source, bool]] = []
492
- probe_speeds: dict[str, float] = {}
493
- stream = iter(remote_ops_download.ordered(sources, size, label, region, failed, probe_speeds))
494
- upcoming = next(stream, None)
495
- supports_slow = remote_ops_download.transfer is remote_ops_download.DEFAULT_TRANSFER
496
-
497
- while immediate or upcoming is not None or deferred_slow:
498
- if immediate:
499
- source, ranged = immediate.pop(0)
500
- elif upcoming is not None:
501
- source, ranged = upcoming
502
- upcoming = next(stream, None)
503
- else:
504
- source, ranged = deferred_slow.pop(0)
505
- probed_bad = any(f["url"] == source["url"] for f in failed)
506
- has_more = (
507
- bool(immediate)
508
- or upcoming is not None
509
- or any(s["url"] not in slow_urls for s, _ in deferred_slow)
510
- )
511
- allow_slow = supports_slow and has_more and source["url"] not in slow_urls
512
- resumed_prior = os.path.exists(part) and os.path.getsize(part) > 0
513
- try:
514
- _transfer_once(
515
- source, part, size, label, ranged, probed_bad=probed_bad, allow_slow=allow_slow
516
- )
517
- except remote_ops_download.SlowTransferError as exc:
518
- emit(
519
- "log",
520
- message=(
521
- f"download from {source['source']} is too slow for {label} ({exc}); "
522
- "switching source"
523
- ),
524
- )
525
- error = exc
526
- slow_urls.add(source["url"])
527
- deferred_slow.append((source, ranged))
528
- failed.append(source)
529
- continue
530
- except Exception as exc: # noqa: BLE001 - the next source is tried, the last re-raised
531
- emit(
532
- "log",
533
- message=f"download from {source['source']} stopped, {label}: {redact_text(str(exc))}",
534
- )
535
- error = exc
536
- failed.append(source)
537
- continue
538
- mismatch = _check_part(part, sha256, size, label, source["source"])
539
- if mismatch is not None:
540
- error = mismatch
541
- remote_ops_download.discard(part)
542
- if resumed_prior and source["url"] not in fresh_retried:
543
- fresh_retried.add(source["url"])
544
- immediate.append((source, ranged))
545
- continue
546
- remote_ops_download.discard(part + ".ranges") # the record only; part is renamed
547
- os.replace(part, dest)
548
- if sha256:
549
- _write(marker, sha256)
550
- _store_cached(dest, sha256, size)
551
- else:
552
- _write(marker, _sha256(dest, label))
553
- switch = _fallback(region, source, failed, probe_speeds)
554
- extra = {"region_fallback": switch} if switch else {}
555
- emit("log", message=f"downloaded and verified {label} from {source['source']}", **extra)
556
- return switch
557
- if not had_part and remote_ops_download.kept_bytes(part, size) == 0:
558
- remote_ops_download.discard(part)
559
- raise error or RuntimeError(f"{label} has no download source")
560
-
561
-
562
- def _check_part(
563
- part: str, sha256: str, size: int, label: str, source_name: str
564
- ) -> Exception | None:
565
- got_size = os.path.getsize(part)
566
- if size <= 0 or got_size != size:
567
- return RuntimeError(f"{label} size mismatch: {got_size} != {size}")
568
- if not sha256:
569
- if not gguf_magic_ok(part, label):
570
- emit("log", message=f"{label} from {source_name} failed the GGUF magic check")
571
- return RuntimeError(f"{label} is not a valid GGUF file (bad magic)")
572
- return None
573
- actual = _sha256(part, label)
574
- if actual != sha256:
575
- emit("log", message=f"{label} from {source_name} failed the SHA256 check")
576
- return RuntimeError(f"{label} SHA256 mismatch: {actual} != {sha256}")
577
- return None
578
-
579
-
580
- def _fallback(
581
- region: str | None,
582
- used: Source,
583
- failed: list[Source],
584
- probe_speeds: dict[str, float] | None = None,
585
- ) -> str | None:
586
- """The other region, when ``used`` is on its side and either a source on the region's own
587
- side failed/was slow-aborted first, or cross-region speed probing proved the other side was
588
- decisively faster (>= 2x) while every probed preferred source was below
589
- ``CROSS_REGION_PROBE_BPS``. A neutral source (GitHub, a LAN or user mirror) never switches."""
590
- other = remote_ops_download.side(used["url"])
591
- if region not in ("cn", "global") or other in ("", region):
592
- return None
593
- mine = [s for s in failed if remote_ops_download.side(s["url"]) == region]
594
- if mine:
595
- return other
596
- if probe_speeds:
597
- used_speed = probe_speeds.get(used["url"], 0.0)
598
- pref_speeds = [
599
- bps
600
- for candidate_url, bps in probe_speeds.items()
601
- if remote_ops_download.side(candidate_url) == region
602
- ]
603
- if (
604
- used_speed > 0
605
- and pref_speeds
606
- and max(pref_speeds) < remote_ops_download.CROSS_REGION_PROBE_BPS
607
- and used_speed >= 2.0 * max(pref_speeds)
608
- ):
609
- return other
610
- return None
611
-
612
-
613
- def _relative(name: str) -> str:
614
- while name.startswith("./"):
615
- name = name[2:]
616
- return name
617
-
618
-
619
- def _unzip(archive: str, directory: str, members: tuple[str, ...] = ()) -> None:
620
- """A Windows release zip: regular files only, each kept inside ``directory``."""
621
- with zipfile.ZipFile(archive) as bundle:
622
- names = [_relative(i.filename.replace("\\", "/")) for i in bundle.infolist()]
623
- tops = {n.split("/", 1)[0] for n in names if n}
624
- strip = len(tops) == 1 and any("/" in n for n in names)
625
- for info, name in zip(bundle.infolist(), names):
626
- if strip:
627
- name = name.split("/", 1)[1] if "/" in name else ""
628
- if members and not name.startswith(members):
629
- continue
630
- if not name or info.is_dir() or name.startswith("/") or ".." in name.split("/"):
631
- continue
632
- if ":" in name or (info.external_attr >> 16) & 0o170000 == 0o120000:
633
- continue # a drive letter or a symlink entry
634
- target = os.path.join(directory, *name.split("/"))
635
- os.makedirs(os.path.dirname(target), exist_ok=True)
636
- with bundle.open(info) as source, open(target, "wb") as dest:
637
- shutil.copyfileobj(source, dest)
638
-
639
-
640
- def unpack(archive: str, directory: str, keep: tuple[str, ...] = ()) -> None:
641
- """Extract into ``directory``, dropping the archive's single top folder when it has one;
642
- ``keep``: only the paths under these prefixes (Archive.members). A wheel is a zip
643
- (PolyStrata's Windows build takes cuBLAS from NVIDIA's)."""
644
- if archive.endswith((".zip", ".whl")):
645
- _unzip(archive, directory, keep)
646
- return
647
- with tarfile.open(archive) as tar:
648
- members = tar.getmembers()
649
- tops = {m.name.lstrip("./").split("/", 1)[0] for m in members if m.name.lstrip("./")}
650
- strip = len(tops) == 1 and any("/" in m.name.lstrip("./") for m in members)
651
- for member in members:
652
- name = member.name.lstrip("./")
653
- if strip:
654
- name = name.split("/", 1)[1] if "/" in name else ""
655
- if keep and not name.startswith(keep):
656
- continue
657
- if not name or name.startswith("/") or ".." in name.split("/"):
658
- continue
659
- if member.issym() or member.islnk():
660
- target = member.linkname
661
- if target.startswith("/") or ".." in target.split("/")[:-1]:
662
- continue
663
- if member.islnk() and strip:
664
- member.linkname = target.lstrip("./").split("/", 1)[-1]
665
- member.name = name
666
- if member.isdir():
667
- member.mode |= 0o700
668
- elif member.isfile():
669
- member.mode |= 0o200
670
- if member.issym() or member.islnk():
671
- remote_ops_download.clear_link(os.path.join(directory, name))
672
- tar.extract(member, directory)
673
-
674
-
675
- def _paths(p: ServiceParams) -> dict[str, str]:
676
- root = _expand(p["deploy_dir"])
677
- return {
678
- "root": root,
679
- "script": os.path.join(root, "run.cmd" if sys.platform == "win32" else "run.sh"),
680
- "log": os.path.join(root, "server.log"),
681
- "key": os.path.join(root, "api-key"),
682
- "pid": os.path.join(root, "server.pid"),
683
- "spec": os.path.join(root, "deployment.json"),
684
- "unit": _expand("~/.config/systemd/user/{}.service".format(p["service"])),
685
- }
686
-
687
-
688
- def _systemctl(*args: str) -> tuple[int, str]:
689
- out = subprocess.run(
690
- ["systemctl", "--user", *args], capture_output=True, text=True, check=False
691
- )
692
- return out.returncode, (out.stdout + out.stderr).strip()
693
-
694
-
695
- def _systemctl_ok(*args: str) -> None:
696
- rc, out = _systemctl(*args)
697
- if rc != 0:
698
- raise RuntimeError(f"systemctl {args[0]} failed: " + out)
699
-
700
-
701
- # macOS and Windows have no /proc: their nohup services keep process identity receipts.
702
- def receipts() -> bool:
703
- return sys.platform in ("darwin", "win32")
704
-
705
-
706
- def _pid_alive(pid_path: str) -> int | None:
707
- if receipts():
708
- return process_identity.status(pid_path)[1]
709
- try:
710
- pid = int(_read(pid_path).strip())
711
- os.kill(pid, 0)
712
- return pid
713
- except (OSError, ValueError):
714
- return None
715
-
716
-
717
- def _port_owner(port: int) -> bool:
718
- """True when something already listens on 127.0.0.1:port."""
719
- if sys.platform == "win32": # a refused loopback connect retries for seconds there
720
- owners = process_identity.listener_pids(port)
721
- return owners is None or bool(owners)
722
- with socket.socket() as s:
723
- s.settimeout(1)
724
- return s.connect_ex(("127.0.0.1", port)) == 0
725
-
726
-
727
- def _request(url: str, api_key: str, data: bytes | None, kind: str, timeout: float) -> bytes:
728
- """One request to a loopback service with the deployment key, past any proxy settings."""
729
- headers = {"Authorization": "Bearer " + api_key, "Content-Type": kind}
730
- if trace := globals().get("_REQUEST_ID"):
731
- headers["X-Request-ID"] = str(trace)
732
- req = urllib.request.Request(url, data=data, headers=headers)
733
- with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(
734
- req, timeout=timeout
735
- ) as r:
736
- return cast(bytes, r.read())
737
-
738
-
739
- def _http(url: str, api_key: str, body: object = None, timeout: float = 10) -> dict[str, object]:
740
- data = json.dumps(body).encode() if body is not None else None
741
- value = json.loads(_request(url, api_key, data, JSON, timeout) or b"{}")
742
- if not isinstance(value, dict):
743
- raise ValueError("expected HTTP JSON object")
744
- return cast("dict[str, object]", value)
745
-
746
-
747
- def _log_tail(paths: dict[str, str], lines: int = 30) -> str:
748
- try:
749
- with open(paths["log"], "rb") as f:
750
- f.seek(0, 2)
751
- f.seek(max(0, f.tell() - 16384))
752
- return "\n".join(f.read().decode("utf-8", "replace").splitlines()[-lines:])
753
- except OSError:
754
- return ""
755
-
756
-
757
- # The moved handlers keep their remote_ops.* names for callers, tests and ACTIONS.
162
+ # The action handlers keep their remote_ops.* names for callers, tests and ACTIONS.
758
163
  act_engine = remote_ops_download.act_engine
759
164
  act_download = remote_ops_download.act_download
760
165
  act_install = remote_ops_service.act_install
@@ -763,7 +168,6 @@ act_stop = remote_ops_service.act_stop
763
168
  act_status = remote_ops_service.act_status
764
169
  act_verify = remote_ops_verify.act_verify
765
170
  act_remove = remote_ops_remove.act_remove
766
- _verify_stt = remote_ops_verify._verify_stt
767
171
 
768
172
 
769
173
  ACTIONS: Actions = {
@@ -779,6 +183,7 @@ ACTIONS: Actions = {
779
183
 
780
184
 
781
185
  def main(argv: list[str]) -> int:
186
+ remote_ops_common.set_request_id(globals().get("_REQUEST_ID"))
782
187
  remote_ops_download.bind_to_parent(globals().get("_PARENT_PID"))
783
188
  os.umask(os.umask(0o022) | 0o022) # never leave group/world-writable files under umask 0002
784
189
  encoded = globals().get("_PARAMS_B64") or (argv[2] if len(argv) == 3 else None)
@@ -789,7 +194,9 @@ def main(argv: list[str]) -> int:
789
194
  try:
790
195
  run(json.loads(base64.b64decode(encoded).decode("utf-8")))
791
196
  except Exception as exc: # report every failure as an event the controller can show
792
- emit("error", message=redact_text(str(exc)), type=type(exc).__name__)
197
+ remote_ops_common.emit(
198
+ "error", message=remote_ops_common.redact_text(str(exc)), type=type(exc).__name__
199
+ )
793
200
  return 1
794
201
  return 0
795
202