@simplexai/localmodels-darwin-x64 0.1.0-dev.60 → 0.1.0-dev.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +73 -60
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +5 -3
  5. package/modules/localmodels/auth_proxy.py +185 -19
  6. package/modules/localmodels/catalog.json +363 -0
  7. package/modules/localmodels/catalog.py +1 -1
  8. package/modules/localmodels/catalog_add.py +5 -5
  9. package/modules/localmodels/catalog_license.py +2 -0
  10. package/modules/localmodels/catalog_recipes.py +2 -0
  11. package/modules/localmodels/cli_parser.py +6 -2
  12. package/modules/localmodels/context_policy.py +40 -4
  13. package/modules/localmodels/debug_mode.py +13 -0
  14. package/modules/localmodels/debug_stub_server.py +156 -1
  15. package/modules/localmodels/deploy.py +11 -2
  16. package/modules/localmodels/download-mirrors.json +12 -0
  17. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  18. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  19. package/modules/localmodels/gateway_app_bifrost.py +14 -14
  20. package/modules/localmodels/gateway_bifrost.py +4 -1
  21. package/modules/localmodels/gateway_cli.py +14 -80
  22. package/modules/localmodels/gateway_server.py +88 -16
  23. package/modules/localmodels/gpu_specs.py +35 -1
  24. package/modules/localmodels/harness.py +1 -2
  25. package/modules/localmodels/hf_repo.py +12 -4
  26. package/modules/localmodels/install.py +4 -4
  27. package/modules/localmodels/library_serve.py +69 -13
  28. package/modules/localmodels/npm_transport.py +4 -58
  29. package/modules/localmodels/recommend_cli.py +2 -1
  30. package/modules/localmodels/remote_ops.py +120 -713
  31. package/modules/localmodels/remote_ops_common.py +729 -0
  32. package/modules/localmodels/remote_ops_download.py +397 -381
  33. package/modules/localmodels/remote_ops_mirrors.py +26 -65
  34. package/modules/localmodels/remote_ops_prepare.py +43 -35
  35. package/modules/localmodels/remote_ops_ranges.py +98 -62
  36. package/modules/localmodels/remote_ops_remove.py +30 -22
  37. package/modules/localmodels/remote_ops_service.py +102 -95
  38. package/modules/localmodels/remote_ops_verify.py +94 -63
  39. package/modules/localmodels/runtime_cli.py +15 -5
  40. package/modules/localmodels/runtime_io.py +54 -1
  41. package/modules/localmodels/speech-sv.txt +93 -0
  42. package/modules/localmodels/speech_admission.py +437 -0
  43. package/modules/localmodels/speech_catalog.py +170 -0
  44. package/modules/localmodels/speech_cli.py +273 -0
  45. package/modules/localmodels/speech_jobs.py +772 -0
  46. package/modules/localmodels/speech_model.py +404 -0
  47. package/modules/localmodels/speech_serve.py +287 -0
  48. package/modules/localmodels/speech_server.py +837 -0
  49. package/modules/localmodels/speech_state.py +697 -0
  50. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  51. package/modules/localmodels/speech_workers.py +783 -0
  52. package/modules/localmodels/stack.py +0 -33
  53. package/modules/localmodels/stack_auto.py +5 -3
  54. package/modules/localmodels/stack_aux_gpu.py +45 -4
  55. package/modules/localmodels/stack_capacity.py +77 -8
  56. package/modules/localmodels/stack_cli.py +16 -1
  57. package/modules/localmodels/stack_compose.py +1 -1
  58. package/modules/localmodels/stack_down.py +24 -1
  59. package/modules/localmodels/stack_hardware.py +57 -88
  60. package/modules/localmodels/stack_hardware_text.py +4 -59
  61. package/modules/localmodels/stack_memory.py +13 -3
  62. package/modules/localmodels/stack_suite.py +9 -10
  63. package/modules/localmodels/stack_summary.py +4 -4
  64. package/modules/localmodels/stack_view_llm.py +1 -1
  65. package/modules/localmodels/transport.py +3 -2
  66. package/modules/localmodels/tui_views.py +2 -2
  67. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
  68. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +70 -57
  69. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
  70. package/package.json +1 -1
  71. package/tool.json +1 -1
  72. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
  73. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
  74. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -2,9 +2,8 @@
