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.
Files changed (38) hide show
  1. hackbot_runtime/__init__.py +24 -0
  2. hackbot_runtime/actions/__init__.py +41 -0
  3. hackbot_runtime/actions/action_records.py +51 -0
  4. hackbot_runtime/actions/agents.py +55 -0
  5. hackbot_runtime/actions/bugzilla.py +232 -0
  6. hackbot_runtime/actions/claude_sdk.py +49 -0
  7. hackbot_runtime/actions/email.py +152 -0
  8. hackbot_runtime/actions/feedback.py +60 -0
  9. hackbot_runtime/actions/github.py +208 -0
  10. hackbot_runtime/actions/mcp_server.py +39 -0
  11. hackbot_runtime/actions/phabricator.py +234 -0
  12. hackbot_runtime/actions/recorder.py +146 -0
  13. hackbot_runtime/actions/slack.py +101 -0
  14. hackbot_runtime/actions/testrail.py +206 -0
  15. hackbot_runtime/actions/tools.py +46 -0
  16. hackbot_runtime/actions/try_server.py +166 -0
  17. hackbot_runtime/artifacts.py +89 -0
  18. hackbot_runtime/changes.py +431 -0
  19. hackbot_runtime/claude.py +96 -0
  20. hackbot_runtime/codex.py +366 -0
  21. hackbot_runtime/config.py +82 -0
  22. hackbot_runtime/context.py +362 -0
  23. hackbot_runtime/errors.py +7 -0
  24. hackbot_runtime/providers.py +46 -0
  25. hackbot_runtime/pull_request.py +130 -0
  26. hackbot_runtime/results.py +13 -0
  27. hackbot_runtime/revision.py +238 -0
  28. hackbot_runtime/runtime.py +244 -0
  29. hackbot_runtime/searchfox.py +182 -0
  30. hackbot_runtime/slack_kit.py +51 -0
  31. hackbot_runtime/source.py +157 -0
  32. hackbot_runtime/tracing.py +230 -0
  33. hackbot_runtime/transcript.py +61 -0
  34. hackbot_runtime/uploader.py +76 -0
  35. hackbot_runtime/wif.py +359 -0
  36. hackbot_runtime-0.1.0.dist-info/METADATA +25 -0
  37. hackbot_runtime-0.1.0.dist-info/RECORD +38 -0
  38. hackbot_runtime-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,51 @@
