hackbot-runtime 0.1.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.
- hackbot_runtime/__init__.py +24 -0
- hackbot_runtime/actions/__init__.py +41 -0
- hackbot_runtime/actions/action_records.py +51 -0
- hackbot_runtime/actions/agents.py +55 -0
- hackbot_runtime/actions/bugzilla.py +232 -0
- hackbot_runtime/actions/claude_sdk.py +49 -0
- hackbot_runtime/actions/email.py +152 -0
- hackbot_runtime/actions/feedback.py +60 -0
- hackbot_runtime/actions/github.py +208 -0
- hackbot_runtime/actions/mcp_server.py +39 -0
- hackbot_runtime/actions/phabricator.py +234 -0
- hackbot_runtime/actions/recorder.py +146 -0
- hackbot_runtime/actions/slack.py +101 -0
- hackbot_runtime/actions/testrail.py +206 -0
- hackbot_runtime/actions/tools.py +46 -0
- hackbot_runtime/actions/try_server.py +166 -0
- hackbot_runtime/artifacts.py +89 -0
- hackbot_runtime/changes.py +431 -0
- hackbot_runtime/claude.py +96 -0
- hackbot_runtime/codex.py +366 -0
- hackbot_runtime/config.py +82 -0
- hackbot_runtime/context.py +362 -0
- hackbot_runtime/errors.py +7 -0
- hackbot_runtime/providers.py +46 -0
- hackbot_runtime/pull_request.py +130 -0
- hackbot_runtime/results.py +13 -0
- hackbot_runtime/revision.py +238 -0
- hackbot_runtime/runtime.py +244 -0
- hackbot_runtime/searchfox.py +182 -0
- hackbot_runtime/slack_kit.py +51 -0
- hackbot_runtime/source.py +157 -0
- hackbot_runtime/tracing.py +230 -0
- hackbot_runtime/transcript.py +61 -0
- hackbot_runtime/uploader.py +76 -0
- hackbot_runtime/wif.py +359 -0
- hackbot_runtime-0.1.0.dist-info/METADATA +25 -0
- hackbot_runtime-0.1.0.dist-info/RECORD +38 -0
- hackbot_runtime-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""The single object an agent's ``main()`` receives from the runtime.
|
|
2
|
+
|
|
3
|
+
``HackbotContext`` is what an agent author touches. It answers for everything
|
|
4
|
+
the platform provides — the prepared source checkout, Firefox build paths,
|
|
5
|
+
model-provider credentials — plus the results/artifacts/actions plumbing, so the
|
|
6
|
+
author never cares how or from where those come.
|
|
7
|
+
|
|
8
|
+
Its platform fields are read from the environment (the orchestrator sets them);
|
|
9
|
+
its capability declarations come from the agent's ``hackbot.toml``
|
|
10
|
+
(:class:`HackbotConfig`), attached via :meth:`from_config`.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import datetime
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import tempfile
|
|
17
|
+
import uuid
|
|
18
|
+
from functools import cached_property
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import TYPE_CHECKING, Annotated
|
|
21
|
+
|
|
22
|
+
from pydantic import Field, PrivateAttr
|
|
23
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
24
|
+
|
|
25
|
+
from hackbot_runtime import artifacts, changes
|
|
26
|
+
from hackbot_runtime.actions import github
|
|
27
|
+
from hackbot_runtime.actions.phabricator import (
|
|
28
|
+
PATCH_ACTION_TYPES,
|
|
29
|
+
SUBMIT_PATCH_ACTION_TYPE,
|
|
30
|
+
)
|
|
31
|
+
from hackbot_runtime.actions.recorder import ActionsRecorder
|
|
32
|
+
from hackbot_runtime.actions.try_server import TRY_ACTION_TYPES, TRY_PUSH_ACTION_TYPE
|
|
33
|
+
from hackbot_runtime.config import HackbotConfig, load_config
|
|
34
|
+
from hackbot_runtime.providers import AnthropicAuth
|
|
35
|
+
from hackbot_runtime.source import checkout_commit, ensure_source_repo
|
|
36
|
+
from hackbot_runtime.uploader import SignedPolicyUploader
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from agent_tools.firefox import FirefoxContext
|
|
40
|
+
|
|
41
|
+
log = logging.getLogger("hackbot_runtime.context")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _default_run_id() -> str:
|
|
45
|
+
"""A unique, sortable id for runs that don't get one from the platform.
|
|
46
|
+
|
|
47
|
+
The orchestrator sets ``RUN_ID`` explicitly in production; this fallback
|
|
48
|
+
keeps local/compose/direct runs unique (so per-run artifact dirs don't
|
|
49
|
+
collide). The ``local-`` prefix marks it as not platform-assigned.
|
|
50
|
+
"""
|
|
51
|
+
stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d-%H%M%S")
|
|
52
|
+
return f"local-{stamp}-{uuid.uuid4().hex[:6]}"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _wip_commit_message(actions: list[dict]) -> str:
|
|
56
|
+
"""The patch title, else the try push title, for the agent's uncommitted work."""
|
|
57
|
+
for action_type in (
|
|
58
|
+
SUBMIT_PATCH_ACTION_TYPE,
|
|
59
|
+
github.SUBMIT_PATCH_ACTION_TYPE,
|
|
60
|
+
TRY_PUSH_ACTION_TYPE,
|
|
61
|
+
):
|
|
62
|
+
for action in actions:
|
|
63
|
+
if action["type"] == action_type and action["params"]["title"]:
|
|
64
|
+
return action["params"]["title"]
|
|
65
|
+
return changes.WIP_MESSAGE
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class HackbotContext(BaseSettings):
|
|
69
|
+
"""Platform capabilities + results plumbing handed to every agent's main().
|
|
70
|
+
|
|
71
|
+
`run_id` defaults to a generated unique id (the orchestrator overrides it via
|
|
72
|
+
``RUN_ID`` in production). The results-upload fields are optional so local-dev
|
|
73
|
+
runs (compose, scripts) can start the agent without a signed POST policy — in
|
|
74
|
+
that case results are written into the local artifacts dir rather than
|
|
75
|
+
uploaded.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
run_id: Annotated[str, Field(default_factory=_default_run_id)]
|
|
79
|
+
results_prefix: str = ""
|
|
80
|
+
results_policy_url: str | None = None
|
|
81
|
+
results_policy_fields: dict[str, str] = {}
|
|
82
|
+
# Base for locally-persisted artifacts when no uploader is configured
|
|
83
|
+
# (compose/direct runs). Each run is namespaced under it by run_id (see
|
|
84
|
+
# `run_artifacts_dir`). Overridable via ARTIFACTS_DIR — compose points this
|
|
85
|
+
# at a host-mounted dir; the default stays relative so it does not bake a
|
|
86
|
+
# host path into the container.
|
|
87
|
+
artifacts_dir: Path = Path("artifacts")
|
|
88
|
+
# Set on a run started by another run's `agents.start_run` action.
|
|
89
|
+
parent_run_id: str | None = None
|
|
90
|
+
# Signed download URLs for the parent's artifacts, by key. Unset locally,
|
|
91
|
+
# where the parent's artifacts are read from `artifacts_dir` instead.
|
|
92
|
+
parent_artifacts: dict[str, str] | None = None
|
|
93
|
+
|
|
94
|
+
model_config = SettingsConfigDict(extra="ignore")
|
|
95
|
+
|
|
96
|
+
# Capability declarations from hackbot.toml (not env); attached after
|
|
97
|
+
# construction via from_config()/from_config_obj().
|
|
98
|
+
_config: HackbotConfig = PrivateAttr(default_factory=HackbotConfig)
|
|
99
|
+
# The commit the source checkout started from, recorded when source_repo is
|
|
100
|
+
# prepared. Stays None for agents that never touch source, which is how
|
|
101
|
+
# publish_changes() knows there are no changes to collect.
|
|
102
|
+
_source_base: str | None = PrivateAttr(default=None)
|
|
103
|
+
# The commit the checkout was *fetched* at, which unlike `_source_base` is
|
|
104
|
+
# always a published commit the remote can resolve. The two differ once a
|
|
105
|
+
# caller seeds the checkout with local commits (see `record_source_base`),
|
|
106
|
+
# and consumers that hand a base to another service — Lando, for a try push
|
|
107
|
+
# — need this one rather than a sha that only exists in this container.
|
|
108
|
+
_published_base: str | None = PrivateAttr(default=None)
|
|
109
|
+
# The prepared checkout path + the ref it was prepared at, so the source is
|
|
110
|
+
# prepared exactly once and a conflicting re-prepare is caught.
|
|
111
|
+
_repo_path: Path | None = PrivateAttr(default=None)
|
|
112
|
+
_prepared_ref: str | None = PrivateAttr(default=None)
|
|
113
|
+
_parent_artifacts_dir: Path | None = PrivateAttr(default=None)
|
|
114
|
+
|
|
115
|
+
@classmethod
|
|
116
|
+
def from_config(cls, config_path: Path) -> HackbotContext:
|
|
117
|
+
"""Build from ``hackbot.toml`` at ``config_path`` plus env-derived fields."""
|
|
118
|
+
return cls.from_config_obj(load_config(config_path))
|
|
119
|
+
|
|
120
|
+
@classmethod
|
|
121
|
+
def from_config_obj(cls, config: HackbotConfig) -> HackbotContext:
|
|
122
|
+
"""Build from an already-parsed config plus env-derived fields."""
|
|
123
|
+
obj = cls()
|
|
124
|
+
obj._config = config
|
|
125
|
+
return obj
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def config(self) -> HackbotConfig:
|
|
129
|
+
return self._config
|
|
130
|
+
|
|
131
|
+
# --- Platform capabilities (declared in hackbot.toml) ------------- #
|
|
132
|
+
|
|
133
|
+
async def prepare_repo(
|
|
134
|
+
self, ref: str | None = None, depth: int | None = None
|
|
135
|
+
) -> Path:
|
|
136
|
+
"""Clone/refresh the source checkout (prerequisite) and return its path.
|
|
137
|
+
|
|
138
|
+
Call this once, up front; afterwards read :attr:`repo_path`. ``ref``
|
|
139
|
+
selects the checkout point (e.g. a Phabricator revision's base commit);
|
|
140
|
+
when omitted it falls back to ``SOURCE_REF`` then the ``[source].ref`` in
|
|
141
|
+
``hackbot.toml``. ``depth`` bounds the shallow fetch (agents that need
|
|
142
|
+
history — e.g. build-repair — pass it explicitly). The path comes from
|
|
143
|
+
``SOURCE_REPO`` or ``[source].checkout_path``. Passing a ``ref`` that
|
|
144
|
+
conflicts with an already-prepared checkout raises.
|
|
145
|
+
"""
|
|
146
|
+
if self._config.source is None:
|
|
147
|
+
raise RuntimeError(
|
|
148
|
+
"This agent did not declare a [source] in hackbot.toml; "
|
|
149
|
+
"no source repository is available."
|
|
150
|
+
)
|
|
151
|
+
resolved_ref = ref or os.environ.get("SOURCE_REF") or self._config.source.ref
|
|
152
|
+
if self._repo_path is not None:
|
|
153
|
+
if ref is not None and ref != self._prepared_ref:
|
|
154
|
+
raise RuntimeError(
|
|
155
|
+
f"source already prepared at ref {self._prepared_ref!r}; "
|
|
156
|
+
f"cannot re-prepare at {ref!r} (prepare it before first use)"
|
|
157
|
+
)
|
|
158
|
+
return self._repo_path
|
|
159
|
+
|
|
160
|
+
env_path = os.environ.get("SOURCE_REPO")
|
|
161
|
+
path = Path(env_path) if env_path else self._config.source.checkout_path
|
|
162
|
+
ensure_source_repo(path, self._config.source.repo_url, resolved_ref, depth)
|
|
163
|
+
# Record where the agent starts editing, so publish_changes() can later
|
|
164
|
+
# diff the final tree against it. Best-effort: a failure here must not
|
|
165
|
+
# break the agent's access to source — it only disables change capture.
|
|
166
|
+
try:
|
|
167
|
+
self._source_base = self._published_base = changes.base_commit(path)
|
|
168
|
+
except Exception:
|
|
169
|
+
log.warning("Could not record source base commit at %s", path)
|
|
170
|
+
self._repo_path = path
|
|
171
|
+
self._prepared_ref = resolved_ref
|
|
172
|
+
return path
|
|
173
|
+
|
|
174
|
+
def record_source_base(self) -> None:
|
|
175
|
+
"""Re-record the commit the agent starts editing from (current HEAD).
|
|
176
|
+
|
|
177
|
+
:meth:`prepare_repo` records it at checkout time. A caller that then
|
|
178
|
+
seeds the checkout with commits that are not the agent's work — e.g. the
|
|
179
|
+
unlanded ancestors of a stacked Phabricator revision, see
|
|
180
|
+
``revision.checkout_revision`` — calls this afterwards so
|
|
181
|
+
:meth:`publish_changes` collects only what the agent itself did.
|
|
182
|
+
"""
|
|
183
|
+
self._source_base = changes.base_commit(self.repo_path)
|
|
184
|
+
|
|
185
|
+
def checkout(self, ref: str) -> str:
|
|
186
|
+
"""Move the prepared checkout to ``ref`` and start the agent's edits there.
|
|
187
|
+
|
|
188
|
+
For work that belongs on a different commit than the one the source was
|
|
189
|
+
prepared at. What the run publishes -- its patch, its Phabricator diff, its
|
|
190
|
+
try push -- is then taken against ``ref``, so a revision built from it
|
|
191
|
+
stacks on that commit. Returns the full sha. The tree must be clean.
|
|
192
|
+
|
|
193
|
+
``ref`` must be a commit the clone already holds, and it becomes the base
|
|
194
|
+
rather than part of the diff. That is the difference from
|
|
195
|
+
:func:`hackbot_runtime.revision.checkout_revision`, which rebuilds a
|
|
196
|
+
revision from its Phabricator diffs so the agent can revise it.
|
|
197
|
+
"""
|
|
198
|
+
checkout_commit(self.repo_path, ref)
|
|
199
|
+
self._source_base = self._published_base = changes.base_commit(self.repo_path)
|
|
200
|
+
return self._source_base
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def repo_path(self) -> Path:
|
|
204
|
+
"""The prepared source checkout path. Call :meth:`prepare_repo` first."""
|
|
205
|
+
if self._repo_path is None:
|
|
206
|
+
raise RuntimeError(
|
|
207
|
+
"source repo not prepared; call prepare_repo() before repo_path"
|
|
208
|
+
)
|
|
209
|
+
return self._repo_path
|
|
210
|
+
|
|
211
|
+
@cached_property
|
|
212
|
+
def firefox(self) -> FirefoxContext:
|
|
213
|
+
"""Firefox build paths derived from the prepared source checkout.
|
|
214
|
+
|
|
215
|
+
Importing ``agent_tools.firefox`` lazily keeps the base runtime free of
|
|
216
|
+
the ``agent-tools[firefox]`` extra for agents that don't need it.
|
|
217
|
+
"""
|
|
218
|
+
if self._config.firefox is None or not self._config.firefox.enabled:
|
|
219
|
+
raise RuntimeError(
|
|
220
|
+
"This agent did not declare an enabled [firefox] in "
|
|
221
|
+
"hackbot.toml; no Firefox build is available."
|
|
222
|
+
)
|
|
223
|
+
from agent_tools.firefox import FirefoxContext
|
|
224
|
+
|
|
225
|
+
return FirefoxContext.from_source_repo(
|
|
226
|
+
self.repo_path, objdir=self._config.firefox.objdir
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
@cached_property
|
|
230
|
+
def anthropic(self) -> AnthropicAuth:
|
|
231
|
+
"""Anthropic credentials (validated on first key access)."""
|
|
232
|
+
return AnthropicAuth()
|
|
233
|
+
|
|
234
|
+
# --- Results / artifacts / actions plumbing ----------------------- #
|
|
235
|
+
|
|
236
|
+
@cached_property
|
|
237
|
+
def uploader(self) -> SignedPolicyUploader | None:
|
|
238
|
+
if not self.results_policy_url:
|
|
239
|
+
return None
|
|
240
|
+
return SignedPolicyUploader(
|
|
241
|
+
url=self.results_policy_url,
|
|
242
|
+
fields=self.results_policy_fields,
|
|
243
|
+
prefix=self.results_prefix,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
@cached_property
|
|
247
|
+
def run_artifacts_dir(self) -> Path:
|
|
248
|
+
"""Per-run local artifacts directory: ``artifacts_dir / run_id``."""
|
|
249
|
+
return self.artifacts_dir / self.run_id
|
|
250
|
+
|
|
251
|
+
@cached_property
|
|
252
|
+
def log_path(self) -> Path:
|
|
253
|
+
"""A writable path for the agent's run log; published by the runtime.
|
|
254
|
+
|
|
255
|
+
The parent dir is created on first access (so a ``Reporter`` can open the
|
|
256
|
+
file straight away). Agents that never write a log just leave it absent,
|
|
257
|
+
and :meth:`publish_log` becomes a no-op.
|
|
258
|
+
"""
|
|
259
|
+
return Path(tempfile.mkdtemp(prefix=f"hackbot-{self.run_id}-")) / "agent.log"
|
|
260
|
+
|
|
261
|
+
def fetch_parent_artifacts(self) -> None:
|
|
262
|
+
"""Make the parent run's artifacts available; called by the runtime."""
|
|
263
|
+
if self.parent_artifacts is None:
|
|
264
|
+
self._parent_artifacts_dir = self.artifacts_dir / self.parent_run_id
|
|
265
|
+
return
|
|
266
|
+
dest = Path(tempfile.mkdtemp(prefix=f"hackbot-{self.parent_run_id}-"))
|
|
267
|
+
artifacts.download_all(self.parent_artifacts, dest)
|
|
268
|
+
self._parent_artifacts_dir = dest
|
|
269
|
+
|
|
270
|
+
@property
|
|
271
|
+
def parent_artifacts_dir(self) -> Path:
|
|
272
|
+
"""The parent run's artifacts, under the keys it published them with."""
|
|
273
|
+
if self._parent_artifacts_dir is None:
|
|
274
|
+
raise RuntimeError("this run was not started by another run")
|
|
275
|
+
return self._parent_artifacts_dir
|
|
276
|
+
|
|
277
|
+
@cached_property
|
|
278
|
+
def actions(self) -> ActionsRecorder:
|
|
279
|
+
return ActionsRecorder(self.uploader, artifacts_dir=self.run_artifacts_dir)
|
|
280
|
+
|
|
281
|
+
def publish_file(
|
|
282
|
+
self, key: str, path: Path, content_type: str | None = None
|
|
283
|
+
) -> str:
|
|
284
|
+
"""Upload ``path`` under ``key``, else copy it into the artifacts dir."""
|
|
285
|
+
return artifacts.publish_file(
|
|
286
|
+
self.uploader, self.run_artifacts_dir, key, path, content_type
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
def publish_json(self, key: str, payload: dict) -> str:
|
|
290
|
+
"""Upload ``payload`` JSON under ``key``, else write it to artifacts."""
|
|
291
|
+
return artifacts.publish_json(
|
|
292
|
+
self.uploader, self.run_artifacts_dir, key, payload
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
@property
|
|
296
|
+
def source_changed(self) -> bool:
|
|
297
|
+
"""Whether this run will publish a patch, for a notification to gate on.
|
|
298
|
+
|
|
299
|
+
Read-only: the patch itself belongs to the apply step, which reads the
|
|
300
|
+
published artifact (see hackbot-api's ``app/action_handlers/email_handler.py``).
|
|
301
|
+
"""
|
|
302
|
+
if self._repo_path is None or self._source_base is None:
|
|
303
|
+
return False
|
|
304
|
+
return changes.has_changes(self._repo_path, self._source_base)
|
|
305
|
+
|
|
306
|
+
def publish_changes(
|
|
307
|
+
self,
|
|
308
|
+
patch_key: str = changes.PATCH_ARTIFACT,
|
|
309
|
+
meta_key: str = "changes/changes.json",
|
|
310
|
+
phabricator_diff_key: str = "changes/phabricator_diff.json",
|
|
311
|
+
try_push_key: str = "changes/try_push.json",
|
|
312
|
+
github_commit_key: str = "changes/github_commit.json",
|
|
313
|
+
) -> str | None:
|
|
314
|
+
"""Collect the agent's source-tree changes and publish them as artifacts."""
|
|
315
|
+
if self._source_base is None:
|
|
316
|
+
return None
|
|
317
|
+
change_set = changes.collect(
|
|
318
|
+
self.repo_path,
|
|
319
|
+
self._source_base,
|
|
320
|
+
self._config.source.repo_url,
|
|
321
|
+
message=_wip_commit_message(self.actions.actions),
|
|
322
|
+
)
|
|
323
|
+
if change_set is None:
|
|
324
|
+
return None
|
|
325
|
+
artifacts.publish_bytes(
|
|
326
|
+
self.uploader,
|
|
327
|
+
self.run_artifacts_dir,
|
|
328
|
+
patch_key,
|
|
329
|
+
change_set.patch,
|
|
330
|
+
"text/x-patch",
|
|
331
|
+
)
|
|
332
|
+
self.publish_json(meta_key, change_set.metadata)
|
|
333
|
+
|
|
334
|
+
recorded_types = {action["type"] for action in self.actions.actions}
|
|
335
|
+
|
|
336
|
+
if recorded_types & PATCH_ACTION_TYPES:
|
|
337
|
+
diff_payload = changes.build_phabricator_diff(
|
|
338
|
+
self.repo_path, self._source_base, self._config.source.repo_url
|
|
339
|
+
)
|
|
340
|
+
if diff_payload is not None:
|
|
341
|
+
self.publish_json(phabricator_diff_key, diff_payload)
|
|
342
|
+
|
|
343
|
+
if recorded_types & github.PATCH_ACTION_TYPES:
|
|
344
|
+
# From the published base, like the try push: the commit is created
|
|
345
|
+
# on GitHub on top of it, so it has to be a commit the repository
|
|
346
|
+
# already has.
|
|
347
|
+
github_payload = changes.build_github_commit(
|
|
348
|
+
self.repo_path, self._published_base, self._config.source.repo_url
|
|
349
|
+
)
|
|
350
|
+
if github_payload is not None:
|
|
351
|
+
self.publish_json(github_commit_key, github_payload)
|
|
352
|
+
|
|
353
|
+
if recorded_types & TRY_ACTION_TYPES:
|
|
354
|
+
# From the *published* base, not `_source_base`: Lando has to
|
|
355
|
+
# resolve the base commit in its own clone, and it pushes the patch
|
|
356
|
+
# series onto it — so the series has to carry any locally-seeded
|
|
357
|
+
# commits (a stacked revision's ancestors) rather than assume them.
|
|
358
|
+
try_payload = changes.build_try_push(self.repo_path, self._published_base)
|
|
359
|
+
if try_payload is not None:
|
|
360
|
+
self.publish_json(try_push_key, try_payload)
|
|
361
|
+
|
|
362
|
+
return patch_key
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
class AgentError(Exception):
|
|
2
|
+
"""Raise from an agent's ``main()`` to fail the run with a clear message.
|
|
3
|
+
|
|
4
|
+
The runtime records the message as the run's ``error`` in ``summary.json``
|
|
5
|
+
and exits non-zero. Any other exception fails the run too — ``AgentError``
|
|
6
|
+
just reads as a deliberate, expected failure rather than a crash.
|
|
7
|
+
"""
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Credentials the runtime provides to agents.
|
|
2
|
+
|
|
3
|
+
The runtime owns where credentials come from so agents don't reach into the
|
|
4
|
+
environment themselves. Today only Anthropic is wired; the :class:`Provider`
|
|
5
|
+
protocol leaves room to add others (Vertex, OpenAI, ...) without changing the
|
|
6
|
+
agent-facing surface.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from typing import Protocol, runtime_checkable
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ProviderError(RuntimeError):
|
|
14
|
+
"""A required credential for a provider is missing or invalid."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@runtime_checkable
|
|
18
|
+
class Provider(Protocol):
|
|
19
|
+
"""A credentialed model/service provider the runtime can hand to an agent."""
|
|
20
|
+
|
|
21
|
+
name: str
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def api_key(self) -> str: ...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AnthropicAuth:
|
|
28
|
+
"""Anthropic credentials, read from the environment and validated on access.
|
|
29
|
+
|
|
30
|
+
Exposes the API key explicitly (rather than relying on the SDK implicitly
|
|
31
|
+
reading the env) so a missing key fails fast with a clear message instead of
|
|
32
|
+
surfacing as an opaque error deep inside a request.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
name = "anthropic"
|
|
36
|
+
env_var = "ANTHROPIC_API_KEY"
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def api_key(self) -> str:
|
|
40
|
+
key = os.environ.get(self.env_var)
|
|
41
|
+
if not key:
|
|
42
|
+
raise ProviderError(
|
|
43
|
+
f"{self.env_var} is not set; the runtime cannot provide "
|
|
44
|
+
"Anthropic credentials to this agent."
|
|
45
|
+
)
|
|
46
|
+
return key
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Check an agent's source tree out at a GitHub pull request's head."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import subprocess
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from hackbot_runtime.context import HackbotContext
|
|
10
|
+
|
|
11
|
+
log = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
# How much history to fetch, from both the head and the base, while looking for
|
|
14
|
+
# the commit the pull request branched from. The source is a shallow clone, so
|
|
15
|
+
# that commit is usually missing at first. The depth doubles each round, so a PR
|
|
16
|
+
# close to its base costs a few commits, and one that is far behind (or shares
|
|
17
|
+
# no history with it) stops at a bounded fetch instead of pulling the
|
|
18
|
+
# repository's whole history.
|
|
19
|
+
_FIRST_DEPTH = 16
|
|
20
|
+
_MAX_DEPTH = 4096
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def checkout_pull_request(
|
|
24
|
+
ctx: HackbotContext,
|
|
25
|
+
number: int,
|
|
26
|
+
base: str,
|
|
27
|
+
head_sha: str | None = None,
|
|
28
|
+
) -> str:
|
|
29
|
+
"""Prepare the source so it matches pull request ``number`` before the agent runs.
|
|
30
|
+
|
|
31
|
+
The checkout is left at the PR's head, committed and clean: the PR's commits
|
|
32
|
+
are the agent's starting point, not its work, so what the run publishes is
|
|
33
|
+
only what the agent changed on top of them (which is also what a later push
|
|
34
|
+
to the PR's branch would add).
|
|
35
|
+
|
|
36
|
+
``base`` is the branch or commit the PR targets (its ``base.ref`` or
|
|
37
|
+
``base.sha``). It is fetched with enough history on both sides for git to
|
|
38
|
+
find the commit the PR branched from. Use the returned merge base with
|
|
39
|
+
``git diff <merge-base> HEAD`` to see the same change as GitHub's "Files
|
|
40
|
+
changed" tab, or ``git log <merge-base>..HEAD`` to list the PR's commits.
|
|
41
|
+
|
|
42
|
+
``head_sha``, when given, is the full sha the caller saw the PR at (for
|
|
43
|
+
example when the run was requested). If the PR has been pushed to since, this
|
|
44
|
+
raises rather than working on code nobody asked about.
|
|
45
|
+
|
|
46
|
+
The PR must belong to the agent's source repository (``[source].repo_url``),
|
|
47
|
+
and that repository must be readable without credentials.
|
|
48
|
+
|
|
49
|
+
Returns the merge base: the commit the PR's changes are measured from.
|
|
50
|
+
|
|
51
|
+
Raises :class:`RuntimeError` if the PR or its base cannot be fetched, the
|
|
52
|
+
head is not ``head_sha``, or no common history with the base turns up, so
|
|
53
|
+
the run fails visibly rather than working on the wrong tree.
|
|
54
|
+
"""
|
|
55
|
+
head_ref = f"refs/pull/{number}/head"
|
|
56
|
+
try:
|
|
57
|
+
# Must run before anything else touches the source (prepare_repo raises
|
|
58
|
+
# otherwise). It also records the head as the agent's starting point.
|
|
59
|
+
repo = await ctx.prepare_repo(ref=head_ref)
|
|
60
|
+
except subprocess.CalledProcessError as exc:
|
|
61
|
+
raise RuntimeError(
|
|
62
|
+
f"Could not fetch pull request #{number} ({head_ref}). Check that it "
|
|
63
|
+
"exists in the agent's source repository."
|
|
64
|
+
) from exc
|
|
65
|
+
|
|
66
|
+
head = _git(repo, "rev-parse", "HEAD")
|
|
67
|
+
if head_sha is not None and head != head_sha:
|
|
68
|
+
raise RuntimeError(
|
|
69
|
+
f"Pull request #{number} is at {head}, not {head_sha}: it was pushed "
|
|
70
|
+
"to after this run was requested. Request a new run to work on the "
|
|
71
|
+
"new head."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# prepare_repo resets tracked files, but reused checkouts can retain untracked files.
|
|
75
|
+
_git(repo, "clean", "-fd")
|
|
76
|
+
if _git(repo, "status", "--porcelain"):
|
|
77
|
+
raise RuntimeError(f"Pull request #{number} checkout is not clean")
|
|
78
|
+
|
|
79
|
+
# Fetching the base with --depth on a full clone would truncate its history,
|
|
80
|
+
# so only stay shallow if the checkout already is.
|
|
81
|
+
shallow = _git(repo, "rev-parse", "--is-shallow-repository") == "true"
|
|
82
|
+
try:
|
|
83
|
+
_fetch(repo, base, depth=1 if shallow else None)
|
|
84
|
+
except subprocess.CalledProcessError as exc:
|
|
85
|
+
raise RuntimeError(
|
|
86
|
+
f"Could not fetch {base!r}, the base of pull request #{number}: "
|
|
87
|
+
f"{exc.stderr.strip()}"
|
|
88
|
+
) from exc
|
|
89
|
+
base_sha = _git(repo, "rev-parse", "FETCH_HEAD")
|
|
90
|
+
log.info("Checked out pull request #%s at %s (base %s)", number, head, base_sha)
|
|
91
|
+
|
|
92
|
+
merge_base = _merge_base(repo, base_sha, head)
|
|
93
|
+
depth = _FIRST_DEPTH
|
|
94
|
+
while merge_base is None and shallow and depth <= _MAX_DEPTH:
|
|
95
|
+
# Both sides, by sha: the shared commit is behind the head by the PR's
|
|
96
|
+
# own commits, and behind the base by whatever landed since the PR
|
|
97
|
+
# branched. Fetching shas rather than refs keeps either side from moving
|
|
98
|
+
# under us mid-search.
|
|
99
|
+
_fetch(repo, head, base_sha, depth=depth)
|
|
100
|
+
merge_base = _merge_base(repo, base_sha, head)
|
|
101
|
+
depth *= 2
|
|
102
|
+
|
|
103
|
+
if merge_base is None:
|
|
104
|
+
raise RuntimeError(
|
|
105
|
+
f"Pull request #{number} shares no history with its base {base!r} "
|
|
106
|
+
f"within {_MAX_DEPTH} commits. If it is that far behind, it has to "
|
|
107
|
+
"be rebased before hackbot can work on it."
|
|
108
|
+
)
|
|
109
|
+
return merge_base
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _git(repo: Path, *args: str) -> str:
|
|
113
|
+
return subprocess.run(
|
|
114
|
+
["git", "-C", str(repo), *args], check=True, capture_output=True, text=True
|
|
115
|
+
).stdout.strip()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _fetch(repo: Path, *refs: str, depth: int | None) -> None:
|
|
119
|
+
depth_flag = [f"--depth={depth}"] if depth is not None else []
|
|
120
|
+
_git(repo, "fetch", "-q", *depth_flag, "origin", *refs)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _merge_base(repo: Path, base: str, head: str) -> str | None:
|
|
124
|
+
"""The commit ``head`` branched from ``base`` at, if the checkout holds it."""
|
|
125
|
+
result = subprocess.run(
|
|
126
|
+
["git", "-C", str(repo), "merge-base", base, head],
|
|
127
|
+
capture_output=True,
|
|
128
|
+
text=True,
|
|
129
|
+
)
|
|
130
|
+
return result.stdout.strip() if result.returncode == 0 else None
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Base result model for hackbot agents.
|
|
2
|
+
|
|
3
|
+
An agent's ``main()`` may return a subclass of :class:`HackbotAgentResult`; the
|
|
4
|
+
runtime serializes it into ``summary.json``'s ``findings``. Framework-neutral —
|
|
5
|
+
plain pydantic, no claude-agent-sdk dependency.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class HackbotAgentResult(BaseModel):
|
|
12
|
+
num_turns: int
|
|
13
|
+
total_cost_usd: float | None = None
|