@simplexai/localmodels-win32-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
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env python3
2
2
  """Parallel byte-range transfer of one file, with connections that rebalance ranges.
3
3
 
4
- Part of the remote_ops bundle (transport.BUNDLES): standard library only, Python 3.8+. The
5
- tunables live in remote_ops_download and are read as ``download.<name>`` at call
6
- time, so the bundle keeps one patchable surface.
4
+ Part of the remote_ops bundle (transport.BUNDLES): standard library only, Python 3.8+. Owns the
5
+ range-transfer tunables and SlowTransferError so ``remote_ops_download`` imports strictly
6
+ downward without any cycle.
7
7
  """
8
8
 
9
9
  from __future__ import annotations
@@ -17,49 +17,87 @@ import statistics
17
17
  import threading
18
18
  import time
19
19
  import urllib.error
20
- import urllib.request
21
20
  from typing import Any
22
21
 
23
22
  try:
24
- from localmodels import remote_ops, remote_ops_mirrors
25
- from localmodels import remote_ops_download as download
23
+ from localmodels import remote_ops_common, remote_ops_mirrors
26
24
  except ImportError: # run as a bare file from this directory
27
- import remote_ops # type: ignore[import-not-found,no-redef]
28
- import remote_ops_download as download # type: ignore[import-not-found,no-redef]
25
+ import remote_ops_common # type: ignore[import-not-found,no-redef]
29
26
  import remote_ops_mirrors # type: ignore[import-not-found,no-redef]
30
27
 
28
+ # Switch away from a transfer whose sustained throughput over SLOW_WINDOW_S stays below
29
+ # SLOW_BYTES_PER_S while more than SLOW_MIN_REMAINING_S of transfer time remains.
30
+ SLOW_WINDOW_S = 15.0
31
+ SLOW_BYTES_PER_S = 256 * 1024
32
+ SLOW_MIN_REMAINING_S = 30.0
33
+ # A file is fetched over up to CONNECTIONS parallel byte ranges of at least MIN_SEGMENT_BYTES
34
+ # each. A connection that finishes its range takes over the second part of the range that will
35
+ # finish last (work stealing), split by the two connections' rates so both end together; a
36
+ # stalled connection loses all of its range. A piece is stolen only when the thief would spend
37
+ # at least STEAL_MIN_S on it, so the extra request (TLS, a Hub redirect) is worth it. Counts come
38
+ # from the 2026-11-24 measurements in docs/local-models/network-download-optimization.md: from
39
+ # China the Hugging Face CDN (also behind hf-mirror) caps each connection near 0.1 MB/s, so 16
40
+ # connections fetch about 16 times as fast; ModelScope reaches the link's ~100 MB/s with 8.
41
+ CONNECTIONS = 8
42
+ SOURCE_CONNECTIONS: dict[str, int] = {"huggingface": 16, "hf-mirror": 16}
43
+ MIN_SEGMENT_BYTES = 64 << 20
44
+ STEAL_MIN_S = 6.0
45
+ STEAL_MIN_BYTES = 8 << 20 # while no connection's rate is known yet, halve ranges this large
46
+ CLAIM_GRACE_S = 3.0 # a connection's rate is unknown until this long after its first byte
47
+ # A connection with no first byte after this long counts as stalled. The first byte of a Hub
48
+ # range took up to 3 s (a redirect, then TLS to the CDN), so a slow start is not a stall.
49
+ CLAIM_STALL_S = 20.0
50
+ CLAIM_RATE_WINDOW_S = 10.0
51
+ STEAL_POLL_S = 0.5 # how often an idle connection looks for a range to steal
52
+ ATTEMPTS = 5
53
+ # A connection's progress moves once per read, so reads stay small: an 8 MiB read at 2-3 MB/s
54
+ # per connection made the 2 s rate jump in 4 MiB/s steps (often 0). The rate shown is the
55
+ # average over RATE_WINDOW_S, so a stall or burst of one connection does not swing the ETA.
56
+ READ_BYTES = 1 << 20
57
+
58
+
59
+ class SlowTransferError(RuntimeError):
60
+ """Sustained transfer throughput dropped below SLOW_BYTES_PER_S; switch to another host."""
61
+
62
+ def __init__(self, bytes_per_s: int) -> None:
63
+ self.bytes_per_s = bytes_per_s
64
+ super().__init__(
65
+ f"download too slow ({bytes_per_s / 1024:.0f} KB/s < "
66
+ f"{SLOW_BYTES_PER_S / 1024:.0f} KB/s)"
67
+ )
68
+
31
69
 
