envweaver 0.0.1__py3-none-any.whl

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 (115) hide show
  1. envweaver/__init__.py +34 -0
  2. envweaver/_io/__init__.py +1 -0
  3. envweaver/_io/files.py +66 -0
  4. envweaver/_io/output.py +78 -0
  5. envweaver/_io/output_lock.py +54 -0
  6. envweaver/_io/paths.py +37 -0
  7. envweaver/_io/process.py +26 -0
  8. envweaver/_io/retry.py +59 -0
  9. envweaver/_io/ssh_config.py +80 -0
  10. envweaver/_io/ssh_transport.py +61 -0
  11. envweaver/_io/storage.py +181 -0
  12. envweaver/_task_store.py +100 -0
  13. envweaver/_util.py +108 -0
  14. envweaver/agents/__init__.py +5 -0
  15. envweaver/agents/_redaction.py +23 -0
  16. envweaver/agents/adapters/__init__.py +6 -0
  17. envweaver/agents/adapters/_cli.py +428 -0
  18. envweaver/agents/adapters/_dependencies.py +123 -0
  19. envweaver/agents/adapters/_download_client.py +38 -0
  20. envweaver/agents/adapters/_download_pipe.py +59 -0
  21. envweaver/agents/adapters/_downloads.py +216 -0
  22. envweaver/agents/adapters/_model_capture.py +125 -0
  23. envweaver/agents/adapters/_npm_download.cjs +64 -0
  24. envweaver/agents/adapters/_pip_install.py +43 -0
  25. envweaver/agents/adapters/_process.py +145 -0
  26. envweaver/agents/adapters/_uv_install.py +156 -0
  27. envweaver/agents/adapters/codex/__init__.py +3 -0
  28. envweaver/agents/adapters/codex/adapter.py +127 -0
  29. envweaver/agents/adapters/codex/trajectory.py +208 -0
  30. envweaver/agents/adapters/mini_swe/__init__.py +3 -0
  31. envweaver/agents/adapters/mini_swe/adapter.py +177 -0
  32. envweaver/agents/adapters/mini_swe/runner.py +11 -0
  33. envweaver/agents/adapters/mini_swe/trajectory.py +156 -0
  34. envweaver/agents/adapters/pi/__init__.py +3 -0
  35. envweaver/agents/adapters/pi/adapter.py +162 -0
  36. envweaver/agents/adapters/pi/capture.ts +62 -0
  37. envweaver/agents/adapters/pi/trajectory.py +238 -0
  38. envweaver/agents/adapters/terminus/__init__.py +3 -0
  39. envweaver/agents/adapters/terminus/adapter.py +204 -0
  40. envweaver/agents/adapters/terminus/install.py +76 -0
  41. envweaver/agents/adapters/terminus/monkey_patches/__init__.py +14 -0
  42. envweaver/agents/adapters/terminus/monkey_patches/v0_25_0/__init__.py +1 -0
  43. envweaver/agents/adapters/terminus/monkey_patches/v0_25_0/context_recovery.py +77 -0
  44. envweaver/agents/adapters/terminus/runner.py +262 -0
  45. envweaver/agents/adapters/terminus/trajectory.py +77 -0
  46. envweaver/agents/base.py +131 -0
  47. envweaver/agents/execution.py +192 -0
  48. envweaver/agents/output.py +303 -0
  49. envweaver/agents/trajectory/LICENSE +201 -0
  50. envweaver/agents/trajectory/NOTICE +3 -0
  51. envweaver/agents/trajectory/__init__.py +132 -0
  52. envweaver/agents/trajectory/_scan.py +67 -0
  53. envweaver/agents/trajectory/atif-v1.8.schema.json +916 -0
  54. envweaver/agents/trajectory/capture.py +155 -0
  55. envweaver/cache.py +197 -0
  56. envweaver/errors.py +108 -0
  57. envweaver/evaluation/__init__.py +3 -0
  58. envweaver/evaluation/failure.py +39 -0
  59. envweaver/evaluation/runner.py +760 -0
  60. envweaver/evaluation/store.py +250 -0
  61. envweaver/management/__init__.py +1 -0
  62. envweaver/management/__main__.py +24 -0
  63. envweaver/management/_pool_files.py +260 -0
  64. envweaver/management/_ssh.py +83 -0
  65. envweaver/management/api.py +294 -0
  66. envweaver/management/deletion.py +139 -0
  67. envweaver/management/jobs.py +67 -0
  68. envweaver/management/models.py +261 -0
  69. envweaver/management/pools.py +337 -0
  70. envweaver/management/runtimes.py +213 -0
  71. envweaver/management/store.py +541 -0
  72. envweaver/management/tasks.py +203 -0
  73. envweaver/management/trajectories.py +59 -0
  74. envweaver/management/web/README.md +120 -0
  75. envweaver/management/web/index.html +173 -0
  76. envweaver/management/web/src/api/client.js +40 -0
  77. envweaver/management/web/src/components/detail-panel.js +107 -0
  78. envweaver/management/web/src/components/filters.js +78 -0
  79. envweaver/management/web/src/components/image-viewer.js +25 -0
  80. envweaver/management/web/src/components/json.js +32 -0
  81. envweaver/management/web/src/components/menu.js +37 -0
  82. envweaver/management/web/src/components/pagination.js +36 -0
  83. envweaver/management/web/src/components/selection.js +51 -0
  84. envweaver/management/web/src/components/session.js +16 -0
  85. envweaver/management/web/src/components/table-columns.js +155 -0
  86. envweaver/management/web/src/components/tags.js +191 -0
  87. envweaver/management/web/src/components/task-groups.js +120 -0
  88. envweaver/management/web/src/components/trajectory-view.js +104 -0
  89. envweaver/management/web/src/components/ui.js +143 -0
  90. envweaver/management/web/src/main.js +608 -0
  91. envweaver/management/web/src/pages/assets.js +319 -0
  92. envweaver/management/web/src/pages/trajectories.js +160 -0
  93. envweaver/management/web/src/style.css +1244 -0
  94. envweaver/models.py +141 -0
  95. envweaver/runtime/__init__.py +6 -0
  96. envweaver/runtime/_bootstrap.py +89 -0
  97. envweaver/runtime/_command.py +45 -0
  98. envweaver/runtime/_connection.py +42 -0
  99. envweaver/runtime/_python.sh +52 -0
  100. envweaver/runtime/_relay.py +83 -0
  101. envweaver/runtime/_remote.py +69 -0
  102. envweaver/runtime/_ssh.py +141 -0
  103. envweaver/runtime/_vnc.py +49 -0
  104. envweaver/runtime/base.py +83 -0
  105. envweaver/runtime/docker.py +280 -0
  106. envweaver/runtime/manager.py +386 -0
  107. envweaver/runtime/qemu.py +641 -0
  108. envweaver/task.py +375 -0
  109. envweaver/trajectory/__init__.py +5 -0
  110. envweaver/trajectory/pool.py +182 -0
  111. envweaver/trajectory/usage.py +104 -0
  112. envweaver/verifier.py +353 -0
  113. envweaver-0.0.1.dist-info/METADATA +46 -0
  114. envweaver-0.0.1.dist-info/RECORD +115 -0
  115. envweaver-0.0.1.dist-info/WHEEL +4 -0