2
2
  """remote_ops ``install``, ``start``, ``stop`` and ``status`` actions: service files and lifecycle.
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
@@ -26,24 +25,24 @@ try:
26
25
  from localmodels import (
27
26
  process_identity,
28
27
  process_identity_darwin,
29
- remote_ops,
28
+ remote_ops_common,
30
29
  remote_ops_launchd,
31
30
  )
32
31
  except ImportError: # run as a bare file from this directory
33
32
  import process_identity # type: ignore[import-not-found,no-redef]
34
33
  import process_identity_darwin # type: ignore[import-not-found,no-redef]
35
- import remote_ops # type: ignore[import-not-found,no-redef]
34
+ import remote_ops_common # type: ignore[import-not-found,no-redef]
36
35
  import remote_ops_launchd # type: ignore[import-not-found,no-redef]
37
36
 
38
37
 
39
38
  def _write_slice(name: str, limits: dict[str, str]) -> None:
40
39
  """The suite's shared cgroup: one memory ceiling and no swap for every unit inside it."""
41
- path = remote_ops._expand("~/.config/systemd/user/" + name)
40
+ path = remote_ops_common.expand("~/.config/systemd/user/" + name)
42
41
  body = "[Unit]\nDescription=localmodels suite\n\n[Slice]\n" + "".join(
43
42
  f"{k}={v}\n" for k, v in sorted(limits.items())
44
43
  )
45
44
  os.makedirs(os.path.dirname(path), exist_ok=True)
46
- remote_ops._write(path, body)
45
+ remote_ops_common.write_text(path, body)
47
46
 
48
47
 
49
48
  def _render_script(argv: list[str], env: dict[str, str]) -> str:
@@ -52,13 +51,13 @@ def _render_script(argv: list[str], env: dict[str, str]) -> str:
52
51
  if sys.platform == "win32":
53
52
  return _render_cmd(argv, env)
54
53
  env_lines = "".join(
55
- f'export {k}="$(cat {shlex.quote(remote_ops._home(v[6:]))})"\n'
54
+ f'export {k}="$(cat {shlex.quote(remote_ops_common.home(v[6:]))})"\n'
56
55
  if v.startswith("@file:")
57
- else f"export {k}={shlex.quote(remote_ops._home(v))}\n"
56
+ else f"export {k}={shlex.quote(remote_ops_common.home(v))}\n"
58
57
  for k, v in sorted(env.items())
59
58
  )
60
59
  return "#!/bin/sh\n# Generated by localmodels; edit the deployment plan instead.\n{}exec {}\n".format(
61
- env_lines, " ".join(shlex.quote(remote_ops._home(a)) for a in argv)
60
+ env_lines, " ".join(shlex.quote(remote_ops_common.home(a)) for a in argv)
62
61
  )
63
62
 
64
63
 
@@ -66,11 +65,11 @@ def _render_cmd(argv: list[str], env: dict[str, str]) -> str:
66
65
  """Windows: the same launch as a .cmd file, for reading and for running by hand. ``start``
67
66
  launches ``argv`` itself (``launch_environment``) so the recorded PID is the server's."""
68
67
  lines = [
69
- f'set /p {k}=<"{remote_ops._home(v[6:])}"' if v.startswith("@file:") else
70
- f'set "{k}={remote_ops._home(v)}"'
68
+ f'set /p {k}=<"{remote_ops_common.home(v[6:])}"' if v.startswith("@file:") else
69
+ f'set "{k}={remote_ops_common.home(v)}"'
71
70
  for k, v in sorted(env.items())
72
71
  ] # fmt: skip
73
- command = subprocess.list2cmdline([remote_ops._home(a) for a in argv])
72
+ command = subprocess.list2cmdline([remote_ops_common.home(a) for a in argv])
74
73
  # "\n" only: text mode writes CRLF on Windows and reads it back as "\n".
75
74
  head = "@echo off\nrem Generated by localmodels; edit the deployment plan instead.\n"
76
75
  return head + "".join(line + "\n" for line in [*lines, command])
@@ -81,15 +80,15 @@ def launch_environment(env: dict[str, str]) -> dict[str, str]:
81
80
  merged = dict(os.environ)
82
81
  for key, value in env.items():
83
82
  if value.startswith("@file:"):
84
- merged[key] = remote_ops._read(remote_ops._home(value[6:])).strip()
83
+ merged[key] = remote_ops_common.read_text(remote_ops_common.home(value[6:])).strip()
85
84
  else:
86
- merged[key] = remote_ops._home(value)
85
+ merged[key] = remote_ops_common.home(value)
87
86
  return merged
88
87
 
89
88
 
90
89
  def _start_windows(paths: dict[str, str]) -> None:
91
- record = json.loads(remote_ops._read(paths["spec"]))["service"]
92
- argv = [remote_ops._home(a) for a in record["argv"]]
90
+ record = json.loads(remote_ops_common.read_text(paths["spec"]))["service"]
91
+ argv = [remote_ops_common.home(a) for a in record["argv"]]
93
92
  env = launch_environment(record["env"])
94
93
  base = process_identity.venv_base(argv[0])
95
94
  if base is not None: # skip the venv redirector: its child, not it, would listen
@@ -109,15 +108,15 @@ def _start_windows(paths: dict[str, str]) -> None:
109
108
 
110
109
 
111
110
  def _previous_install(
112
- p: remote_ops.ServiceParams, paths: dict[str, str]
113
- ) -> remote_ops.InstallParams:
111
+ p: remote_ops_common.ServiceParams, paths: dict[str, str]
112
+ ) -> remote_ops_common.InstallParams:
114
113
  try:
115
- record = json.loads(remote_ops._read(paths["spec"]))
114
+ record = json.loads(remote_ops_common.read_text(paths["spec"]))
116
115
  service = record["service"]
117
116
  if service["name"] != p["service"] or service["kind"] != p["service_kind"]:
118
117
  raise ValueError("service identity")
119
118
  if (
120
- Path(remote_ops._expand(service["deploy_dir"])).resolve()
119
+ Path(remote_ops_common.expand(service["deploy_dir"])).resolve()
121
120
  != Path(paths["root"]).resolve()
122
121
  ):
123
122
  raise ValueError("deployment directory")