32
- class _NoRangeError(Exception):
70
+ class NoRangeError(Exception):
33
71
  """The source stopped honouring byte ranges; the next source is tried."""
34
72
 
35
73
 
36
- def connections_for(source: remote_ops.Source) -> int:
74
+ def connections_for(source: remote_ops_common.Source) -> int:
37
75
  """How many parallel ranges to open on ``source`` (a few hosts throttle each connection)."""
38
76
  return max(
39
77
  1,
40
- download.SOURCE_CONNECTIONS.get(source.get("source", ""), download.CONNECTIONS),
78
+ SOURCE_CONNECTIONS.get(source.get("source", ""), CONNECTIONS),
41
79
  )
42
80
 
43
81
 
44
82
  def _split(start: int, end: int, count: int | None = None) -> list[list[int]]:
45
83
  """[start, end, done] segments of [start, end): ``count`` (default CONNECTIONS) of them when
46
84
  each gets at least MIN_SEGMENT_BYTES, fewer otherwise, never none for a non-empty range."""
47
- wanted = download.CONNECTIONS if count is None else count
48
- count = max(1, min(wanted, (end - start) // download.MIN_SEGMENT_BYTES))
85
+ wanted = CONNECTIONS if count is None else count
86
+ count = max(1, min(wanted, (end - start) // MIN_SEGMENT_BYTES))
49
87
  step = -(-(end - start) // count)
50
88
  return [[s, min(end, s + step), s] for s in range(start, end, step)]
51
89
 
52
90
 
53
- def _resume_ranges(part: str, size: int, count: int | None = None) -> list[list[int]]:
91
+ def resume_ranges(part: str, size: int, count: int | None = None) -> list[list[int]]:
54
92
  """The segments still to fetch. A plain .part (a single-connection download of an earlier
55
93
  version) is a finished prefix; the file is then sized so each range writes in place."""
56
- segments = download._load_ranges(part, size)
94
+ segments = remote_ops_common.load_ranges(part, size)
57
95
  if segments is None:
58
96
  have = os.path.getsize(part) if os.path.exists(part) else 0
59
97
  with open(part, "ab") as out:
60
98
  out.truncate(size)
61
99
  segments = _split(have, size, count) if have < size else []
62
- download._save_ranges(part, size, segments)
100
+ remote_ops_common.save_ranges(part, size, segments)
63
101
  return segments
64
102
 
65
103
 
@@ -71,7 +109,7 @@ def _retryable(exc: BaseException) -> bool:
71
109
  return True
72
110
 
73
111
 
74
- class _Claim:
112
+ class Claim:
75
113
  """One connection's hold on a segment, with recent (time, done) marks for its rate."""
76
114
 
77
115
  def __init__(self, segment: list[int], now: float) -> None:
@@ -84,7 +122,7 @@ class _Claim:
84
122
  if self.first is None:
85
123
  self.first = now
86
124
  self.marks.append((now, self.segment[2]))
87
- while len(self.marks) > 2 and now - self.marks[1][0] >= download.CLAIM_RATE_WINDOW_S:
125
+ while len(self.marks) > 2 and now - self.marks[1][0] >= CLAIM_RATE_WINDOW_S:
88
126
  self.marks.popleft()
89
127
 
90
128
  def rate(self, now: float) -> float | None:
@@ -92,14 +130,14 @@ class _Claim:
92
130
  byte yet, or less than CLAIM_GRACE_S since it), 0 with no first byte after
93
131
  CLAIM_STALL_S. A stalled connection adds no marks, so its rate falls towards zero."""
94
132
  if self.first is None:
95
- return 0.0 if now - self.since >= download.CLAIM_STALL_S else None
96
- if now - self.first < download.CLAIM_GRACE_S:
133
+ return 0.0 if now - self.since >= CLAIM_STALL_S else None
134
+ if now - self.first < CLAIM_GRACE_S:
97
135
  return None
98
136
  then, before = self.marks[0]
99
137
  return (self.segment[2] - before) / max(1e-3, now - then)
100
138
 
101
139
 
102
- class _Transfer:
140
+ class Transfer:
103
141
  """Parallel ranged download of one file. Each connection claims a segment and fetches it
104
142
  from its ``done`` offset with retries, then claims another or steals the tail of the one
105
143
  that will finish last. ``done`` advances only after the bytes are written and never past
@@ -117,12 +155,12 @@ class _Transfer:
117
155
  connections: int = 1,
118
156
  ) -> None:
119
157
  self.url, self.part, self.size, self.segments = url, part, size, segments
120
- self.attempts = download.ATTEMPTS if attempts is None else max(1, attempts)
158
+ self.attempts = ATTEMPTS if attempts is None else max(1, attempts)
121
159
  self.connections = max(1, connections)
122
160
  self.lock, self.io_lock = threading.Lock(), threading.Lock()
123
161
  self.stop = threading.Event()
124
162
  self.errors: list[BaseException] = []
125
- self.claims: dict[int, _Claim] = {} # id(segment) -> its connection's claim
163
+ self.claims: dict[int, Claim] = {} # id(segment) -> its connection's claim
126
164
  self.steals = 0
127
165
  self._responses: list[Any] = []
128
166
 
@@ -165,7 +203,7 @@ class _Transfer:
165
203
  if claim is None:
166
204
  if not self.active():
167
205
  return
168
- self.stop.wait(download.STEAL_POLL_S) # stay to take over a range that stalls later
206
+ self.stop.wait(STEAL_POLL_S) # stay to take over a range that stalls later
169
207
  continue
170
208
  try:
171
209
  self.worker(claim.segment, claim)
@@ -174,7 +212,7 @@ class _Transfer:
174
212
  pace = claim.rate(time.monotonic())
175
213
  self.claims.pop(id(claim.segment), None)
176
214
 
177
- def _claim(self, pace: float | None) -> _Claim | None:
215
+ def _claim(self, pace: float | None) -> Claim | None:
178
216
  now, victim = time.monotonic(), None
179
217
  with self.lock:
180
218
  if self.stop.is_set():
@@ -186,19 +224,19 @@ class _Transfer:
186
224
  segment, victim = self._steal(now, pace)
187
225
  if segment is None:
188
226
  return None
189
- claim = self.claims[id(segment)] = _Claim(segment, now)
227
+ claim = self.claims[id(segment)] = Claim(segment, now)
190
228
  response = victim.response if victim is not None else None
191
229
  if response is not None: # a stalled victim gave up all of its range: unblock it
192
230
  _close(response)
193
231
  return claim
194
232
 
195
- def _steal(self, now: float, pace: float | None) -> tuple[list[int] | None, _Claim | None]:
233
+ def _steal(self, now: float, pace: float | None) -> tuple[list[int] | None, Claim | None]:
196
234
  """Under ``lock``: split off the tail of the claim that will finish last and return it
197
235
  (and the victim when it keeps nothing), or (None, None) when no split is worth it."""
198
236
  rates = [r for r in (c.rate(now) for c in self.claims.values()) if r]
199
237
  peer = statistics.median(rates) if rates else None
200
238
  thief = pace if pace else peer # only measured, moving rates
201
- best: tuple[float, _Claim, int] | None = None
239
+ best: tuple[float, Claim, int] | None = None
202
240
  for claim in self.claims.values():
203
241
  left = claim.segment[1] - claim.segment[2]
204
242
  share = _share(left, claim.rate(now), thief) if left > 0 else None
@@ -215,12 +253,14 @@ class _Transfer:
215
253
  self.steals += 1
216
254
  return stolen, (claim if keep == 0 else None)
217
255
 
218
- def _range(self, segment: list[int], claim: _Claim) -> None:
256
+ def _range(self, segment: list[int], claim: Claim) -> None:
219
257
  with self.lock:
220
258
  done, end = segment[2], segment[1]
221
259
  if done >= end:
222
260
  return
223
- with download.open_url(download._ranged_request(self.url, done, end), timeout=60) as r:
261
+ with remote_ops_common.open_url(
262
+ remote_ops_common.build_request(self.url, done, end), timeout=60
263
+ ) as r:
224
264
  self._track_response(r)
225
265
  claim.response = r
226
266
  try:
@@ -229,7 +269,7 @@ class _Transfer:
229
269
  if getattr(r, "status", 200) != 206 or not str(
230
270
  r.headers.get("Content-Range", "")
231
271
  ).startswith(f"bytes {done}-"):
232
- raise _NoRangeError()
272
+ raise NoRangeError()
233
273
  read_fn = getattr(r, "read1", r.read)
234
274
  with self.io_lock:
235
275
  if self.stop.is_set():
@@ -242,7 +282,7 @@ class _Transfer:
242
282
  end = segment[1] # a thief may have cut the range short
243
283
  if done >= end:
244
284
  break
245
- chunk = read_fn(min(download.READ_BYTES, end - done))
285
+ chunk = read_fn(min(READ_BYTES, end - done))
246
286
  if not chunk:
247
287
  break
248
288
  with self.io_lock:
@@ -262,14 +302,14 @@ class _Transfer:
262
302
  if done < end and not self.stop.is_set():
263
303
  raise http.client.IncompleteRead(b"", end - done)
264
304
 
265
- def worker(self, segment: list[int], claim: _Claim | None = None) -> None:
305
+ def worker(self, segment: list[int], claim: Claim | None = None) -> None:
266
306
  if claim is None:
267
- claim = _Claim(segment, time.monotonic())
307
+ claim = Claim(segment, time.monotonic())
268
308
  attempt = 0
269
309
  while not self._finished(segment) and not self.stop.is_set():
270
310
  try:
271
311
  self._range(segment, claim)
272
- except _NoRangeError as exc:
312
+ except NoRangeError as exc:
273
313
  self.fail(exc)
274
314
  except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
275
315
  if self.stop.is_set() or self._finished(segment):
@@ -303,15 +343,11 @@ def _share(left: int, own: float | None, thief: float | None) -> tuple[int, floa
303
343
  return 0, float("inf")
304
344
  if own is None or thief is None:
305
345
  keep = left // 2
306
- return (
307
- (keep, left / (own or thief or 1e6))
308
- if left - keep >= download.STEAL_MIN_BYTES
309
- else None
310
- )
346
+ return (keep, left / (own or thief or 1e6)) if left - keep >= STEAL_MIN_BYTES else None
311
347
  keep = int(left * own / (own + thief))
312
- if keep < download.READ_BYTES:
348
+ if keep < READ_BYTES:
313
349
  keep = 0
314
- return (keep, left / own) if (left - keep) / thief >= download.STEAL_MIN_S else None
350
+ return (keep, left / own) if (left - keep) / thief >= STEAL_MIN_S else None
315
351
 
316
352
 
317
353
  def _close(resp: Any) -> None:
@@ -332,28 +368,28 @@ def _close(resp: Any) -> None:
332
368
  threading.Thread(target=close, daemon=True).start()
333
369
 
334
370
 
335
- def _finish(job: _Transfer, label: str) -> None:
371
+ def finish_transfer(job: Transfer, label: str) -> None:
336
372
  if job.errors:
337
373
  raise job.errors[0]
338
374
  if job.remaining():
339
375
  raise RuntimeError(f"{label} download stopped with bytes missing")
340
376
 
341
377
 
342
- def _threads(job: _Transfer, ranged: bool) -> list[threading.Thread]:
378
+ def _threads(job: Transfer, ranged: bool) -> list[threading.Thread]:
343
379
  if not ranged:
344
380
  return [threading.Thread(target=_plain, args=(job,), daemon=True)]
345
381
  # a resumed file of one large open range spreads over every connection again
346
382
  open_ranges = sum(1 for s in job.segments if s[2] < s[1])
347
- count = min(job.connections, max(open_ranges, job.remaining() // download.MIN_SEGMENT_BYTES))
383
+ count = min(job.connections, max(open_ranges, job.remaining() // MIN_SEGMENT_BYTES))
348
384
  return [
349
385
  threading.Thread(target=job.connection, daemon=True)
350
386
  for _ in range(max(1, count) if open_ranges else 0)
351
387
  ]
352
388
 
353
389
 
354
- def _run(
355
- job: _Transfer,
356
- source: remote_ops.Source,
390
+ def run_transfer(
391
+ job: Transfer,
392
+ source: remote_ops_common.Source,
357
393
  label: str,
358
394
  *,
359
395
  ranged: bool,
@@ -372,20 +408,20 @@ def _run(
372
408
  if not alive or not job.remaining(): # a stalled thief's victim may still be blocked
373
409
  break
374
410
  for t in alive:
375
- t.join(timeout=remote_ops._PROGRESS_EVERY_S / len(alive))
411
+ t.join(timeout=remote_ops_common.PROGRESS_EVERY_S / len(alive))
376
412
  now, done = time.monotonic(), size - job.remaining()
377
413
  if allow_slow_switch and not job.stop.is_set():
378
414
  window_elapsed = now - slow_window_start
379
- if window_elapsed >= download.SLOW_WINDOW_S:
415
+ if window_elapsed >= SLOW_WINDOW_S:
380
416
  window_rate = int((done - slow_window_done) / max(1e-3, window_elapsed))
381
417
  remaining = max(0, size - done)
382
- near_done = remaining <= download.SLOW_BYTES_PER_S * download.SLOW_MIN_REMAINING_S
383
- if window_rate < download.SLOW_BYTES_PER_S and not near_done:
384
- job.fail(download.SlowTransferError(window_rate))
418
+ near_done = remaining <= SLOW_BYTES_PER_S * SLOW_MIN_REMAINING_S
419
+ if window_rate < SLOW_BYTES_PER_S and not near_done:
420
+ job.fail(SlowTransferError(window_rate))
385
421
  break
386
422
  slow_window_start, slow_window_done = now, done
387
- if now - mark >= remote_ops._PROGRESS_EVERY_S:
388
- remote_ops.emit(
423
+ if now - mark >= remote_ops_common.PROGRESS_EVERY_S:
424
+ remote_ops_common.emit(
389
425
  "progress",
390
426
  phase="download",
391
427
  file=label,
@@ -394,11 +430,11 @@ def _run(
394
430
  bytes_per_s=meter.add(now, done),
395
431
  source=source["source"],
396
432
  connections=max(1, job.active()) if ranged else 1,
397
- **remote_ops.step_fields(done),
433
+ **remote_ops_common.step_fields(done),
398
434
  )
399
435
  mark = now
400
436
  if ranged:
401
- download._save_ranges(job.part, size, job.snapshot())
437
+ remote_ops_common.save_ranges(job.part, size, job.snapshot())
402
438
  if job.errors or any(t.is_alive() for t in threads):
403
439
  job.stop_and_close()
404
440
  deadline = time.monotonic() + 2.0
@@ -406,19 +442,19 @@ def _run(
406
442
  if t.is_alive():
407
443
  t.join(timeout=max(0.0, deadline - time.monotonic()))
408
444
  if ranged:
409
- download._save_ranges(job.part, size, job.snapshot())
445
+ remote_ops_common.save_ranges(job.part, size, job.snapshot())
410
446
  if job.steals:
411
- remote_ops.emit(
447
+ remote_ops_common.emit(
412
448
  "log",
413
449
  message=f"{label}: {len(threads)} connections, {job.steals} ranges rebalanced",
414
450
  )
415
451
 
416
452
 
417
- def _plain(job: _Transfer) -> None:
453
+ def _plain(job: Transfer) -> None:
418
454
  """A single unranged stream (a data: URL or a server without Range support)."""
419
455
  segment = job.segments[0]
420
456
  try:
421
- with download.open_url(download.build_request(job.url), timeout=60) as r:
457
+ with remote_ops_common.open_url(remote_ops_common.build_request(job.url), timeout=60) as r:
422
458
  job._track_response(r)
423
459
  try:
424
460
  with job.io_lock:
@@ -428,7 +464,7 @@ def _plain(job: _Transfer) -> None:
428
464
  with out:
429
465
  read_fn = getattr(r, "read1", r.read)
430
466
  while not job.stop.is_set():
431
- chunk = read_fn(download.READ_BYTES)
467
+ chunk = read_fn(READ_BYTES)
432
468
  if not chunk:
433
469
  break
434
470
  with job.io_lock:
@@ -2,9 +2,8 @@
2
2
  """remote_ops ``remove`` action: service files and the shared slice; weights stay unless purged.
3
3
 
4
4
  Part of the remote_ops bundle shipped to the target as one stdin payload (transport.BUNDLES):
5
- standard library only, Python 3.8+. Shared primitives stay in the entry module and are used
6
- here as ``remote_ops.<name>``, so the bundle keeps one patchable surface and needs no
7
- private-name imports.
5
+ standard library only, Python 3.8+. Shared primitives live in ``remote_ops_common`` and are used
6
+ here via ``remote_ops_common.<name>`` so the bundle stays acyclic with no private-name accesses.
8
7
  """
9
8
 
10
9
  from __future__ import annotations
@@ -15,9 +14,14 @@ import time
15
14
  from typing import Callable
16
15
 
17
16
  try:
18
- from localmodels import remote_ops, remote_ops_launchd, remote_ops_prepare, remote_ops_service
17
+ from localmodels import (
18
+ remote_ops_common,
19
+ remote_ops_launchd,
20
+ remote_ops_prepare,
21
+ remote_ops_service,
22
+ )
19
23
  except ImportError: # run as a bare file from this directory
20
- import remote_ops # type: ignore[import-not-found,no-redef]
24
+ import remote_ops_common # type: ignore[import-not-found,no-redef]
21
25
  import remote_ops_launchd # type: ignore[import-not-found,no-redef]
22
26
  import remote_ops_prepare # type: ignore[import-not-found,no-redef]
23
27
  import remote_ops_service # type: ignore[import-not-found,no-redef]
@@ -26,10 +30,10 @@ except ImportError: # run as a bare file from this directory
26
30
  RELEASE_WAIT_S = 30.0
27
31
 
28
32
 
29
- def _purgeable(p: remote_ops.RemoveParams, preparation: list[str]) -> list[list[object]]:
33
+ def _purgeable(p: remote_ops_common.RemoveParams, preparation: list[str]) -> list[list[object]]:
30
34
  """[path, bytes, links] for every file in the deployment directory and the model files named."""
31
- found = [remote_ops._expand(f) for f in p.get("purge_files") or []] + preparation
32
- for root, _, names in os.walk(remote_ops._expand(p["deploy_dir"])):
35
+ found = [remote_ops_common.expand(f) for f in p.get("purge_files") or []] + preparation
36
+ for root, _, names in os.walk(remote_ops_common.expand(p["deploy_dir"])):
33
37
  found += [os.path.join(root, n) for n in names]
34
38
  stats = [(f, os.lstat(f)) for f in sorted(set(found)) if os.path.lexists(f)]
35
39
  return [[f, st.st_size, st.st_nlink] for f, st in stats if not os.path.isdir(f)]
@@ -66,7 +70,7 @@ def _delete(path: str, remove: Callable[[str], None] = os.remove) -> None:
66
70
  time.sleep(0.25)
67
71
 
68
72
 
69
- def act_remove(p: remote_ops.RemoveParams) -> None:
73
+ def act_remove(p: remote_ops_common.RemoveParams) -> None:
70
74
  """Stop and delete the service and config files, and the slice once no unit uses it; logs,
71
75
  weights and engines stay. ``dry_run`` lists a purge; ``purge`` deletes approved files."""
72
76
  purging = p.get("dry_run") or p.get("purge")
@@ -77,48 +81,52 @@ def act_remove(p: remote_ops.RemoveParams) -> None:
77
81
  _remove(p, preparation)
78
82
 
79
83
 
80
- def _remove(p: remote_ops.RemoveParams, preparation: list[str]) -> None:
84
+ def _remove(p: remote_ops_common.RemoveParams, preparation: list[str]) -> None:
81
85
  listed = _purgeable(p, preparation) if p.get("dry_run") or p.get("purge") else []
82
86
  if p.get("dry_run"):
83
- remote_ops.emit("result", files=listed, bytes=sum(int(str(f[1])) for f in listed))
87
+ remote_ops_common.emit("result", files=listed, bytes=sum(int(str(f[1])) for f in listed))
84
88
  return
85
- paths = remote_ops._paths(p)
89
+ paths = remote_ops_common.paths(p)
86
90
  systemd = p["service_kind"] == "systemd-user"
87
91
  theirs = systemd and remote_ops_service.unit_runs_elsewhere(paths)
88
92
  if theirs: # a same-named unit of another install: its service and file stay
89
- remote_ops.emit("log", message=f"kept {p['service']}.service: it runs another deployment")
93
+ remote_ops_common.emit(
94
+ "log", message=f"kept {p['service']}.service: it runs another deployment"
95
+ )
90
96
  else:
91
- remote_ops.act_stop(p)
97
+ remote_ops_service.act_stop(p)
92
98
  if p["service_kind"] == "launchd-user":
93
99
  plist, _ = remote_ops_launchd.identity(p["deploy_dir"])
94
100
  if plist.exists():
95
101
  plist.unlink()
96
102
  if systemd and not theirs and os.path.exists(paths["unit"]):
97
- remote_ops._systemctl("disable", p["service"] + ".service")
103
+ remote_ops_common.systemctl("disable", p["service"] + ".service")
98
104
  part = "".join(
99
- ln[6:] for ln in remote_ops._read(paths["unit"]).splitlines() if ln[:6] == "Slice="
105
+ ln[6:]
106
+ for ln in remote_ops_common.read_text(paths["unit"]).splitlines()
107
+ if ln[:6] == "Slice="
100
108
  )
101
109
  os.remove(paths["unit"])
102
110
  units = os.path.dirname(paths["unit"])
103
111
  rest = [
104
- remote_ops._read(os.path.join(units, n))
112
+ remote_ops_common.read_text(os.path.join(units, n))
105
113
  for n in os.listdir(units)
106
114
  if n.endswith(".service")
107
115
  ]
108
116
  suite = os.path.join(units, part)
109
117
  if part and os.path.isfile(suite) and not any(f"Slice={part}\n" in t for t in rest):
110
- if "Description=localmodels suite" in remote_ops._read(
118
+ if "Description=localmodels suite" in remote_ops_common.read_text(
111
119
  suite
112
120
  ): # the slice _write_slice wrote
113
121
  os.remove(suite)
114
- remote_ops._systemctl("daemon-reload")
122
+ remote_ops_common.systemctl("daemon-reload")
115
123
  for path in [
116
124
  *(paths[k] for k in ("script", "pid", "spec", "key")),
117
125
  paths["pid"] + ".identity.json",
118
126
  *p.get("config_files", []),
119
127
  ]:
120
- if os.path.exists(remote_ops._expand(path)):
121
- _delete(remote_ops._expand(path))
128
+ if os.path.exists(remote_ops_common.expand(path)):
129
+ _delete(remote_ops_common.expand(path))
122
130
  _delete_prompt_caches(paths["root"])
123
131
  approved = set(p.get("purge") or []) & {str(f[0]) for f in listed}
124
132
  for path in approved:
@@ -128,4 +136,4 @@ def _remove(p: remote_ops.RemoveParams, preparation: list[str]) -> None:
128
136
  if not os.listdir(root):
129
137
  _delete(root, os.rmdir)
130
138
  kept = [paths["log"]] if os.path.exists(paths["log"]) else []
131
- remote_ops.emit("result", removed=True, purged=len(approved), kept=kept)
139
+ remote_ops_common.emit("result", removed=True, purged=len(approved), kept=kept)