1
+ """Utilities for building the Block Kit payloads Hackbot's Slack messages carry.
2
+
3
+ https://docs.slack.dev/reference/block-kit/block-elements
4
+ """
5
+
6
+ import json
7
+ from typing import Any
8
+
9
+ from slack_sdk.models.blocks import ButtonElement, ConfirmObject
10
+
11
+
12
+ def create_start_agent_run_button(
13
+ label: str,
14
+ *,
15
+ agent_name: str,
16
+ inputs: dict[str, Any],
17
+ dedupe_key: str,
18
+ apply_run_id: str | None = None,
19
+ confirm: ConfirmObject | None = None,
20
+ style: str | None = None,
21
+ ) -> ButtonElement:
22
+ """A button that starts one ``agent_name`` run, and only ever one.
23
+
24
+ ``dedupe_key`` is required, because Slack cannot un-render a button: a client
25
+ still holding the message can click it again, and two readers can click at
26
+ once. The key is what makes the button a one-shot.
27
+
28
+ ``apply_run_id`` names a run whose pending actions are applied *before* the
29
+ new run starts, for a button offered on a result still held for review: the
30
+ press is the review, so what it approves has to land before the agent that
31
+ reads it starts reading.
32
+
33
+ ``confirm`` is Slack's confirmation dialog, worth one for a button whose run
34
+ writes somewhere public: a click is the whole of the interaction, and there
35
+ is no undo on the other side of it.
36
+ """
37
+ value: dict[str, Any] = {
38
+ "agent_name": agent_name,
39
+ "inputs": inputs,
40
+ "dedupe_key": dedupe_key,
41
+ }
42
+ if apply_run_id is not None:
43
+ value["apply_run_id"] = apply_run_id
44
+
45
+ return ButtonElement(
46
+ text=label,
47
+ action_id=f"start_agent_run:{agent_name}:{dedupe_key}",
48
+ value=json.dumps(value),
49
+ style=style,
50
+ confirm=confirm,
51
+ )
@@ -0,0 +1,157 @@
1
+ """Prepare a source checkout for agents that operate on a code repository."""
2
+
3
+ import logging
4
+ import os
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import BinaryIO
11
+
12
+ from google.cloud import storage
13
+
14
+ log = logging.getLogger("hackbot_runtime.source")
15
+
16
+ _GITHUB_REPO = re.compile(r"https://github\.com/([^/]+/[^/]+?)(?:\.git)?")
17
+
18
+
19
+ def _git(source_repo: Path, *args: str) -> None:
20
+ subprocess.run(
21
+ ["git", "-C", str(source_repo), *args],
22
+ check=True,
23
+ stdout=sys.stderr,
24
+ stderr=sys.stderr,
25
+ )
26
+
27
+
28
+ def _download(bucket: str, name: str, out: BinaryIO) -> None:
29
+ """Write ``gs://bucket/name`` to ``out``, checking its checksum."""
30
+ # crc32c: large uploads are composite objects, which have no md5.
31
+ storage.Client().bucket(bucket).blob(name).download_to_file(out, checksum="crc32c")
32
+
33
+
34
+ def _check_out_snapshot(
35
+ source_repo: Path, bucket: str, name: str, fetch_target: str
36
+ ) -> None:
37
+ log.info("restoring %s from gs://%s/%s", source_repo, bucket, name)
38
+ source_repo.mkdir(parents=True, exist_ok=True)
39
+ # Stream straight into tar, so the tar never takes disk space of its own.
40
+ tar = subprocess.Popen(
41
+ ["tar", "-x", "-f", "-", "-C", str(source_repo)], stdin=subprocess.PIPE
42
+ )
43
+ try:
44
+ _download(bucket, name, tar.stdin)
45
+ finally:
46
+ tar.stdin.close()
47
+ returncode = tar.wait()
48
+ if returncode:
49
+ raise subprocess.CalledProcessError(returncode, tar.args)
50
+ log.info("snapshot unpacked; fetching %s", fetch_target)
51
+ # Name the unpacked repository, so a tar without .git fails here instead of
52
+ # git finding an enclosing repository. Relative to -C, so relative paths work.
53
+ git_dir = ("--git-dir=.git", "--work-tree=.")
54
+ _git(source_repo, *git_dir, "fetch", "origin", fetch_target)
55
+ _git(source_repo, *git_dir, "checkout", "-q", "-f", "FETCH_HEAD")
56
+ log.info("snapshot checkout complete")
57
+
58
+
59
+ def _restore_snapshot(source_repo: Path, repo_url: str, fetch_target: str) -> bool:
60
+ """Check out ``fetch_target`` from the full-history snapshot, if one is set up.
61
+
62
+ The snapshot is a daily ``.git`` tar (``SOURCE_SNAPSHOT_BUCKET``); fetching
63
+ then adds only newer commits. Returns False, leaving nothing behind, when
64
+ there is none or any step fails, so the caller can clone instead.
65
+ """
66
+ bucket = os.environ.get("SOURCE_SNAPSHOT_BUCKET")
67
+ match = _GITHUB_REPO.fullmatch(repo_url)
68
+ # Only into an empty directory, so a failure can remove all of it.
69
+ if not bucket or not match or (source_repo.exists() and any(source_repo.iterdir())):
70
+ return False
71
+ name = f"github/{match[1]}.tar"
72
+ try:
73
+ _check_out_snapshot(source_repo, bucket, name, fetch_target)
74
+ except Exception:
75
+ # Any failure (download, checksum, tar, git) is recoverable by cloning.
76
+ log.warning("snapshot restore failed; cloning instead", exc_info=True)
77
+ shutil.rmtree(source_repo, ignore_errors=True)
78
+ return False
79
+ return True
80
+
81
+
82
+ def _update_checkout(source_repo: Path, fetch_target: str, depth: int) -> None:
83
+ """Refresh an existing checkout to ``fetch_target``, repairing a broken one."""
84
+ git_dir = source_repo / ".git"
85
+ # An earlier run killed mid-fetch (e.g. the container was stopped) leaves
86
+ # stale lock files behind. Since each run drives git sequentially, any lock
87
+ # present at startup is stale and safe to remove.
88
+ for lock in (git_dir / "shallow.lock", git_dir / "index.lock"):
89
+ if lock.exists():
90
+ log.warning("removing stale git lock %s", lock)
91
+ lock.unlink()
92
+ status = subprocess.run(
93
+ ["git", "-C", str(source_repo), "status", "--porcelain"],
94
+ check=True,
95
+ capture_output=True,
96
+ text=True,
97
+ )
98
+ # A healthy fresh shallow clone has an empty status; a broken checkout shows
99
+ # thousands of missing-file "D" entries.
100
+ if status.stdout.strip():
101
+ log.warning("source at %s is incomplete; restoring working tree", source_repo)
102
+ _git(source_repo, "restore", "--source=HEAD", ":/")
103
+ log.info("updating source at %s (shallow fetch %s)", source_repo, fetch_target)
104
+ _git(source_repo, "fetch", f"--depth={depth}", "origin", fetch_target)
105
+ _git(source_repo, "reset", "--hard", "FETCH_HEAD")
106
+
107
+
108
+ def _shallow_clone(
109
+ source_repo: Path, repo_url: str, ref: str | None, depth: int
110
+ ) -> None:
111
+ source_repo.mkdir(parents=True, exist_ok=True)
112
+ if ref:
113
+ # A bare clone can't fetch an arbitrary commit directly, so init an empty
114
+ # repo and shallow-fetch just the requested ref.
115
+ log.info("cloning %s (shallow) to %s at ref %s", repo_url, source_repo, ref)
116
+ _git(source_repo, "init", "-q")
117
+ _git(source_repo, "remote", "add", "origin", repo_url)
118
+ _git(source_repo, "fetch", f"--depth={depth}", "origin", ref)
119
+ _git(source_repo, "checkout", "-q", "FETCH_HEAD")
120
+ else:
121
+ log.info("cloning %s (shallow) to %s", repo_url, source_repo)
122
+ _git(source_repo, "clone", f"--depth={depth}", repo_url, ".")
123
+ log.info("shallow clone complete")
124
+
125
+
126
+ def ensure_source_repo(
127
+ source_repo: Path, repo_url: str, ref: str | None = None, depth: int | None = None
128
+ ) -> None:
129
+ """Ensure a checkout of ``repo_url`` exists at ``source_repo``.
130
+
131
+ Idempotent: an existing checkout is shallow-fetched and hard-reset to the
132
+ requested ``ref`` (``origin/HEAD`` when ``ref`` is None), recovering from a
133
+ partial checkout left by an earlier failed run. A fresh checkout starts from
134
+ the full-history snapshot when one is set up, and is otherwise a shallow
135
+ clone.
136
+
137
+ When ``ref`` is set (a commit/branch/tag), the repo is pinned there — useful
138
+ for agents that must operate on a specific historical commit (e.g. a build
139
+ failure commit) rather than the tip of the default branch.
140
+ """
141
+ # Every path fetches this ref, so a pinned commit is fetchable even when it
142
+ # is not on HEAD.
143
+ fetch_target = ref or "HEAD"
144
+ # A pinned commit needs its parent too so the commit's own diff can be
145
+ # computed (e.g. `git show <commit>`). An explicit ``depth`` (e.g. to cover
146
+ # every commit in a push so each is showable) overrides the default.
147
+ if depth is None:
148
+ depth = 2 if ref else 1
149
+ if (source_repo / ".git").exists():
150
+ _update_checkout(source_repo, fetch_target, depth)
151
+ elif not _restore_snapshot(source_repo, repo_url, fetch_target):
152
+ _shallow_clone(source_repo, repo_url, ref, depth)
153
+
154
+
155
+ def checkout_commit(source_repo: Path, ref: str) -> None:
156
+ """Detach the checkout at ``ref``, which the shallow clone must already hold."""
157
+ _git(source_repo, "checkout", "-q", "--detach", ref)
@@ -0,0 +1,230 @@
1
+ """Weights & Biases Weave tracing for all hackbot agents.
2
+
3
+ ``weave.init()`` autopatches the Claude Agent SDK, so calling it once in the
4
+ runtime before an agent's ``main()`` runs captures every query, model response,
5
+ and tool call as a trace with no per-agent instrumentation. It authenticates
6
+ either from ``WANDB_API_KEY`` (local/dev) or, in deployment, from the short-lived
7
+ identity token that :mod:`hackbot_runtime.wif` writes -- so the agent
8
+ container needs no long-lived W&B credential. Tracing is opt-in: it activates
9
+ only when one of those is present, and never fails the run if Weave can't start.
10
+
11
+ The SDK integration otherwise labels every agent ``claude_agent_sdk``;
12
+ ``agent_name_override`` relabels the spans with the running agent's name so the
13
+ dashboard can tell the agents apart. Subagents get the parent agent's name too,
14
+ so they don't show up as separate agents, are tagged with their own name, and
15
+ get their token usage recorded.
16
+ """
17
+
18
+ import contextlib
19
+ import inspect
20
+ import logging
21
+ import os
22
+ from collections.abc import Callable, Iterator
23
+ from pathlib import Path
24
+ from typing import TYPE_CHECKING, Any
25
+
26
+ from opentelemetry import trace as otel_trace
27
+ from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
28
+
29
+ from hackbot_runtime import wif
30
+
31
+ if TYPE_CHECKING:
32
+ from opentelemetry.context import Context
33
+ from opentelemetry.sdk.trace import Span
34
+
35
+ log = logging.getLogger("hackbot_runtime")
36
+
37
+ # Weave project traces land in when the deploy doesn't set WEAVE_PROJECT. Accepts
38
+ # either "project" or "entity/project".
39
+ DEFAULT_WEAVE_PROJECT = "hackbot-test"
40
+
41
+ # Weave's tagging namespace: the server surfaces this as `attributes.hackbot.run_id`
42
+ # on every call, which the Hackbot UI uses to link a run to its traces.
43
+ RUN_ID_SPAN_ATTRIBUTE = "wandb.attributes.hackbot.run_id"
44
+ SUBAGENT_SPAN_ATTRIBUTE = "wandb.attributes.hackbot.subagent"
45
+
46
+ # ``ResultMessage.usage`` keys -> ``ResultMessage.model_usage`` keys.
47
+ _MODEL_USAGE_KEYS = {
48
+ "input_tokens": "inputTokens",
49
+ "cache_read_input_tokens": "cacheReadInputTokens",
50
+ "cache_creation_input_tokens": "cacheCreationInputTokens",
51
+ "output_tokens": "outputTokens",
52
+ }
53
+
54
+
55
+ def resolve_agent_name(entrypoint: Callable) -> str:
56
+ """The running agent's name, derived from its ``main()`` source file.
57
+
58
+ Every agent's ``main()`` lives in ``hackbot_agents/<agent>/__main__.py``, so
59
+ the directory holding it is the agent's package. We read the source file path
60
+ (not ``__module__``, which is just ``"__main__"`` under ``python -m``) and
61
+ take that directory name, normalized to the canonical hyphenated form
62
+ (``build_repair`` -> ``build-repair``).
63
+ """
64
+ source = inspect.getfile(entrypoint)
65
+ return Path(source).parent.name.replace("_", "-")
66
+
67
+
68
+ def _init_weave(config: wif.WandbWifSettings, project: str | None = None) -> bool:
69
+ """Initialize Weave when credentials are available; return whether enabled.
70
+
71
+ Credentials come from ``WANDB_API_KEY`` (local) or federation (deployment).
72
+ No-op when neither is configured.
73
+ The project is ``WEAVE_PROJECT``, else ``project``, the agent's configured one.
74
+ """
75
+ if not (config.enabled or config.api_key):
76
+ return False
77
+
78
+ project = os.environ.get("WEAVE_PROJECT") or project or DEFAULT_WEAVE_PROJECT
79
+ try:
80
+ import weave
81
+
82
+ weave.init(project)
83
+ return True
84
+ except Exception:
85
+ log.exception("Failed to initialize Weave tracing; continuing without it")
86
+ return False
87
+
88
+
89
+ class _HackbotSpanProcessor(SpanProcessor):
90
+ """Tag every span with the run id, and spans inside a subagent with its type."""
91
+
92
+ def __init__(self, run_id: str) -> None:
93
+ self._run_id = run_id
94
+
95
+ def on_start(self, span: Span, parent_context: Context | None = None) -> None:
96
+ span.set_attribute(RUN_ID_SPAN_ATTRIBUTE, self._run_id)
97
+ parent = otel_trace.get_current_span(parent_context)
98
+ subagent = (getattr(parent, "attributes", None) or {}).get(
99
+ SUBAGENT_SPAN_ATTRIBUTE
100
+ )
101
+ if subagent:
102
+ span.set_attribute(SUBAGENT_SPAN_ATTRIBUTE, subagent)
103
+
104
+
105
+ def _tag_spans(run_id: str) -> None:
106
+ provider = otel_trace.get_tracer_provider()
107
+ if isinstance(provider, TracerProvider):
108
+ provider.add_span_processor(_HackbotSpanProcessor(run_id))
109
+
110
+
111
+ @contextlib.contextmanager
112
+ def _trace_subagents_as(agent: str) -> Iterator[None]:
113
+ """Fix two gaps in Weave's Claude Agent SDK integration for subagents.
114
+
115
+ Naming: Weave names a subagent's ``invoke_agent`` span after its type
116
+ (e.g. ``investigator``), and the Agents view groups by that name, so every
117
+ subagent type shows up as a separate agent. We give the span the parent
118
+ agent's name and keep the type in ``hackbot.subagent``.
119
+
120
+ Usage: Weave records only the main thread's ``ResultMessage.usage``, which
121
+ excludes subagents and the CLI's helper model calls. The SDK's per-message
122
+ usage can't fill the gap: it repeats across content blocks and its output
123
+ counts are partial, and a subagent's tool result reports only its last call.
124
+ The only exact source is ``ResultMessage.model_usage``, so the rest of each
125
+ turn's usage is recorded on a chat span per model under the turn, tagged
126
+ with the subagents that ran in it. Weave then prices it like any chat span
127
+ and sums it into the run's cost.
128
+
129
+ Weave has no public hooks for either, so this patches ``SubAgent.start``
130
+ and the integration's message handler for the duration of the run.
131
+ """
132
+ try:
133
+ from weave.conversation import SubAgent
134
+ from weave.integrations.claude_agent_sdk import otel_integration
135
+ except ImportError:
136
+ yield
137
+ return
138
+
139
+ # Subagent types started since the last ResultMessage, for tagging.
140
+ subagents: set[str] = set()
141
+ # model_usage is cumulative over a session, so keep the previous totals per
142
+ # session to take only this turn's part.
143
+ session_totals: dict[str, dict[str, dict[str, int]]] = {}
144
+ start = SubAgent.start
145
+ process = otel_integration._process_message
146
+
147
+ def start_as_agent(self: SubAgent, *, set_current: bool = True) -> SubAgent:
148
+ subagent = self.name
149
+ subagents.add(subagent)
150
+ # Rename before starting: the span name is set at start, and the agent
151
+ # name attribute is rewritten from ``self.name`` when the span ends.
152
+ self.record(name=agent)
153
+ start(self, set_current=set_current)
154
+ self.set_attributes({SUBAGENT_SPAN_ATTRIBUTE: subagent})
155
+ return self
156
+
157
+ def record_unattributed_usage(msg: Any, state: Any) -> None:
158
+ totals = {
159
+ model: {
160
+ key: int(usage.get(src, 0) or 0)
161
+ for key, src in _MODEL_USAGE_KEYS.items()
162
+ }
163
+ for model, usage in (msg.model_usage or {}).items()
164
+ }
165
+ previous = session_totals.get(msg.session_id, {})
166
+ session_totals[msg.session_id] = totals
167
+ for model, total in totals.items():
168
+ # Weave already records the main thread's usage, for the main model only.
169
+ main = (msg.usage or {}) if model == state.model else {}
170
+ rest = {
171
+ key: max(
172
+ 0,
173
+ total[key]
174
+ - previous.get(model, {}).get(key, 0)
175
+ - int(main.get(key, 0) or 0),
176
+ )
177
+ for key in _MODEL_USAGE_KEYS
178
+ }
179
+ if not any(rest.values()):
180
+ continue
181
+ # Under the turn, not a subagent span: Weave ends subagent spans on
182
+ # the task notification, before this, and when several subagents
183
+ # run in a turn, model_usage can't split their usage between them.
184
+ with state.turn.start_llm(model=model, provider_name="anthropic") as llm:
185
+ if subagents:
186
+ llm.set_attributes(
187
+ {SUBAGENT_SPAN_ATTRIBUTE: ",".join(sorted(subagents))}
188
+ )
189
+ llm.record(usage=otel_integration._usage_from_result(rest))
190
+ subagents.clear()
191
+
192
+ def process_with_subagent_usage(msg: Any, state: Any) -> str | None:
193
+ # Only ResultMessage carries model_usage. Record before Weave processes
194
+ # it, while the turn span is still open.
195
+ if getattr(msg, "model_usage", None) is not None:
196
+ record_unattributed_usage(msg, state)
197
+ return process(msg, state)
198
+
199
+ SubAgent.start = start_as_agent
200
+ otel_integration._process_message = process_with_subagent_usage
201
+ try:
202
+ yield
203
+ finally:
204
+ SubAgent.start = start
205
+ otel_integration._process_message = process
206
+
207
+
208
+ @contextlib.contextmanager
209
+ def trace_agent(
210
+ entrypoint: Callable, run_id: str, weave_project: str | None = None
211
+ ) -> Iterator[None]:
212
+ """Trace the agent run, labelled with the agent's name and tagged with the run id.
213
+
214
+ A no-op when tracing isn't configured (no W&B credentials). Sets up W&B auth
215
+ first. ``weave_project`` is the agent's ``[tracing]`` one, which
216
+ ``WEAVE_PROJECT`` overrides.
217
+ """
218
+ config = wif.WandbWifSettings.from_env()
219
+ with wif.configure(config):
220
+ if not _init_weave(config, weave_project):
221
+ yield
222
+ return
223
+
224
+ from weave.conversation import agent_name_override
225
+
226
+ _tag_spans(run_id)
227
+ agent = resolve_agent_name(entrypoint)
228
+ log.info("Enabled Weave tracing for agent %s", agent)
229
+ with agent_name_override(agent), _trace_subagents_as(agent):
230
+ yield
@@ -0,0 +1,61 @@
1
+ """Shared logging helpers for Claude and Codex reporters.
2
+
3
+ Each reporter handles its SDK's events and uses these helpers to write short
4
+ messages to stdout and full records to the run log, with UTC timestamps.
5
+ """
6
+
7
+ import time
8
+ from pathlib import Path
9
+
10
+
11
+ def _truncate(s: str, n: int = 500) -> str:
12
+ return s if len(s) <= n else s[:n] + f"... [{len(s) - n} more chars]"
13
+
14
+
15
+ def _stamp() -> str:
16
+ """UTC wall clock, HH:MM:SS.mmm, prefixed to every log-file record."""
17
+ now = time.time()
18
+ clock = time.strftime("%H:%M:%S", time.gmtime(now))
19
+ millis = int(now * 1000) % 1000
20
+ return f"{clock}.{millis:03d}"
21
+
22
+
23
+ class TranscriptLog:
24
+ """Writes transcript lines to stdout and/or a log file."""
25
+
26
+ def __init__(self, verbose: bool, log_path: Path | None):
27
+ self.verbose = verbose
28
+ self._log = log_path.open("a", encoding="utf-8") if log_path else None
29
+ self._turn = 0
30
+ self._started = time.monotonic()
31
+
32
+ def __enter__(self):
33
+ return self
34
+
35
+ def __exit__(self, *exc):
36
+ if self._log:
37
+ self._log.close()
38
+
39
+ def header(self, title: str) -> None:
40
+ """Emit a section header (e.g. ``"bug 12345"``) and reset the turn count."""
41
+ self._turn = 0
42
+ self._started = time.monotonic()
43
+ banner = f"\n{'#' * 60}\n# {title}\n# started {_stamp()} UTC\n{'#' * 60}"
44
+ self._emit(banner, always=True, stamp=False)
45
+
46
+ def _emit(
47
+ self,
48
+ line: str,
49
+ *,
50
+ always: bool = False,
51
+ full: str | None = None,
52
+ stamp: bool = True,
53
+ ):
54
+ if self._log:
55
+ text = full if full is not None else line
56
+ lead, text = ("\n", text[1:]) if text.startswith("\n") else ("", text)
57
+ prefix = f"{_stamp()} " if stamp else ""
58
+ self._log.write(f"{lead}{prefix}{text}\n")
59
+ self._log.flush()
60
+ if always or self.verbose:
61
+ print(line)
@@ -0,0 +1,76 @@
1
+ import json
2
+ from pathlib import Path
3
+ from typing import IO
4
+
5
+ import requests
6
+ from requests.adapters import HTTPAdapter
7
+ from urllib3.util.retry import Retry
8
+
9
+ # GCS asks clients to retry 408, 429 and 5xx with exponential backoff:
10
+ # https://cloud.google.com/storage/docs/retry-strategy. Retrying an upload is
11
+ # safe because only this run writes its keys, and a retry sends the same bytes.
12
+ _RETRY = Retry(
13
+ total=5,
14
+ backoff_factor=1,
15
+ status_forcelist=[408, 429, *range(500, 600)],
16
+ allowed_methods=["POST"],
17
+ raise_on_status=False,
18
+ )
19
+
20
+
21
+ class SignedPolicyUploader:
22
+ """POST artifacts to a GCS V4 signed POST policy.
23
+
24
+ The orchestrator passes the policy via env vars consumed by `HackbotContext`.
25
+ The Job has no GCP identity; this signed policy is its only write
26
+ capability.
27
+ """
28
+
29
+ def __init__(self, url: str, fields: dict[str, str], prefix: str) -> None:
30
+ self.url = url
31
+ self.fields = fields
32
+ self.prefix = prefix
33
+ self._session = requests.Session()
34
+ self._session.mount(self.url, HTTPAdapter(max_retries=_RETRY))
35
+
36
+ def upload_bytes(
37
+ self, name: str, data: bytes, content_type: str = "application/octet-stream"
38
+ ) -> None:
39
+ self._post(name, data, content_type, size=len(data))
40
+
41
+ def upload_file(
42
+ self, name: str, path: Path, content_type: str | None = None
43
+ ) -> None:
44
+ # Stream from disk so we don't slurp a multi-GB artifact into
45
+ # memory; the V4 signed policy allows uploads up to its
46
+ # configured `content-length-range` cap.
47
+ size = path.stat().st_size
48
+ with path.open("rb") as fp:
49
+ self._post(name, fp, content_type or "application/octet-stream", size=size)
50
+
51
+ def upload_json(self, name: str, payload: dict) -> None:
52
+ body = json.dumps(payload, default=str).encode("utf-8")
53
+ self.upload_bytes(name, body, "application/json")
54
+
55
+ def _post(
56
+ self,
57
+ name: str,
58
+ body: bytes | IO[bytes],
59
+ content_type: str,
60
+ size: int,
61
+ ) -> None:
62
+ key = f"{self.prefix}{name}"
63
+ form: dict[str, str] = dict(self.fields)
64
+ form["key"] = key
65
+ files = {"file": (name, body, content_type)}
66
+ response = self._session.post(self.url, data=form, files=files, timeout=300)
67
+ if not response.ok:
68
+ # GCS V4 signed POST policy errors are only readable in the
69
+ # response body. `raise_for_status()` strips it, leaving an
70
+ # unhelpful "400 Bad Request" — so include the body in the
71
+ # exception message.
72
+ raise requests.HTTPError(
73
+ f"{response.status_code} uploading {name} to {self.url} "
74
+ f"(key={key}, size={size}): {response.text[:2000]}",
75
+ response=response,
76
+ )