@@ -130,14 +129,14 @@ def _previous_install(
130
129
  raise ValueError("service environment")
131
130
  if type(port) is not int or not 0 < port < 65536:
132
131
  raise ValueError("service port")
133
- if remote_ops._read(paths["script"]) != _render_script(argv, env):
132
+ if remote_ops_common.read_text(paths["script"]) != _render_script(argv, env):
134
133
  raise ValueError("service script")
135
134
  except (OSError, ValueError, KeyError, TypeError) as exc:
136
135
  raise RuntimeError(
137
136
  "cannot confirm who owns the existing deployment; config left unchanged"
138
137
  ) from exc
139
138
  return cast(
140
- "remote_ops.InstallParams",
139
+ "remote_ops_common.InstallParams",
141
140
  {**p, "argv": cast("list[str]", argv), "env": cast("dict[str, str]", env), "port": port},
142
141
  )
143
142
 
@@ -172,7 +171,7 @@ def _process_state(pid: int) -> str | None:
172
171
 
173
172
  def command_matches(pid: int, argv: list[str]) -> bool:
174
173
  """Prove the expected executable and arguments without retaining the process command."""
175
- expected = [remote_ops._home(arg) for arg in argv]
174
+ expected = [remote_ops_common.home(arg) for arg in argv]
176
175
  return process_identity.command_matches(pid, expected)
177
176
 
178
177
 
@@ -218,7 +217,7 @@ def _windows_listeners(port: int, *, settle: bool) -> set[int] | None:
218
217
 
219
218
  def _require_ports(ports: set[int], pids: list[int]) -> None:
220
219
  for port in ports:
221
- if remote_ops.receipts():
220
+ if remote_ops_common.receipts():
222
221
  owners = (
223
222
  _windows_listeners(port, settle=not pids)
224
223
  if sys.platform == "win32"
@@ -246,7 +245,7 @@ def _stop_owned_group(pid: int, argv: list[str]) -> None:
246
245
  saved = process_identity.inspect(pid)
247
246
  if saved is None:
248
247
  return
249
- if not process_identity.windows_stop_tree(pid, saved, remote_ops.STOP_GRACE_S):
248
+ if not process_identity.windows_stop_tree(pid, saved, remote_ops_common.STOP_GRACE_S):
250
249
  raise RuntimeError("failed to stop the service process; config left unchanged")
251
250
  return
252
251
  for sig in (signal.SIGTERM, signal.SIGKILL):
@@ -261,7 +260,7 @@ def _stop_owned_group(pid: int, argv: list[str]) -> None:
261
260
  os.killpg(pid, sig)
262
261
  except ProcessLookupError:
263
262
  pass
264
- deadline = time.monotonic() + remote_ops.STOP_GRACE_S
263
+ deadline = time.monotonic() + remote_ops_common.STOP_GRACE_S
265
264
  while _group_members(pid) and time.monotonic() < deadline:
266
265
  time.sleep(0.2)
267
266
  if _group_members(pid):
@@ -269,7 +268,7 @@ def _stop_owned_group(pid: int, argv: list[str]) -> None:
269
268
 
270
269
 
271
270
  def _unit_property(unit: str, prop: str) -> str:
272
- code, value = remote_ops._systemctl("show", "-p", prop, "--value", unit)
271
+ code, value = remote_ops_common.systemctl("show", "-p", prop, "--value", unit)
273
272
  if code:
274
273
  raise RuntimeError("cannot confirm who owns the systemd service; config left unchanged")
275
274
  return value
@@ -289,13 +288,15 @@ def _require_own_fragment(unit: str, paths: dict[str, str]) -> None:
289
288
  def _unit_not_loaded(unit: str) -> bool:
290
289
  """True when systemd neither knows ``unit`` nor tracks any process or cgroup under it."""
291
290
  return (
292
- remote_ops._systemctl("show", "-p", "LoadState", "--value", unit) == (0, "not-found")
293
- and remote_ops._systemctl("show", "-p", "MainPID", "--value", unit) == (0, "0")
294
- and remote_ops._systemctl("show", "-p", "ControlGroup", "--value", unit) == (0, "")
291
+ remote_ops_common.systemctl("show", "-p", "LoadState", "--value", unit) == (0, "not-found")
292
+ and remote_ops_common.systemctl("show", "-p", "MainPID", "--value", unit) == (0, "0")
293
+ and remote_ops_common.systemctl("show", "-p", "ControlGroup", "--value", unit) == (0, "")
295
294
  )
296
295
 
297
296
 
298
- def _stop_owned_unit(p: remote_ops.InstallParams, paths: dict[str, str], ports: set[int]) -> None:
297
+ def _stop_owned_unit(
298
+ p: remote_ops_common.InstallParams, paths: dict[str, str], ports: set[int]
299
+ ) -> None:
299
300
  unit = p["service"] + ".service"
300
301
  fragment = _unit_property(unit, "FragmentPath")
301
302
  command = _unit_property(unit, "ExecStart")
@@ -314,8 +315,8 @@ def _stop_owned_unit(p: remote_ops.InstallParams, paths: dict[str, str], ports:
314
315
  if pid <= 0 or pid not in pids or not command_matches(pid, p["argv"]):
315
316
  raise RuntimeError("the systemd process has another owner; config left unchanged")
316
317
  _require_ports(ports, pids)
317
- remote_ops._systemctl_ok("stop", unit)
318
- state = remote_ops._systemctl("is-active", unit)[1]
318
+ remote_ops_common.systemctl_ok("stop", unit)
319
+ state = remote_ops_common.systemctl("is-active", unit)[1]
319
320
  if (
320
321
  state not in ("inactive", "failed")
321
322
  or _unit_property(unit, "MainPID") != "0"
@@ -326,7 +327,7 @@ def _stop_owned_unit(p: remote_ops.InstallParams, paths: dict[str, str], ports:
326
327
 
327
328
  def _recorded_service(paths: dict[str, str]) -> str | None:
328
329
  try:
329
- name = json.loads(remote_ops._read(paths["spec"]))["service"]["name"]
330
+ name = json.loads(remote_ops_common.read_text(paths["spec"]))["service"]["name"]
330
331
  except (OSError, ValueError, KeyError, TypeError):
331
332
  return None
332
333
  return name if isinstance(name, str) else None
@@ -341,25 +342,25 @@ def unit_runs_elsewhere(paths: dict[str, str]) -> bool:
341
342
  if not os.path.exists(paths["unit"]):
342
343
  return False
343
344
  try:
344
- text = remote_ops._read(paths["unit"])
345
+ text = remote_ops_common.read_text(paths["unit"])
345
346
  except OSError:
346
347
  return False
347
348
  return f"\nExecStart={paths['script']}\n" not in text
348
349
 
349
350
 
350
- def _retire_renamed_unit(p: remote_ops.InstallParams, paths: dict[str, str]) -> None:
351
+ def _retire_renamed_unit(p: remote_ops_common.InstallParams, paths: dict[str, str]) -> None:
351
352
  """A unit this deployment directory ran under an earlier name (before unit names carried
352
353
  the install root's tag) is stopped, disabled and deleted, so it neither holds the port nor
353
354
  starts again at login. Only a unit whose file runs this directory's run.sh is touched."""
354
355
  name = _recorded_service(paths)
355
356
  if not name or name == p["service"] or not name.startswith("localmodels-"):
356
357
  return
357
- old: remote_ops.InstallParams = {**p, "service": name}
358
- old_paths = remote_ops._paths(old)
358
+ old: remote_ops_common.InstallParams = {**p, "service": name}
359
+ old_paths = remote_ops_common.paths(old)
359
360
  unit = name + ".service"
360
361
  if not os.path.isfile(old_paths["unit"]) or unit_runs_elsewhere(old_paths):
361
362
  return # never installed as a unit, already gone, or another deployment's now
362
- state = remote_ops._systemctl("is-active", unit)[1]
363
+ state = remote_ops_common.systemctl("is-active", unit)[1]
363
364
  if state == "active":
364
365
  previous = _previous_install(old, old_paths)
365
366
  _stop_owned_unit(previous, old_paths, {p["port"], previous["port"]})
@@ -367,20 +368,22 @@ def _retire_renamed_unit(p: remote_ops.InstallParams, paths: dict[str, str]) ->
367
368
  _require_own_fragment(unit, old_paths)
368
369
  else:
369
370
  raise RuntimeError("the earlier systemd service state is uncertain; config left unchanged")
370
- remote_ops._systemctl("disable", unit)
371
+ remote_ops_common.systemctl("disable", unit)
371
372
  Path(old_paths["unit"]).unlink(missing_ok=True)
372
- remote_ops._systemctl_ok("daemon-reload")
373
- remote_ops.emit("log", message=f"retired the earlier unit {unit} of this deployment")
373
+ remote_ops_common.systemctl_ok("daemon-reload")
374
+ remote_ops_common.emit("log", message=f"retired the earlier unit {unit} of this deployment")
374
375
 
375
376
 
376
- def _prepare_install(p: remote_ops.InstallParams, paths: dict[str, str]) -> None:
377
+ def _prepare_install(p: remote_ops_common.InstallParams, paths: dict[str, str]) -> None:
377
378
  systemd = p["service_kind"] == "systemd-user"
378
379
  if systemd:
379
380
  _retire_renamed_unit(p, paths)
380
381
  if unit_runs_elsewhere(paths):
381
382
  raise RuntimeError(f"{_FOREIGN_UNIT}; config left unchanged")
382
- state = remote_ops._systemctl("is-active", p["service"] + ".service")[1] if systemd else ""
383
- pid = None if systemd else remote_ops._pid_alive(paths["pid"])
383
+ state = (
384
+ remote_ops_common.systemctl("is-active", p["service"] + ".service")[1] if systemd else ""
385
+ )
386
+ pid = None if systemd else remote_ops_common.pid_alive(paths["pid"])
384
387
  if pid is not None:
385
388
  state = _process_state(pid) or ""
386
389
  if not state or (state == "Z" and not _group_members(pid)):
@@ -407,11 +410,11 @@ def _prepare_install(p: remote_ops.InstallParams, paths: dict[str, str]) -> None
407
410
  _require_ports({p["port"]}, [])
408
411
 
409
412
 
410
- def act_install(p: remote_ops.InstallParams) -> None:
413
+ def act_install(p: remote_ops_common.InstallParams) -> None:
411
414
  if p["service_kind"] == "launchd-user":
412
415
  remote_ops_launchd.preflight(p["deploy_dir"])
413
- paths = remote_ops._paths(p)
414
- if remote_ops.receipts() and p["service_kind"] == "nohup":
416
+ paths = remote_ops_common.paths(p)
417
+ if remote_ops_common.receipts() and p["service_kind"] == "nohup":
415
418
  process_identity.require_owned(paths["pid"])
416
419
  if p["service_kind"] != "launchd-user":
417
420
  _prepare_install(p, paths)
@@ -420,12 +423,12 @@ def act_install(p: remote_ops.InstallParams) -> None:
420
423
  Path(paths["pid"]).unlink(missing_ok=True)
421
424
  fd = os.open(paths["key"], os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
422
425
  with os.fdopen(fd, "w", encoding="utf-8") as f:
423
- remote_ops._narrow(f.fileno(), 0o077) # 0o600 above applies only to a new file
426
+ remote_ops_common.narrow(f.fileno(), 0o077) # 0o600 above applies only to a new file
424
427
  f.write(p["api_key"] + "\n")
425
428
  for path, text in (p.get("config_files") or {}).items():
426
- os.makedirs(os.path.dirname(remote_ops._expand(path)), exist_ok=True)
427
- remote_ops._write(remote_ops._expand(path), text)
428
- remote_ops._write(paths["script"], _render_script(p["argv"], p["env"]))
429
+ os.makedirs(os.path.dirname(remote_ops_common.expand(path)), exist_ok=True)
430
+ remote_ops_common.write_text(remote_ops_common.expand(path), text)
431
+ remote_ops_common.write_text(paths["script"], _render_script(p["argv"], p["env"]))
429
432
  os.chmod(paths["script"], 0o700)
430
433
  if p["service_kind"] == "launchd-user":
431
434
  remote_ops_launchd.install(p["deploy_dir"])
@@ -444,26 +447,26 @@ def act_install(p: remote_ops.InstallParams) -> None:
444
447
  "{}StandardOutput=append:{}\nStandardError=append:{}\n\n"
445
448
  "[Install]\nWantedBy=default.target\n"
446
449
  ).format(p["service"], paths["script"], limits, paths["log"], paths["log"])
447
- remote_ops._write(paths["unit"], unit)
450
+ remote_ops_common.write_text(paths["unit"], unit)
448
451
  # set-property drop-ins outlive a reinstall and outrank the planned limits (ST5).
449
452
  runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
450
- for root in (remote_ops._expand("~/.config"), runtime):
453
+ for root in (remote_ops_common.expand("~/.config"), runtime):
451
454
  shutil.rmtree(
452
455
  f"{root}/systemd/user.control/{p['service']}.service.d", ignore_errors=True
453
456
  )
454
- remote_ops._systemctl_ok("daemon-reload")
457
+ remote_ops_common.systemctl_ok("daemon-reload")
455
458
  _require_own_fragment(p["service"] + ".service", paths)
456
459
  if p.get("autostart", True):
457
- remote_ops._systemctl_ok("enable", p["service"] + ".service")
460
+ remote_ops_common.systemctl_ok("enable", p["service"] + ".service")
458
461
  keys = ("script", "log", "unit") if p["service_kind"] == "systemd-user" else ("script", "log")
459
- remote_ops.emit("result", **{k: paths[k] for k in keys})
462
+ remote_ops_common.emit("result", **{k: paths[k] for k in keys})
460
463
 
461
464
 
462
465
  def _has_service_record(paths: dict[str, str]) -> bool:
463
466
  if not os.path.isfile(paths["spec"]):
464
467
  return False
465
468
  try:
466
- record = json.loads(remote_ops._read(paths["spec"]))
469
+ record = json.loads(remote_ops_common.read_text(paths["spec"]))
467
470
  except (OSError, ValueError):
468
471
  return True # unreadable or malformed spec still fails closed
469
472
  return not (isinstance(record, dict) and not record)
@@ -472,15 +475,15 @@ def _has_service_record(paths: dict[str, str]) -> bool:
472
475
  def _foreign_systemd_unit(unit: str, paths: dict[str, str]) -> bool:
473
476
  if unit_runs_elsewhere(paths):
474
477
  return True
475
- code, fragment = remote_ops._systemctl("show", "-p", "FragmentPath", "--value", unit)
478
+ code, fragment = remote_ops_common.systemctl("show", "-p", "FragmentPath", "--value", unit)
476
479
  return bool(
477
480
  code == 0 and fragment and Path(fragment).resolve() != Path(paths["unit"]).resolve()
478
481
  )
479
482
 
480
483
 
481
- def act_start(p: remote_ops.ServiceParams) -> None:
482
- paths, unit = remote_ops._paths(p), p["service"] + ".service"
483
- if remote_ops.receipts() and p["service_kind"] == "nohup":
484
+ def act_start(p: remote_ops_common.ServiceParams) -> None:
485
+ paths, unit = remote_ops_common.paths(p), p["service"] + ".service"
486
+ if remote_ops_common.receipts() and p["service_kind"] == "nohup":
484
487
  process_identity.require_owned(paths["pid"])
485
488
  systemd = p["service_kind"] == "systemd-user"
486
489
  if systemd and unit_runs_elsewhere(paths):
@@ -488,9 +491,9 @@ def act_start(p: remote_ops.ServiceParams) -> None:
488
491
  running = (
489
492
  remote_ops_launchd.status(p["deploy_dir"])[0] == "active"
490
493
  if p["service_kind"] == "launchd-user"
491
- else remote_ops._systemctl("is-active", unit)[1] == "active"
494
+ else remote_ops_common.systemctl("is-active", unit)[1] == "active"
492
495
  if systemd
493
- else remote_ops._pid_alive(paths["pid"])
496
+ else remote_ops_common.pid_alive(paths["pid"])
494
497
  )
495
498
  if (
496
499
  not systemd
@@ -501,7 +504,7 @@ def act_start(p: remote_ops.ServiceParams) -> None:
501
504
  and not command_matches(int(running), _previous_install(p, paths)["argv"])
502
505
  ):
503
506
  raise RuntimeError("the existing PID does not belong to this deployment; not started")
504
- if not running and remote_ops._port_owner(p["port"]):
507
+ if not running and remote_ops_common.port_owner(p["port"]):
505
508
  raise RuntimeError(f"port {p['port']} is held by another process")
506
509
  if p["service_kind"] == "launchd-user":
507
510
  remote_ops_launchd.start(p["deploy_dir"])
@@ -509,7 +512,7 @@ def act_start(p: remote_ops.ServiceParams) -> None:
509
512
  _require_own_fragment(unit, paths)
510
513
  if running and not os.path.isfile(paths["unit"]):
511
514
  raise RuntimeError(f"{_FOREIGN_UNIT}; not started")
512
- remote_ops._systemctl_ok("start", unit)
515
+ remote_ops_common.systemctl_ok("start", unit)
513
516
  elif not running and sys.platform == "win32":
514
517
  _start_windows(paths)
515
518
  elif not running:
@@ -523,12 +526,12 @@ def act_start(p: remote_ops.ServiceParams) -> None:
523
526
  proc.wait(timeout=10)
524
527
  raise
525
528
  else:
526
- remote_ops._write(paths["pid"], str(proc.pid))
527
- remote_ops.emit("result", started=True)
529
+ remote_ops_common.write_text(paths["pid"], str(proc.pid))
530
+ remote_ops_common.emit("result", started=True)
528
531
 
529
532
 
530
- def _stop_nohup_verified(p: remote_ops.ServiceParams, paths: dict[str, str]) -> None:
531
- pid = remote_ops._pid_alive(paths["pid"])
533
+ def _stop_nohup_verified(p: remote_ops_common.ServiceParams, paths: dict[str, str]) -> None:
534
+ pid = remote_ops_common.pid_alive(paths["pid"])
532
535
  state = _process_state(pid) if pid is not None else None
533
536
  if pid is not None and state and not (state == "Z" and not _group_members(pid)):
534
537
  _stop_owned_group(pid, _previous_install(p, paths)["argv"])
@@ -540,8 +543,8 @@ def _stop_nohup_signals(paths: dict[str, str]) -> None:
540
543
  if sys.platform == "darwin":
541
544
  process_identity.require_owned(paths["pid"])
542
545
  pid, deadline = (
543
- remote_ops._pid_alive(paths["pid"]),
544
- time.monotonic() + remote_ops.STOP_GRACE_S,
546
+ remote_ops_common.pid_alive(paths["pid"]),
547
+ time.monotonic() + remote_ops_common.STOP_GRACE_S,
545
548
  )
546
549
  if pid is not None:
547
550
  try:
@@ -549,22 +552,24 @@ def _stop_nohup_signals(paths: dict[str, str]) -> None:
549
552
  except ProcessLookupError: # it exited after the check: stopped, as wanted
550
553
  pid = None
551
554
  while (
552
- pid is not None and remote_ops._pid_alive(paths["pid"]) and time.monotonic() < deadline
555
+ pid is not None
556
+ and remote_ops_common.pid_alive(paths["pid"])
557
+ and time.monotonic() < deadline
553
558
  ):
554
559
  time.sleep(0.2)
555
- if remote_ops._pid_alive(paths["pid"]):
560
+ if remote_ops_common.pid_alive(paths["pid"]):
556
561
  raise RuntimeError("the service process is still running after SIGKILL")
557
562
 
558
563
 
559
- def act_stop(p: remote_ops.ServiceParams) -> None:
560
- paths = remote_ops._paths(p)
561
- if remote_ops.receipts() and p["service_kind"] == "nohup":
564
+ def act_stop(p: remote_ops_common.ServiceParams) -> None:
565
+ paths = remote_ops_common.paths(p)
566
+ if remote_ops_common.receipts() and p["service_kind"] == "nohup":
562
567
  process_identity.require_owned(paths["pid"])
563
568
  if p["service_kind"] == "launchd-user":
564
569
  remote_ops_launchd.stop(p["deploy_dir"])
565
570
  elif sys.platform == "win32":
566
571
  try:
567
- process_identity.stop(paths["pid"], remote_ops.STOP_GRACE_S)
572
+ process_identity.stop(paths["pid"], remote_ops_common.STOP_GRACE_S)
568
573
  except RuntimeError as exc:
569
574
  raise RuntimeError(f"the service process is still running: {exc}") from None
570
575
  elif p["service_kind"] == "systemd-user":
@@ -574,13 +579,13 @@ def act_stop(p: remote_ops.ServiceParams) -> None:
574
579
  _require_own_fragment(unit, paths)
575
580
  if not os.path.exists(paths["unit"]) and _unit_not_loaded(unit):
576
581
  pass
577
- elif remote_ops._systemctl("stop", unit)[0]:
582
+ elif remote_ops_common.systemctl("stop", unit)[0]:
578
583
  raise RuntimeError("systemctl could not stop the service")
579
584
  elif sys.platform.startswith("linux") and _has_service_record(paths):
580
585
  _stop_nohup_verified(p, paths)
581
586
  else:
582
587
  _stop_nohup_signals(paths)
583
- remote_ops.emit("result", stopped=True)
588
+ remote_ops_common.emit("result", stopped=True)
584
589
 
585
590
 
586
591
  def loopback_listener_inodes(port: int) -> set[str] | None:
@@ -685,10 +690,10 @@ def group_pids(pid: int) -> list[int]:
685
690
  return [pid]
686
691
 
687
692
 
688
- def _status_pids(p: remote_ops.ServiceParams, pid: int) -> list[int]:
693
+ def _status_pids(p: remote_ops_common.ServiceParams, pid: int) -> list[int]:
689
694
  if p["service_kind"] != "systemd-user":
690
695
  return [pid]
691
- code, group = remote_ops._systemctl(
696
+ code, group = remote_ops_common.systemctl(
692
697
  "show", "-p", "ControlGroup", "--value", p["service"] + ".service"
693
698
  )
694
699
  if code or not group.startswith("/") or group == "/" or ".." in group.split("/"):
@@ -702,41 +707,43 @@ def _status_pids(p: remote_ops.ServiceParams, pid: int) -> list[int]:
702
707
  return []
703
708
 
704
709
 
705
- def act_status(p: remote_ops.ServiceParams) -> None:
706
- paths = remote_ops._paths(p)
710
+ def act_status(p: remote_ops_common.ServiceParams) -> None:
711
+ paths = remote_ops_common.paths(p)
707
712
  pid = None
708
713
  if p["service_kind"] == "launchd-user":
709
714
  state, pid = remote_ops_launchd.status(p["deploy_dir"])
710
715
  elif p["service_kind"] == "systemd-user":
711
716
  unit = p["service"] + ".service"
712
717
  if _foreign_systemd_unit(unit, paths):
713
- remote_ops.emit("result", state="inactive", health=f"{_FOREIGN_UNIT}, not probed")
718
+ remote_ops_common.emit(
719
+ "result", state="inactive", health=f"{_FOREIGN_UNIT}, not probed"
720
+ )
714
721
  return
715
- _, state = remote_ops._systemctl("is-active", unit)
722
+ _, state = remote_ops_common.systemctl("is-active", unit)
716
723
  if state == "active":
717
- _, number = remote_ops._systemctl("show", "-p", "MainPID", "--value", unit)
724
+ _, number = remote_ops_common.systemctl("show", "-p", "MainPID", "--value", unit)
718
725
  pid = int(number) if number.isdigit() and int(number) > 0 else None
719
- elif remote_ops.receipts():
726
+ elif remote_ops_common.receipts():
720
727
  state, pid = process_identity.status(paths["pid"])
721
728
  else:
722
- pid = remote_ops._pid_alive(paths["pid"])
729
+ pid = remote_ops_common.pid_alive(paths["pid"])
723
730
  state = "active" if pid else "inactive"
724
731
  if state != "active" or pid is None:
725
- remote_ops.emit("result", state=state, health="not running, not probed")
732
+ remote_ops_common.emit("result", state=state, health="not running, not probed")
726
733
  return
727
734
  reason = listener_problem(p["port"], _status_pids(p, pid))
728
735
  if reason:
729
- remote_ops.emit("result", state=state, health=reason)
736
+ remote_ops_common.emit("result", state=state, health=reason)
730
737
  return
731
738
  url = f"http://127.0.0.1:{p['port']}/health"
732
739
  try:
733
740
  key = p["api_key"]
734
741
  if not key:
735
742
  try:
736
- key = remote_ops._read(paths["key"]).strip()
743
+ key = remote_ops_common.read_text(paths["key"]).strip()
737
744
  except OSError:
738
745
  pass
739
- health = remote_ops._http(url, key, timeout=3).get("status")
746
+ health = remote_ops_common.http_json(url, key, timeout=3).get("status")
740
747
  except urllib.error.HTTPError as exc:
741
748
  health = f"unreachable: HTTP {exc.code}"
742
749
  except urllib.error.URLError:
@@ -745,4 +752,4 @@ def act_status(p: remote_ops.ServiceParams) -> None:
745
752
  health = "unreachable: OSError"
746
753
  except ValueError:
747
754
  health = "unreachable: ValueError"
748
- remote_ops.emit("result", state=state, health=health)
755
+ remote_ops_common.emit("result", state=state, health=health)