envweaver/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """Small infrastructure primitives; pipeline policy belongs to the caller."""
2
+
3
+ from .agents import Agent, AgentOutput, CodexAgent, MiniSweAgent, PiAgent, Terminus2Agent
4
+ from .agents.trajectory import ATIF_VERSION
5
+ from .cache import DownloadCache
6
+ from .errors import AgentStopReason, ErrorType
7
+ from .evaluation import EvalConfig, eval
8
+ from .models import Instance, RuntimeRef, Task
9
+ from .runtime import Runtime
10
+ from .task import TaskPool
11
+ from .trajectory import TrajPool
12
+ from .verifier import Verifier
13
+
14
+ __all__ = [
15
+ "Agent",
16
+ "ATIF_VERSION",
17
+ "DownloadCache",
18
+ "AgentOutput",
19
+ "AgentStopReason",
20
+ "ErrorType",
21
+ "CodexAgent",
22
+ "PiAgent",
23
+ "MiniSweAgent",
24
+ "Terminus2Agent",
25
+ "EvalConfig",
26
+ "eval",
27
+ "Instance",
28
+ "RuntimeRef",
29
+ "Task",
30
+ "Runtime",
31
+ "TaskPool",
32
+ "TrajPool",
33
+ "Verifier",
34
+ ]
@@ -0,0 +1 @@
1
+ """Shared local and SSH file operations."""
envweaver/_io/files.py ADDED
@@ -0,0 +1,66 @@
1
+ import io
2
+ import os
3
+ import shutil
4
+ import tempfile
5
+ import zipfile
6
+ from pathlib import Path, PurePosixPath
7
+
8
+
9
+ def _write_file(target, source):
10
+ target.parent.mkdir(parents=True, exist_ok=True)
11
+ with tempfile.TemporaryDirectory(prefix=".envweaver-transfer-", dir=target.parent) as directory:
12
+ temporary = Path(directory) / "file"
13
+ with temporary.open("wb") as output:
14
+ shutil.copyfileobj(source, output)
15
+ if target.is_file():
16
+ temporary.chmod(target.stat().st_mode)
17
+ os.replace(temporary, target)
18
+
19
+
20
+ def pack(path):
21
+ path = Path(path).resolve(strict=True)
22
+ if path.is_file():
23
+ return "file", path.read_bytes()
24
+ buffer = io.BytesIO()
25
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
26
+ for entry in sorted(path.rglob("*")):
27
+ if entry.is_symlink():
28
+ raise ValueError(f"File transfer does not follow symlinks: {entry}")
29
+ archive.write(entry, str(entry.relative_to(path)))
30
+ return "directory", buffer.getvalue()
31
+
32
+
33
+ def unpack(kind, payload, target, *, mode=None):
34
+ target = Path(target)
35
+ permissions = []
36
+ if kind == "file":
37
+ _write_file(target, io.BytesIO(payload))
38
+ elif kind == "directory":
39
+ target.mkdir(parents=True, exist_ok=True)
40
+ with zipfile.ZipFile(io.BytesIO(payload)) as archive:
41
+ for item in archive.infolist():
42
+ relative = PurePosixPath(item.filename)
43
+ if (
44
+ relative.is_absolute()
45
+ or ".." in relative.parts
46
+ or "\\" in item.filename
47
+ or ":" in item.filename
48
+ ):
49
+ raise ValueError("Unsafe archive path")
50
+ destination = target.joinpath(*relative.parts)
51
+ if not destination.resolve().is_relative_to(target.resolve()):
52
+ raise ValueError("Archive escapes destination")
53
+ if item.is_dir():
54
+ destination.mkdir(parents=True, exist_ok=True)
55
+ else:
56
+ with archive.open(item) as source:
57
+ _write_file(destination, source)
58
+ if mode is not None:
59
+ permissions.append((destination, (item.external_attr >> 16) & 0o777))
60
+ else:
61
+ raise ValueError(f"Unknown file transfer kind: {kind}")
62
+ if mode is not None:
63
+ # Set directory modes last so read-only inputs can still be populated.
64
+ for path, permission in reversed(permissions):
65
+ path.chmod(permission)
66
+ target.chmod(mode & 0o777)
@@ -0,0 +1,78 @@
1
+ """Local working directories with incremental publication to SSH destinations."""
2
+
3
+ import base64
4
+ import shutil
5
+ import tempfile
6
+ import threading
7
+ import weakref
8
+ from pathlib import Path
9
+
10
+ from .paths import join_address, normalize_address
11
+ from .storage import _dispatch
12
+
13
+
14
+ class OutputDirectory:
15
+ def __init__(self, address, *, exist_ok=False, sentinel=None, source_lock=None):
16
+ self.address = normalize_address(address)
17
+ self._lock = threading.RLock()
18
+ self._source_lock = source_lock or threading.RLock()
19
+ self._published = {}
20
+ self._cleanup = None
21
+ if isinstance(self.address, Path):
22
+ self.path = self.address.resolve()
23
+ if sentinel and (self.path / sentinel).exists():
24
+ raise FileExistsError(self.path / sentinel)
25
+ self.path.mkdir(parents=True, exist_ok=exist_ok)
26
+ else:
27
+ created = _dispatch(
28
+ self.address,
29
+ {"action": "mkdir", "exist_ok": exist_ok, "sentinel": sentinel},
30
+ )
31
+ if not created:
32
+ raise FileExistsError(self.address)
33
+ self.path = Path(tempfile.mkdtemp(prefix="envweaver-output-"))
34
+ self._cleanup = weakref.finalize(self, shutil.rmtree, self.path, True)
35
+
36
+ def sync(self):
37
+ if isinstance(self.address, Path):
38
+ return
39
+ with self._lock:
40
+ try:
41
+ # Capture a consistent snapshot, then release the Agent state lock
42
+ # before network I/O so stop() can still meet its deadline.
43
+ updates = []
44
+ with self._source_lock:
45
+ files = sorted(
46
+ self.path.rglob("*"),
47
+ key=lambda path: (
48
+ path.name in {"result.json", "results.json"},
49
+ path.name == "trajectory.json",
50
+ str(path),
51
+ ),
52
+ )
53
+ for path in files:
54
+ if path.is_symlink():
55
+ raise ValueError("Output files must not be symbolic links")
56
+ if not path.is_file():
57
+ continue
58
+ relative = path.relative_to(self.path).as_posix()
59
+ stat = path.stat()
60
+ signature = (stat.st_mtime_ns, stat.st_size, stat.st_mode)
61
+ if self._published.get(relative) != signature:
62
+ updates.append((relative, signature, path.read_bytes(), stat.st_mode & 0o777))
63
+ # Publish referenced files before the snapshot which advertises them.
64
+ for relative, signature, body, mode in updates:
65
+ _dispatch(
66
+ join_address(self.address, relative),
67
+ {
68
+ "action": "publish",
69
+ "body": base64.b64encode(body).decode(),
70
+ "mode": mode,
71
+ },
72
+ )
73
+ self._published[relative] = signature
74
+ except BaseException as error:
75
+ # Keep recoverable local artifacts if the remote destination fails.
76
+ self._cleanup.detach()
77
+ error.add_note(f"Unsynchronized output retained at {self.path}")
78
+ raise
@@ -0,0 +1,54 @@
1
+ """A process-owned file lock; closing stdin also releases remote locks."""
2
+
3
+ import select
4
+ import subprocess
5
+ import sys
6
+ from contextlib import contextmanager
7
+ from pathlib import Path
8
+
9
+ from . import ssh_transport as _ssh_transport
10
+ from .paths import _location, normalize_address
11
+
12
+ _LOCK = """
13
+ import fcntl, sys
14
+ with open(sys.argv[1], "a") as lock:
15
+ try:
16
+ fcntl.flock(lock, fcntl.LOCK_EX | (0 if sys.argv[2] == "wait" else fcntl.LOCK_NB))
17
+ except BlockingIOError:
18
+ print("busy", flush=True)
19
+ else:
20
+ print("locked", flush=True)
21
+ sys.stdin.buffer.read()
22
+ """
23
+
24
+
25
+ @contextmanager
26
+ def output_lock(address, *, wait=False):
27
+ address = normalize_address(address)
28
+ mode = "wait" if wait else "fail"
29
+ if isinstance(address, Path):
30
+ command = [sys.executable, "-c", _LOCK, str(address), mode]
31
+ else:
32
+ host, path = _location(address)
33
+ command = _ssh_transport.command_args(host, ["python3", "-c", _LOCK, path, mode])
34
+ process = subprocess.Popen(
35
+ command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
36
+ )
37
+ try:
38
+ if not select.select([process.stdout], [], [], 30)[0]:
39
+ raise TimeoutError("Timed out acquiring Eval output lock")
40
+ response = process.stdout.readline()
41
+ if response == b"busy\n":
42
+ raise FileExistsError("Another eval is writing to this output directory")
43
+ if response != b"locked\n":
44
+ raise OSError("Cannot lock Eval output: " + process.stderr.read().decode(errors="replace"))
45
+ yield process
46
+ finally:
47
+ process.stdin.close()
48
+ try:
49
+ process.wait(timeout=5)
50
+ except subprocess.TimeoutExpired:
51
+ process.kill()
52
+ process.wait()
53
+ process.stdout.close()
54
+ process.stderr.close()
envweaver/_io/paths.py ADDED
@@ -0,0 +1,37 @@
1
+ """Parse local paths and SSH file addresses."""
2
+
3
+ from pathlib import Path
4
+ from urllib.parse import quote, unquote, urlsplit, urlunsplit
5
+
6
+ from .ssh_transport import _validate_host
7
+
8
+
9
+ def _location(root):
10
+ parsed = urlsplit(root)
11
+ if parsed.scheme != "ssh":
12
+ raise ValueError(f"Unsupported file address scheme: {parsed.scheme}")
13
+ host = urlunsplit((parsed.scheme, parsed.netloc, "", "", ""))
14
+ _validate_host(host)
15
+ path = unquote(parsed.path)
16
+ if parsed.query or parsed.fragment or not path.startswith("/") or "\x00" in path:
17
+ raise ValueError("SSH address must include an absolute path, without query or fragment")
18
+ return host, path
19
+
20
+
21
+ def normalize_address(root: str | Path) -> str | Path:
22
+ if isinstance(root, str):
23
+ if not root.strip():
24
+ raise ValueError("File address must be nonempty")
25
+ if "://" in root:
26
+ host, path = _location(root)
27
+ return host + quote(path, safe="/")
28
+ return Path(root).expanduser().absolute()
29
+
30
+
31
+ def join_address(root: str | Path, name: str) -> str | Path:
32
+ """Append one relative path without interpreting an SSH URL as a local path."""
33
+ root = normalize_address(root)
34
+ if isinstance(root, Path):
35
+ return root / name
36
+ host, path = _location(root)
37
+ return host + quote(path.rstrip("/") + "/" + name, safe="/")
@@ -0,0 +1,26 @@
1
+ """A scoped binary pipe to a sandbox process."""
2
+
3
+ import subprocess
4
+ from contextlib import contextmanager
5
+
6
+
7
+ @contextmanager
8
+ def open_pipe(command, *, env=None):
9
+ process = subprocess.Popen(
10
+ command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
11
+ env=env,
12
+ )
13
+ try:
14
+ yield process
15
+ finally:
16
+ try:
17
+ process.stdin.close()
18
+ except OSError:
19
+ pass
20
+ try:
21
+ process.wait(timeout=5)
22
+ except subprocess.TimeoutExpired:
23
+ process.kill()
24
+ process.wait()
25
+ process.stdout.close()
26
+ process.stderr.close()
envweaver/_io/retry.py ADDED
@@ -0,0 +1,59 @@
1
+ """Bounded recovery for transport operations, without replaying arbitrary commands."""
2
+
3
+ import re
4
+ import subprocess
5
+ import time
6
+ from contextvars import ContextVar
7
+
8
+ from ..errors import RuntimeError
9
+
10
+ _active = ContextVar("envweaver_transport_retry", default=False)
11
+
12
+
13
+ class ConnectionFailure(RuntimeError, ConnectionError):
14
+ def __init__(self, message, *, before_dispatch=False):
15
+ super().__init__(message)
16
+ self.before_dispatch = before_dispatch
17
+
18
+
19
+ def connection_error(message):
20
+ """Interpret transport diagnostics only, never command output or model messages."""
21
+ text = message.lower()
22
+ if any(value in text for value in (
23
+ "permission denied", "host key verification failed", "remote host identification has changed",
24
+ )):
25
+ return RuntimeError(message)
26
+ before_dispatch = bool(re.search(
27
+ r"ssh: connect to host .*: (connection refused|connection timed out|no route to host|network is unreachable)",
28
+ text,
29
+ ))
30
+ if before_dispatch or any(value in text for value in (
31
+ "connection reset", "connection closed", "broken pipe", "connection timed out",
32
+ "connection refused", "network is unreachable", "no route to host",
33
+ "temporary failure in name resolution",
34
+ )):
35
+ return ConnectionFailure(message, before_dispatch=before_dispatch)
36
+ return RuntimeError(message)
37
+
38
+
39
+ def retry(operation, *, replay=False, cancelled=None):
40
+ """Try up to three times; nested calls share the outer recovery budget."""
41
+ if _active.get():
42
+ return operation()
43
+ token = _active.set(True)
44
+ try:
45
+ for attempt in range(3):
46
+ if cancelled is not None and cancelled.is_set():
47
+ raise InterruptedError("Transport recovery cancelled")
48
+ try:
49
+ return operation()
50
+ except (ConnectionError, TimeoutError, subprocess.TimeoutExpired) as error:
51
+ if attempt == 2 or not (replay or getattr(error, "before_dispatch", False)):
52
+ raise
53
+ delay = 0.5 * 2 ** attempt
54
+ if cancelled is None:
55
+ time.sleep(delay)
56
+ elif cancelled.wait(delay):
57
+ raise InterruptedError("Transport recovery cancelled") from error
58
+ finally:
59
+ _active.reset(token)
@@ -0,0 +1,80 @@
1
+ """Per-call OpenSSH configuration; never edits the user's SSH files."""
2
+
3
+ import os
4
+ import shlex
5
+ import shutil
6
+ import tempfile
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+
10
+ from .._util import merge_dicts
11
+
12
+ _FILES = ("config_file", "known_hosts_file", "identity_file")
13
+
14
+
15
+ def reconnect_options(saved, overrides):
16
+ """None inherits a record; {} resets it; nonempty overrides merge recursively."""
17
+ if overrides is None:
18
+ return normalize(saved)
19
+ if not overrides:
20
+ return {}
21
+
22
+ return normalize(merge_dicts(saved or {}, overrides))
23
+
24
+
25
+ def normalize(options):
26
+ if options is None:
27
+ return {}
28
+ if not isinstance(options, dict):
29
+ raise TypeError("SSH configuration must be a dictionary")
30
+ result = dict(options)
31
+ for key in (*_FILES, "host_key_alias"):
32
+ if key not in result:
33
+ continue
34
+ value = os.fspath(result[key]) if isinstance(result[key], Path) else result[key]
35
+ if not isinstance(value, str) or not value.strip() or any(c in value for c in "\x00\r\n"):
36
+ raise ValueError(f"Invalid ssh.{key}")
37
+ if key == "host_key_alias":
38
+ if any(c.isspace() for c in value):
39
+ raise ValueError("Invalid ssh.host_key_alias")
40
+ result[key] = value
41
+ else:
42
+ result[key] = str(Path(value).expanduser().absolute())
43
+ return result
44
+
45
+
46
+ def flags(options):
47
+ options = normalize(options)
48
+ args = []
49
+ if "config_file" in options:
50
+ args += ["-F", options["config_file"]]
51
+ if "known_hosts_file" in options:
52
+ # OpenSSH parses this option as a list of filenames, even in one argv item.
53
+ path = (
54
+ options["known_hosts_file"].replace("%", "%%").replace("\\", "\\\\").replace('"', '\\"')
55
+ )
56
+ args += ["-o", f'UserKnownHostsFile="{path}"']
57
+ if "identity_file" in options:
58
+ if not Path(options["identity_file"]).is_file():
59
+ raise FileNotFoundError(options["identity_file"])
60
+ args += ["-i", options["identity_file"]]
61
+ if "host_key_alias" in options:
62
+ args += ["-o", "HostKeyAlias=" + options["host_key_alias"]]
63
+ return args
64
+
65
+
66
+ @contextmanager
67
+ def docker_environment(env, options):
68
+ """Docker invokes ssh via PATH; supply options only to this Docker subprocess."""
69
+ args = flags(options)
70
+ if not args:
71
+ yield env
72
+ return
73
+ executable = shutil.which("ssh", path=env.get("PATH"))
74
+ if executable is None:
75
+ raise FileNotFoundError("ssh executable not found")
76
+ with tempfile.TemporaryDirectory(prefix="envweaver-ssh-") as directory:
77
+ wrapper = Path(directory) / "ssh"
78
+ wrapper.write_text("#!/bin/sh\nexec " + shlex.join([executable, *args]) + ' "$@"\n')
79
+ wrapper.chmod(0o700)
80
+ yield {**env, "PATH": directory + os.pathsep + env.get("PATH", os.defpath)}
@@ -0,0 +1,61 @@
1
+ """Run commands over SSH with a JSON request on standard input."""
2
+
3
+ import json
4
+ import shlex
5
+ import subprocess
6
+ from urllib.parse import urlsplit
7
+
8
+ from ..errors import RuntimeError
9
+ from .retry import connection_error, retry
10
+ from .ssh_config import flags
11
+
12
+
13
+ def _validate_host(host):
14
+ if host is None:
15
+ return None
16
+ if not isinstance(host, str):
17
+ raise ValueError("host must be an SSH URL, e.g. ssh://user@server:22")
18
+ parsed = urlsplit(host)
19
+ if (
20
+ parsed.scheme != "ssh"
21
+ or not parsed.hostname
22
+ or parsed.password is not None
23
+ or parsed.path
24
+ or parsed.query
25
+ or parsed.fragment
26
+ or any(c.isspace() for c in host)
27
+ ):
28
+ raise ValueError("host must be an SSH URL without a password or path")
29
+ parsed.port # Validate port syntax and range.
30
+ return host
31
+
32
+
33
+ def command_args(host, command, *, ssh_options=None):
34
+ parsed = urlsplit(_validate_host(host))
35
+ destination = parsed.hostname
36
+ if parsed.username:
37
+ destination = f"{parsed.username}@{destination}"
38
+ args = ["ssh", *flags(ssh_options), "-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10"]
39
+ if parsed.port is not None:
40
+ args += ["-p", str(parsed.port)]
41
+ args += ["--", destination, shlex.join(command)]
42
+ return args
43
+
44
+
45
+ def ssh(host, command, payload, *, timeout=60, ssh_options=None):
46
+ args = command_args(host, command, ssh_options=ssh_options)
47
+ body = json.dumps(payload, allow_nan=False).encode()
48
+
49
+ def send():
50
+ try:
51
+ result = subprocess.run(args, input=body, capture_output=True, timeout=timeout)
52
+ except subprocess.TimeoutExpired as error:
53
+ raise TimeoutError("Remote EnvWeaver call timed out") from error
54
+ if result.returncode:
55
+ message = result.stderr.decode(errors="replace")
56
+ if result.returncode == 255:
57
+ raise connection_error(message)
58
+ raise RuntimeError(f"Remote command failed: {message}")
59
+ return result.stdout
60
+
61
+ return retry(send)
@@ -0,0 +1,181 @@
1
+ """Local and SSH file transfers and environment record storage."""
2
+
3
+ import base64
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import shutil
8
+ import sys
9
+ import tempfile
10
+ from contextlib import contextmanager
11
+ from pathlib import Path, PurePosixPath
12
+
13
+ # The SSH worker receives files.py before this module; it needs only Python's stdlib.
14
+ if __package__:
15
+ from .files import pack, unpack
16
+ from .paths import _location, normalize_address
17
+ from .retry import retry
18
+
19
+
20
+ def _operate(payload):
21
+ if payload["action"] == "exists":
22
+ return Path(payload["root"]).exists()
23
+ if payload["action"] == "publish_directory":
24
+ target = Path(payload["root"])
25
+ target.parent.mkdir(parents=True, exist_ok=True)
26
+ if target.exists() or target.is_symlink():
27
+ raise FileExistsError(str(target))
28
+ if "source" in payload:
29
+ Path(payload["source"]).rename(target)
30
+ else:
31
+ with tempfile.TemporaryDirectory(prefix=".publish-", dir=target.parent) as temporary:
32
+ stage = Path(temporary) / "new"
33
+ unpack("directory", base64.b64decode(payload["body"]), stage, mode=0o700)
34
+ stage.rename(target)
35
+ return
36
+ if payload["action"] == "read_json":
37
+ target = Path(payload["root"])
38
+ return json.loads(target.read_text()) if target.exists() else None
39
+ if payload["action"] == "fingerprint":
40
+ target = Path(payload["root"]).resolve(strict=True)
41
+ digest = hashlib.sha256()
42
+ entries = [target] if target.is_file() else [target, *sorted(target.rglob("*"))]
43
+ for entry in entries:
44
+ if entry.is_symlink():
45
+ raise ValueError(f"File transfer does not follow symlinks: {entry}")
46
+ content = hashlib.sha256()
47
+ if entry.is_file():
48
+ with entry.open("rb") as stream:
49
+ while chunk := stream.read(1024 * 1024):
50
+ content.update(chunk)
51
+ digest.update(json.dumps([
52
+ str(entry.relative_to(target)), entry.stat().st_mode, content.hexdigest(),
53
+ ]).encode())
54
+ return {"kind": "file" if target.is_file() else "directory", "sha256": digest.hexdigest()}
55
+ if payload["action"] == "mkdir":
56
+ target = Path(payload["root"])
57
+ sentinel = payload.get("sentinel")
58
+ if sentinel and (target / sentinel).exists():
59
+ return False
60
+ try:
61
+ target.mkdir(parents=True, exist_ok=payload["exist_ok"])
62
+ except FileExistsError:
63
+ return False
64
+ return True
65
+ if payload["action"] == "publish":
66
+ target = Path(payload["root"])
67
+ target.parent.mkdir(parents=True, exist_ok=True)
68
+ with tempfile.TemporaryDirectory(prefix=".envweaver-", dir=target.parent) as temporary:
69
+ source = Path(temporary) / "file"
70
+ source.write_bytes(base64.b64decode(payload["body"]))
71
+ os.chmod(source, payload["mode"])
72
+ os.replace(source, target)
73
+ return
74
+ if payload["action"] == "read":
75
+ kind, body = pack(payload["root"])
76
+ return {
77
+ "kind": kind,
78
+ "body": base64.b64encode(body).decode(),
79
+ "mode": Path(payload["root"]).stat().st_mode & 0o777,
80
+ }
81
+ if payload["action"] == "write":
82
+ unpack(
83
+ payload["kind"],
84
+ base64.b64decode(payload["body"]),
85
+ payload["root"],
86
+ mode=payload["mode"],
87
+ )
88
+ return
89
+ relative = PurePosixPath(payload["directory"])
90
+ if relative.is_absolute() or ".." in relative.parts or not relative.parts:
91
+ raise ValueError("Record directory must be relative to root")
92
+ target = Path(payload["root"]) / str(relative)
93
+ if payload["action"] == "remove":
94
+ if target.exists():
95
+ shutil.rmtree(target)
96
+ return
97
+ target.parent.mkdir(parents=True, exist_ok=True)
98
+ with tempfile.TemporaryDirectory(prefix=".record-", dir=target.parent) as temporary:
99
+ stage = Path(temporary) / "record"
100
+ stage.mkdir()
101
+ for name, value in payload["records"].items():
102
+ if Path(name).name != name:
103
+ raise ValueError("Record name must be a filename")
104
+ path = stage / name
105
+ path.write_text(
106
+ json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2), encoding="utf-8"
107
+ )
108
+ os.chmod(path, 0o600 if payload["private"] else 0o644)
109
+ stage.rename(target)
110
+
111
+
112
+ def _dispatch(root, payload):
113
+ root = normalize_address(root)
114
+ if isinstance(root, Path):
115
+ return _operate({**payload, "root": str(root)})
116
+ else:
117
+ from .ssh_transport import ssh
118
+
119
+ host, path = _location(root)
120
+ source = (
121
+ Path(__file__).with_name("files.py").read_text() + "\n" + Path(__file__).read_text()
122
+ )
123
+ output = retry(lambda: ssh(
124
+ host,
125
+ ["python3", "-c", source],
126
+ {**payload, "root": path},
127
+ ), replay=payload["action"] in {"read", "read_json", "fingerprint", "write", "publish", "remove"})
128
+ return json.loads(output)
129
+
130
+
131
+ def write_records(root, directory, records, *, private=False):
132
+ _dispatch(
133
+ root,
134
+ {"action": "records", "directory": directory, "records": records, "private": private},
135
+ )
136
+
137
+
138
+ def remove_records(root, directory):
139
+ _dispatch(root, {"action": "remove", "directory": directory})
140
+
141
+
142
+ @contextmanager
143
+ def local_source(source):
144
+ """Yield a local path, downloading SSH input for the duration of the operation."""
145
+ address = normalize_address(source)
146
+ if isinstance(address, Path):
147
+ yield address
148
+ return
149
+ _, path = _location(address)
150
+ with tempfile.TemporaryDirectory(prefix="envweaver-files-") as temporary:
151
+ name = PurePosixPath(path).name
152
+ target = Path(temporary) / (name if name not in {"", ".", ".."} else "data")
153
+ result = _dispatch(address, {"action": "read"})
154
+ unpack(result["kind"], base64.b64decode(result["body"]), target, mode=result["mode"])
155
+ yield target
156
+
157
+
158
+ @contextmanager
159
+ def local_target(target):
160
+ """Yield a local destination; copy to SSH only after the caller succeeds."""
161
+ address = normalize_address(target)
162
+ if isinstance(address, Path):
163
+ yield address
164
+ return
165
+ with tempfile.TemporaryDirectory(prefix="envweaver-files-") as temporary:
166
+ source = Path(temporary) / "data"
167
+ yield source
168
+ kind, body = pack(source)
169
+ _dispatch(
170
+ address,
171
+ {
172
+ "action": "write",
173
+ "kind": kind,
174
+ "body": base64.b64encode(body).decode(),
175
+ "mode": source.stat().st_mode & 0o777,
176
+ },
177
+ )
178
+
179
+
180
+ if __name__ == "__main__":
181
+ print(json.dumps(_operate(json.load(sys.stdin))))