runlatch 1.0.0__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 (74) hide show
  1. runlatch/__init__.py +119 -0
  2. runlatch/adapters/__init__.py +1 -0
  3. runlatch/adapters/executors/__init__.py +13 -0
  4. runlatch/adapters/executors/docker_exec.py +184 -0
  5. runlatch/adapters/executors/subprocess_exec.py +163 -0
  6. runlatch/adapters/llm/__init__.py +16 -0
  7. runlatch/adapters/llm/anthropic.py +212 -0
  8. runlatch/adapters/llm/gemini.py +213 -0
  9. runlatch/adapters/llm/mock.py +62 -0
  10. runlatch/adapters/llm/openai_compat.py +244 -0
  11. runlatch/adapters/llm/pricing.py +43 -0
  12. runlatch/adapters/notifications/__init__.py +23 -0
  13. runlatch/adapters/notifications/discord.py +71 -0
  14. runlatch/adapters/notifications/email.py +95 -0
  15. runlatch/adapters/notifications/github_comment.py +94 -0
  16. runlatch/adapters/notifications/router.py +105 -0
  17. runlatch/adapters/notifications/slack.py +85 -0
  18. runlatch/adapters/notifications/webhook.py +68 -0
  19. runlatch/adapters/observability/__init__.py +8 -0
  20. runlatch/adapters/observability/otel.py +92 -0
  21. runlatch/adapters/storage/__init__.py +27 -0
  22. runlatch/adapters/storage/models.py +249 -0
  23. runlatch/adapters/storage/sqlalchemy_store.py +659 -0
  24. runlatch/config.py +141 -0
  25. runlatch/core/__init__.py +80 -0
  26. runlatch/core/agent.py +765 -0
  27. runlatch/core/events.py +56 -0
  28. runlatch/core/exceptions.py +74 -0
  29. runlatch/core/policy.py +78 -0
  30. runlatch/core/protocols.py +180 -0
  31. runlatch/core/redactor.py +129 -0
  32. runlatch/core/types.py +336 -0
  33. runlatch/core/workflow.py +451 -0
  34. runlatch/runtime/__init__.py +1 -0
  35. runlatch/runtime/cli/__init__.py +1 -0
  36. runlatch/runtime/cli/main.py +720 -0
  37. runlatch/runtime/server/__init__.py +5 -0
  38. runlatch/runtime/server/app.py +76 -0
  39. runlatch/runtime/server/auth.py +89 -0
  40. runlatch/runtime/server/deps.py +148 -0
  41. runlatch/runtime/server/routes/__init__.py +1 -0
  42. runlatch/runtime/server/routes/approvals.py +144 -0
  43. runlatch/runtime/server/routes/health.py +39 -0
  44. runlatch/runtime/server/routes/metrics.py +19 -0
  45. runlatch/runtime/server/routes/runs.py +294 -0
  46. runlatch/runtime/server/routes/ui.py +88 -0
  47. runlatch/runtime/server/routes/webhooks.py +139 -0
  48. runlatch/runtime/workers/__init__.py +23 -0
  49. runlatch/runtime/workers/agent_tasks.py +391 -0
  50. runlatch/runtime/workers/celery_app.py +140 -0
  51. runlatch/runtime/workers/maintenance_tasks.py +80 -0
  52. runlatch/runtime/workers/notification_tasks.py +192 -0
  53. runlatch/toolkits/__init__.py +26 -0
  54. runlatch/toolkits/filesystem.py +191 -0
  55. runlatch/toolkits/git.py +112 -0
  56. runlatch/toolkits/github.py +184 -0
  57. runlatch/toolkits/mcp.py +362 -0
  58. runlatch/toolkits/shell.py +52 -0
  59. runlatch/tools/__init__.py +5 -0
  60. runlatch/tools/git_patcher.py +155 -0
  61. runlatch/tools/registry.py +199 -0
  62. runlatch/tools/sandbox.py +92 -0
  63. runlatch/workflows/__init__.py +35 -0
  64. runlatch/workflows/ci_triage.py +160 -0
  65. runlatch/workflows/dep_audit.py +154 -0
  66. runlatch/workflows/doc_sync.py +187 -0
  67. runlatch/workflows/issue_to_pr.py +185 -0
  68. runlatch/workflows/pr_review.py +168 -0
  69. runlatch-1.0.0.dist-info/METADATA +235 -0
  70. runlatch-1.0.0.dist-info/RECORD +74 -0
  71. runlatch-1.0.0.dist-info/WHEEL +5 -0
  72. runlatch-1.0.0.dist-info/entry_points.txt +2 -0
  73. runlatch-1.0.0.dist-info/licenses/LICENSE +21 -0
  74. runlatch-1.0.0.dist-info/top_level.txt +1 -0
runlatch/__init__.py ADDED
@@ -0,0 +1,119 @@
1
+ """runlatch — Durable, HITL-First Execution Runtime for Autonomous Developer Agents."""
2
+
3
+ from runlatch.adapters.executors import DockerSandboxExecutor, SubprocessExecutor
4
+ from runlatch.adapters.llm import (
5
+ AnthropicProvider,
6
+ GeminiProvider,
7
+ MockLLMProvider,
8
+ OpenAICompatibleProvider,
9
+ )
10
+ from runlatch.adapters.notifications import (
11
+ DiscordNotificationProvider,
12
+ GitHubCommentNotificationProvider,
13
+ NotificationRouter,
14
+ SlackNotificationProvider,
15
+ SMTPEmailNotificationProvider,
16
+ WebhookNotificationProvider,
17
+ )
18
+ from runlatch.adapters.observability import OpenTelemetrySubscriber, RecordedSpan
19
+ from runlatch.adapters.storage import SQLAlchemyCheckpointStore
20
+ from runlatch.config import PolicySettings, RunLatchSettings
21
+ from runlatch.core.agent import Agent
22
+ from runlatch.core.events import EventBus
23
+ from runlatch.core.exceptions import (
24
+ ApprovalAlreadyDecidedError,
25
+ ApprovalExpiredError,
26
+ ApprovalRequiredSignal,
27
+ BudgetExceededError,
28
+ LoopDetectedError,
29
+ PatchTooLargeError,
30
+ PolicyDeniedError,
31
+ RunLatchError,
32
+ SandboxViolationError,
33
+ ToolValidationError,
34
+ )
35
+ from runlatch.core.policy import PolicyEngine
36
+ from runlatch.core.redactor import SecretRedactor
37
+ from runlatch.core.types import (
38
+ BudgetConfig,
39
+ LLMResponse,
40
+ Message,
41
+ NotificationEvent,
42
+ RiskTier,
43
+ RunCheckpoint,
44
+ RunResult,
45
+ RunStatus,
46
+ ToolCall,
47
+ ToolSpec,
48
+ WorkspaceMeta,
49
+ )
50
+ from runlatch.core.workflow import Step, Workflow
51
+ from runlatch.toolkits import (
52
+ FileToolkit,
53
+ GitHubToolkit,
54
+ GitToolkit,
55
+ MCPServerConfig,
56
+ MCPToolDescriptor,
57
+ MCPToolkit,
58
+ ShellToolkit,
59
+ )
60
+ from runlatch.tools.git_patcher import GitWorkspacePatcher
61
+ from runlatch.tools.registry import FunctionTool, ToolRegistry, tool
62
+
63
+ __all__ = [
64
+ "Agent",
65
+ "AnthropicProvider",
66
+ "ApprovalAlreadyDecidedError",
67
+ "ApprovalExpiredError",
68
+ "ApprovalRequiredSignal",
69
+ "BudgetConfig",
70
+ "BudgetExceededError",
71
+ "DiscordNotificationProvider",
72
+ "DockerSandboxExecutor",
73
+ "EventBus",
74
+ "FileToolkit",
75
+ "FunctionTool",
76
+ "GeminiProvider",
77
+ "GitHubCommentNotificationProvider",
78
+ "GitHubToolkit",
79
+ "GitToolkit",
80
+ "GitWorkspacePatcher",
81
+ "LLMResponse",
82
+ "LoopDetectedError",
83
+ "MCPServerConfig",
84
+ "MCPToolDescriptor",
85
+ "MCPToolkit",
86
+ "Message",
87
+ "MockLLMProvider",
88
+ "NotificationEvent",
89
+ "NotificationRouter",
90
+ "OpenAICompatibleProvider",
91
+ "OpenTelemetrySubscriber",
92
+ "PatchTooLargeError",
93
+ "PolicyDeniedError",
94
+ "PolicyEngine",
95
+ "PolicySettings",
96
+ "RecordedSpan",
97
+ "RiskTier",
98
+ "RunCheckpoint",
99
+ "RunLatchError",
100
+ "RunLatchSettings",
101
+ "RunResult",
102
+ "RunStatus",
103
+ "SMTPEmailNotificationProvider",
104
+ "SQLAlchemyCheckpointStore",
105
+ "SandboxViolationError",
106
+ "SecretRedactor",
107
+ "ShellToolkit",
108
+ "SlackNotificationProvider",
109
+ "Step",
110
+ "SubprocessExecutor",
111
+ "ToolCall",
112
+ "ToolRegistry",
113
+ "ToolSpec",
114
+ "ToolValidationError",
115
+ "WebhookNotificationProvider",
116
+ "Workflow",
117
+ "WorkspaceMeta",
118
+ "tool",
119
+ ]
@@ -0,0 +1 @@
1
+ """Adapters layer for runlatch."""
@@ -0,0 +1,13 @@
1
+ """Command executor adapters for runlatch."""
2
+
3
+ from runlatch.adapters.executors.docker_exec import DockerSandboxExecutor
4
+ from runlatch.adapters.executors.subprocess_exec import (
5
+ FORBIDDEN_INTERPRETERS,
6
+ SubprocessExecutor,
7
+ )
8
+
9
+ __all__ = [
10
+ "DockerSandboxExecutor",
11
+ "FORBIDDEN_INTERPRETERS",
12
+ "SubprocessExecutor",
13
+ ]
@@ -0,0 +1,184 @@
1
+ """Ephemeral DockerSandboxExecutor for untrusted PR/issue execution.
2
+
3
+ Runs commands inside an isolated container with:
4
+ `docker run --rm --network=none --cap-drop=ALL --read-only --memory=512m --cpus=1`
5
+ Enforces the same strict binary allowlist (no raw python/bash/sh) and metacharacter
6
+ blocking as SubprocessExecutor.
7
+ Imports ONLY Python stdlib and runlatch.core.*.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import re
14
+ import time
15
+ from collections.abc import Callable, Coroutine, Sequence
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from runlatch.adapters.executors.subprocess_exec import FORBIDDEN_INTERPRETERS
20
+ from runlatch.core.exceptions import SandboxViolationError
21
+ from runlatch.core.types import CommandResult
22
+
23
+ _SHELL_METACHAR_RE = re.compile(r"[;&|`$<>\\\n\r\x00]")
24
+
25
+ ProcessRunner = Callable[
26
+ [Sequence[str], Path, float],
27
+ Coroutine[Any, Any, tuple[int, str, str, bool]],
28
+ ]
29
+
30
+
31
+ def _is_forbidden_binary(binary_name: str) -> bool:
32
+ lower = Path(binary_name).name.lower()
33
+ if lower in FORBIDDEN_INTERPRETERS:
34
+ return True
35
+ if lower.startswith("python3.") or lower.startswith("python2."):
36
+ return True
37
+ return False
38
+
39
+
40
+ async def _default_docker_runner(
41
+ argv: Sequence[str], cwd: Path, timeout_s: float
42
+ ) -> tuple[int, str, str, bool]:
43
+ proc = await asyncio.create_subprocess_exec(
44
+ *argv,
45
+ cwd=str(cwd),
46
+ stdin=asyncio.subprocess.DEVNULL,
47
+ stdout=asyncio.subprocess.PIPE,
48
+ stderr=asyncio.subprocess.PIPE,
49
+ )
50
+ timed_out = False
51
+ try:
52
+ out_b, err_b = await asyncio.wait_for(proc.communicate(), timeout=timeout_s)
53
+ except TimeoutError:
54
+ timed_out = True
55
+ proc.kill()
56
+ out_b, err_b = await proc.communicate()
57
+
58
+ code = -1 if timed_out else (proc.returncode if proc.returncode is not None else 1)
59
+ return (
60
+ code,
61
+ out_b.decode("utf-8", errors="replace"),
62
+ err_b.decode("utf-8", errors="replace"),
63
+ timed_out,
64
+ )
65
+
66
+
67
+ class DockerSandboxExecutor:
68
+ """Ephemeral container command executor implementing CommandExecutor."""
69
+
70
+ def __init__(
71
+ self,
72
+ *,
73
+ image: str = "python:3.12-slim",
74
+ allowed_binaries: Sequence[str] = ("pytest", "ruff", "mypy", "git"),
75
+ memory_limit: str = "512m",
76
+ cpus: str = "1",
77
+ docker_binary: str = "docker",
78
+ default_timeout_s: float = 60.0,
79
+ runner: ProcessRunner | None = None,
80
+ ) -> None:
81
+ normalized_allowlist: set[str] = set()
82
+ for binary in allowed_binaries:
83
+ base = Path(binary).name
84
+ if _is_forbidden_binary(base):
85
+ raise SandboxViolationError(
86
+ f"Raw interpreter '{binary}' is forbidden in DockerSandboxExecutor allowlist."
87
+ )
88
+ normalized_allowlist.add(base)
89
+
90
+ self.image = image
91
+ self.allowed_binaries = frozenset(normalized_allowlist)
92
+ self.memory_limit = memory_limit
93
+ self.cpus = cpus
94
+ self.docker_binary = docker_binary
95
+ self.default_timeout_s = default_timeout_s
96
+ self._runner: ProcessRunner = runner or _default_docker_runner
97
+
98
+ def _validate_inner_command(self, command: Sequence[str]) -> list[str]:
99
+ if not command:
100
+ raise SandboxViolationError("Command sequence must not be empty.")
101
+ argv = [str(part) for part in command]
102
+ binary_base = Path(argv[0]).name
103
+
104
+ if _is_forbidden_binary(binary_base):
105
+ raise SandboxViolationError(
106
+ f"Execution of raw interpreter '{binary_base}' is strictly forbidden."
107
+ )
108
+ if binary_base not in self.allowed_binaries:
109
+ allowed_list = sorted(self.allowed_binaries)
110
+ raise SandboxViolationError(
111
+ f"Binary '{binary_base}' is not in allowed_binaries {allowed_list}."
112
+ )
113
+ for token in argv:
114
+ if _SHELL_METACHAR_RE.search(token):
115
+ raise SandboxViolationError(
116
+ f"Shell metacharacter or injection token blocked in argument: '{token}'."
117
+ )
118
+ return argv
119
+
120
+ def build_docker_argv(
121
+ self,
122
+ command: Sequence[str],
123
+ *,
124
+ cwd: Path,
125
+ env_overrides: dict[str, str] | None = None,
126
+ ) -> list[str]:
127
+ """Construct the hardened `docker run` argument vector."""
128
+ inner_argv = self._validate_inner_command(command)
129
+ resolved_cwd = Path(cwd).resolve()
130
+
131
+ env_flags: list[str] = []
132
+ if env_overrides:
133
+ for k, v in sorted(env_overrides.items()):
134
+ if _SHELL_METACHAR_RE.search(k) or _SHELL_METACHAR_RE.search(v):
135
+ raise SandboxViolationError("Invalid characters in env_overrides.")
136
+ env_flags.extend(["-e", f"{k}={v}"])
137
+
138
+ return [
139
+ self.docker_binary,
140
+ "run",
141
+ "--rm",
142
+ "--network=none",
143
+ "--cap-drop=ALL",
144
+ "--read-only",
145
+ f"--memory={self.memory_limit}",
146
+ f"--cpus={self.cpus}",
147
+ "--security-opt=no-new-privileges",
148
+ "--tmpfs",
149
+ "/tmp:rw,noexec,nosuid,size=64m",
150
+ "-v",
151
+ f"{resolved_cwd}:/workspace:rw",
152
+ "-w",
153
+ "/workspace",
154
+ *env_flags,
155
+ self.image,
156
+ *inner_argv,
157
+ ]
158
+
159
+ async def run_command(
160
+ self,
161
+ command: Sequence[str],
162
+ *,
163
+ cwd: Path,
164
+ timeout_s: float = 60.0,
165
+ env_overrides: dict[str, str] | None = None,
166
+ ) -> CommandResult:
167
+ docker_argv = self.build_docker_argv(
168
+ command, cwd=cwd, env_overrides=env_overrides
169
+ )
170
+ effective_timeout = timeout_s if timeout_s > 0 else self.default_timeout_s
171
+ start = time.perf_counter()
172
+
173
+ exit_code, stdout, stderr, timed_out = await self._runner(
174
+ docker_argv, Path(cwd).resolve(), effective_timeout
175
+ )
176
+ duration_ms = int((time.perf_counter() - start) * 1000)
177
+ return CommandResult(
178
+ command=docker_argv,
179
+ exit_code=exit_code,
180
+ stdout=stdout,
181
+ stderr=stderr,
182
+ timed_out=timed_out,
183
+ duration_ms=duration_ms,
184
+ )
@@ -0,0 +1,163 @@
1
+ """Local SubprocessExecutor for trusted repositories.
2
+
3
+ Enforces shell=False, strict binary allowlist, forbidden raw interpreters
4
+ (never allows python/bash/sh/node), metacharacter blocking, and environment stripping.
5
+ Imports ONLY Python stdlib and runlatch.core.*.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import os
12
+ import re
13
+ import time
14
+ from collections.abc import Sequence
15
+ from pathlib import Path
16
+
17
+ from runlatch.core.exceptions import SandboxViolationError
18
+ from runlatch.core.types import CommandResult
19
+
20
+ FORBIDDEN_INTERPRETERS: frozenset[str] = frozenset(
21
+ {
22
+ "python",
23
+ "python2",
24
+ "python3",
25
+ "bash",
26
+ "sh",
27
+ "zsh",
28
+ "dash",
29
+ "ksh",
30
+ "fish",
31
+ "node",
32
+ "nodejs",
33
+ "perl",
34
+ "ruby",
35
+ "php",
36
+ "lua",
37
+ "pwsh",
38
+ "powershell",
39
+ "cmd",
40
+ "curl",
41
+ "wget",
42
+ "nc",
43
+ "netcat",
44
+ }
45
+ )
46
+
47
+ _SHELL_METACHAR_RE = re.compile(r"[;&|`$<>\\\n\r\x00]")
48
+
49
+
50
+ def _is_forbidden_binary(binary_name: str) -> bool:
51
+ lower = Path(binary_name).name.lower()
52
+ if lower in FORBIDDEN_INTERPRETERS:
53
+ return True
54
+ if lower.startswith("python3.") or lower.startswith("python2."):
55
+ return True
56
+ return False
57
+
58
+
59
+ class SubprocessExecutor:
60
+ """Trusted-repo subprocess command executor implementing CommandExecutor."""
61
+
62
+ def __init__(
63
+ self,
64
+ *,
65
+ allowed_binaries: Sequence[str] = ("pytest", "ruff", "mypy", "git"),
66
+ inherit_env_allowlist: Sequence[str] = (
67
+ "PATH",
68
+ "HOME",
69
+ "LANG",
70
+ "VIRTUAL_ENV",
71
+ "TMPDIR",
72
+ ),
73
+ default_timeout_s: float = 60.0,
74
+ ) -> None:
75
+ normalized_allowlist: set[str] = set()
76
+ for binary in allowed_binaries:
77
+ base = Path(binary).name
78
+ if _is_forbidden_binary(base):
79
+ raise SandboxViolationError(
80
+ f"Raw interpreter or network binary '{binary}' is forbidden in "
81
+ "SubprocessExecutor allowlist."
82
+ )
83
+ normalized_allowlist.add(base)
84
+
85
+ self.allowed_binaries = frozenset(normalized_allowlist)
86
+ self.inherit_env_allowlist = tuple(inherit_env_allowlist)
87
+ self.default_timeout_s = default_timeout_s
88
+
89
+ def _build_env(self, overrides: dict[str, str] | None) -> dict[str, str]:
90
+ env: dict[str, str] = {}
91
+ for key in self.inherit_env_allowlist:
92
+ if key in os.environ:
93
+ env[key] = os.environ[key]
94
+ if overrides:
95
+ for k, v in overrides.items():
96
+ env[str(k)] = str(v)
97
+ return env
98
+
99
+ def _validate_command(self, command: Sequence[str]) -> list[str]:
100
+ if not command:
101
+ raise SandboxViolationError("Command sequence must not be empty.")
102
+ argv = [str(part) for part in command]
103
+ binary_base = Path(argv[0]).name
104
+
105
+ if _is_forbidden_binary(binary_base):
106
+ raise SandboxViolationError(
107
+ f"Execution of raw interpreter '{binary_base}' is strictly forbidden."
108
+ )
109
+ if binary_base not in self.allowed_binaries:
110
+ allowed_list = sorted(self.allowed_binaries)
111
+ raise SandboxViolationError(
112
+ f"Binary '{binary_base}' is not in allowed_binaries {allowed_list}."
113
+ )
114
+
115
+ for token in argv:
116
+ if _SHELL_METACHAR_RE.search(token):
117
+ raise SandboxViolationError(
118
+ f"Shell metacharacter or injection token blocked in argument: '{token}'."
119
+ )
120
+ return argv
121
+
122
+ async def run_command(
123
+ self,
124
+ command: Sequence[str],
125
+ *,
126
+ cwd: Path,
127
+ timeout_s: float = 60.0,
128
+ env_overrides: dict[str, str] | None = None,
129
+ ) -> CommandResult:
130
+ argv = self._validate_command(command)
131
+ effective_timeout = timeout_s if timeout_s > 0 else self.default_timeout_s
132
+ clean_env = self._build_env(env_overrides)
133
+ start = time.perf_counter()
134
+
135
+ proc = await asyncio.create_subprocess_exec(
136
+ *argv,
137
+ cwd=str(Path(cwd).resolve()),
138
+ env=clean_env,
139
+ stdin=asyncio.subprocess.DEVNULL,
140
+ stdout=asyncio.subprocess.PIPE,
141
+ stderr=asyncio.subprocess.PIPE,
142
+ )
143
+
144
+ timed_out = False
145
+ try:
146
+ out_b, err_b = await asyncio.wait_for(
147
+ proc.communicate(), timeout=effective_timeout
148
+ )
149
+ except TimeoutError:
150
+ timed_out = True
151
+ proc.kill()
152
+ out_b, err_b = await proc.communicate()
153
+
154
+ duration_ms = int((time.perf_counter() - start) * 1000)
155
+ exit_code = -1 if timed_out else (proc.returncode if proc.returncode is not None else 1)
156
+ return CommandResult(
157
+ command=argv,
158
+ exit_code=exit_code,
159
+ stdout=out_b.decode("utf-8", errors="replace"),
160
+ stderr=err_b.decode("utf-8", errors="replace"),
161
+ timed_out=timed_out,
162
+ duration_ms=duration_ms,
163
+ )
@@ -0,0 +1,16 @@
1
+ """LLM provider adapters for runlatch."""
2
+
3
+ from runlatch.adapters.llm.anthropic import AnthropicProvider
4
+ from runlatch.adapters.llm.gemini import GeminiProvider
5
+ from runlatch.adapters.llm.mock import MockLLMProvider
6
+ from runlatch.adapters.llm.openai_compat import OpenAICompatibleProvider
7
+ from runlatch.adapters.llm.pricing import MODEL_PRICING_PER_1M, calculate_cost_usd
8
+
9
+ __all__ = [
10
+ "AnthropicProvider",
11
+ "GeminiProvider",
12
+ "MODEL_PRICING_PER_1M",
13
+ "MockLLMProvider",
14
+ "OpenAICompatibleProvider",
15
+ "calculate_cost_usd",
16
+ ]