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,366 @@
1
+ """Shared Codex SDK helpers for hackbot agents.
2
+
3
+ Generic, agent-neutral building blocks that every Codex SDK agent would
4
+ otherwise copy verbatim. Agents still start their own ``AsyncCodex`` threads
5
+ and read each turn's event stream — these just remove the boilerplate of
6
+ rendering the streamed notifications and collecting the turn outcome.
7
+
8
+ Requires the ``codex-sdk`` optional extra of hackbot-runtime.
9
+ """
10
+
11
+ import json
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ from openai_codex import AsyncThread
16
+ from openai_codex.generated.v2_all import (
17
+ AgentMessageThreadItem,
18
+ CollabAgentToolCallThreadItem,
19
+ CommandExecutionThreadItem,
20
+ ContextCompactionThreadItem,
21
+ DynamicToolCallThreadItem,
22
+ ErrorNotification,
23
+ FileChangeThreadItem,
24
+ InputTextDynamicToolCallOutputContentItem,
25
+ ItemCompletedNotification,
26
+ ItemStartedNotification,
27
+ McpToolCallThreadItem,
28
+ MessagePhase,
29
+ PlanThreadItem,
30
+ ReasoningThreadItem,
31
+ ThreadTokenUsage,
32
+ ThreadTokenUsageUpdatedNotification,
33
+ TurnCompletedNotification,
34
+ TurnStartedNotification,
35
+ TurnStatus,
36
+ UserMessageThreadItem,
37
+ WebSearchThreadItem,
38
+ )
39
+ from openai_codex.models import UnknownNotification
40
+
41
+ from hackbot_runtime.transcript import TranscriptLog, _truncate
42
+
43
+ DEFAULT_TOOL_TIMEOUT_SEC = 7200
44
+
45
+
46
+ def mcp_servers_config(
47
+ urls: dict[str, str], *, tool_timeout_sec: float = DEFAULT_TOOL_TIMEOUT_SEC
48
+ ) -> dict:
49
+ """Codex ``thread_start(config=...)`` for the MCP servers at ``urls``, by name.
50
+
51
+ Serve each with ``agent_tools.mcp_server.serve``, which yields its URL.
52
+ """
53
+ return {
54
+ "mcp_servers": {
55
+ name: {
56
+ "url": url,
57
+ "tool_timeout_sec": tool_timeout_sec,
58
+ "default_tools_approval_mode": "approve",
59
+ }
60
+ for name, url in urls.items()
61
+ }
62
+ }
63
+
64
+
65
+ @dataclass
66
+ class CodexTurnResult:
67
+ status: TurnStatus
68
+ result: str | None
69
+ error: str | None
70
+ num_turns: int
71
+ usage: ThreadTokenUsage | None
72
+ duration_ms: int | None
73
+
74
+ @property
75
+ def is_error(self) -> bool:
76
+ return self.status != TurnStatus.completed
77
+
78
+
79
+ class Reporter(TranscriptLog):
80
+ """Render Codex events into readable logs."""
81
+
82
+ def __init__(self, verbose: bool, log_path: Path | None):
83
+ super().__init__(verbose, log_path)
84
+ self._requests = 0
85
+ self._tokens = {"input": 0, "cached": 0, "output": 0, "reasoning": 0}
86
+ # the thread's token total from the last usage update, kept across turns
87
+ self._last_total = None
88
+ self._answer = None
89
+ self._last_message = None
90
+ self._usage = None
91
+ self.result: CodexTurnResult | None = None
92
+
93
+ async def session(self, thread: AsyncThread) -> None:
94
+ info = (await thread.read()).thread
95
+ self._emit(f"[system] session started (model={info.model or '?'})")
96
+
97
+ def message(self, event) -> None:
98
+ payload = event.payload
99
+
100
+ if isinstance(payload, TurnStartedNotification):
101
+ self._requests = 0
102
+ self._tokens = {"input": 0, "cached": 0, "output": 0, "reasoning": 0}
103
+ self._answer = None
104
+ self._last_message = None
105
+ self._usage = None
106
+ self.result = None
107
+
108
+ elif isinstance(payload, ThreadTokenUsageUpdatedNotification):
109
+ self._usage = payload.token_usage
110
+
111
+ # Counting a model request when total tokens increase and "last" has
112
+ # input tokens, skipping repeated and context-full updates.
113
+ total = payload.token_usage.total.total_tokens
114
+ last = payload.token_usage.last
115
+ rising = self._last_total is None or total > self._last_total
116
+ if rising and last.input_tokens > 0:
117
+ self._requests += 1
118
+ self._tokens["input"] += last.input_tokens
119
+ self._tokens["cached"] += last.cached_input_tokens
120
+ self._tokens["output"] += last.output_tokens
121
+ self._tokens["reasoning"] += last.reasoning_output_tokens
122
+ self._last_total = total
123
+
124
+ elif isinstance(payload, ItemStartedNotification):
125
+ item = payload.item.root
126
+
127
+ if isinstance(
128
+ item,
129
+ (
130
+ AgentMessageThreadItem,
131
+ CollabAgentToolCallThreadItem,
132
+ CommandExecutionThreadItem,
133
+ DynamicToolCallThreadItem,
134
+ FileChangeThreadItem,
135
+ McpToolCallThreadItem,
136
+ WebSearchThreadItem,
137
+ ),
138
+ ):
139
+ self._turn += 1
140
+ self._emit(f"\n--- turn {self._turn} ---")
141
+ if isinstance(item, CommandExecutionThreadItem):
142
+ arguments = {"command": item.command, "cwd": item.cwd.root}
143
+ self._emit(
144
+ f"[agent→tool] shell({_truncate(json.dumps(arguments), 300)})",
145
+ full=f"[agent→tool] shell\n{json.dumps(arguments, indent=2)}",
146
+ )
147
+ elif isinstance(item, McpToolCallThreadItem):
148
+ name = f"{item.server}.{item.tool}"
149
+ arguments = json.dumps(item.arguments, default=str)
150
+
151
+ self._emit(
152
+ f"[agent→tool] {name}({_truncate(arguments, 300)})",
153
+ full=(
154
+ f"[agent→tool] {name}\n"
155
+ f"{json.dumps(item.arguments, indent=2, default=str)}"
156
+ ),
157
+ )
158
+ elif isinstance(item, DynamicToolCallThreadItem):
159
+ name = item.tool
160
+ if item.namespace:
161
+ name = f"{item.namespace}.{item.tool}"
162
+
163
+ arguments = json.dumps(item.arguments, default=str)
164
+
165
+ self._emit(
166
+ f"[agent→tool] {name}({_truncate(arguments, 300)})",
167
+ full=(
168
+ f"[agent→tool] {name}\n"
169
+ f"{json.dumps(item.arguments, indent=2, default=str)}"
170
+ ),
171
+ )
172
+
173
+ elif isinstance(payload, ItemCompletedNotification):
174
+ item = payload.item.root
175
+
176
+ if isinstance(item, AgentMessageThreadItem):
177
+ if item.phase == MessagePhase.final_answer:
178
+ self._answer = item.text
179
+ elif item.phase is None:
180
+ self._last_message = item.text
181
+ self._emit(f"[agent] {item.text}", always=True)
182
+ elif isinstance(item, ReasoningThreadItem):
183
+ thinking = "\n".join(
184
+ [*(item.summary or []), *(item.content or [])]
185
+ ).strip()
186
+
187
+ if thinking:
188
+ snippet = thinking.split("\n", 1)[0]
189
+ self._emit(
190
+ f"[agent:thinking] {_truncate(snippet, 120)}",
191
+ full=f"[agent:thinking]\n{thinking}",
192
+ )
193
+ elif isinstance(item, CommandExecutionThreadItem):
194
+ marker = "ok"
195
+ if item.status.value in ("failed", "declined"):
196
+ marker = "ERROR"
197
+ if item.exit_code not in (None, 0):
198
+ marker = "ERROR"
199
+
200
+ output = item.aggregated_output or ""
201
+ self._emit(
202
+ f"[tool←{marker}] {_truncate(output, 400)}",
203
+ full=f"[tool←{marker}]\n{output}",
204
+ )
205
+ elif isinstance(item, FileChangeThreadItem):
206
+ paths = [change.path for change in item.changes]
207
+ diffs = "\n".join(change.diff for change in item.changes)
208
+
209
+ self._emit(
210
+ f"[agent→tool] apply_patch({_truncate(json.dumps(paths), 300)})",
211
+ full=f"[agent→tool] apply_patch\n{diffs}",
212
+ )
213
+ marker = "ok"
214
+ if item.status.value in ("failed", "declined"):
215
+ marker = "ERROR"
216
+
217
+ self._emit(f"[tool←{marker}] {item.status.value}")
218
+ elif isinstance(item, McpToolCallThreadItem):
219
+ marker = "ok"
220
+ text = ""
221
+
222
+ if item.error is not None:
223
+ marker = "ERROR"
224
+ text = item.error.message
225
+
226
+ elif item.result is not None:
227
+ parts = []
228
+ for c in item.result.content:
229
+ if isinstance(c, dict) and c.get("type") == "text":
230
+ parts.append(c.get("text", ""))
231
+ if parts:
232
+ text = "\n".join(parts)
233
+ elif item.result.structured_content is not None:
234
+ text = json.dumps(
235
+ item.result.structured_content,
236
+ default=str,
237
+ )
238
+
239
+ if item.status.value == "failed":
240
+ marker = "ERROR"
241
+
242
+ self._emit(
243
+ f"[tool←{marker}] {_truncate(text, 400)}",
244
+ full=f"[tool←{marker}]\n{text}",
245
+ )
246
+ elif isinstance(item, PlanThreadItem):
247
+ self._emit(
248
+ f"[agent:plan] {_truncate(item.text, 300)}",
249
+ full=f"[agent:plan]\n{item.text}",
250
+ )
251
+ elif isinstance(item, WebSearchThreadItem):
252
+ arguments = {"query": item.query}
253
+
254
+ self._emit(
255
+ f"[agent→tool] web_search({_truncate(json.dumps(arguments), 300)})",
256
+ full=(
257
+ f"[agent→tool] web_search\n{json.dumps(arguments, indent=2)}"
258
+ ),
259
+ )
260
+ elif isinstance(item, CollabAgentToolCallThreadItem):
261
+ name = f"collab.{item.tool.value}"
262
+ arguments = {
263
+ "prompt": item.prompt,
264
+ "model": item.model,
265
+ }
266
+
267
+ self._emit(
268
+ f"[agent→tool] {name}({_truncate(json.dumps(arguments), 300)})",
269
+ full=(f"[agent→tool] {name}\n{json.dumps(arguments, indent=2)}"),
270
+ )
271
+ elif isinstance(item, ContextCompactionThreadItem):
272
+ self._emit("[system:compaction] context compacted")
273
+ elif isinstance(item, DynamicToolCallThreadItem):
274
+ marker = "ok"
275
+ if item.status.value == "failed" or item.success is False:
276
+ marker = "ERROR"
277
+
278
+ parts = []
279
+ for content in item.content_items or []:
280
+ if isinstance(
281
+ content.root,
282
+ InputTextDynamicToolCallOutputContentItem,
283
+ ):
284
+ parts.append(content.root.text)
285
+
286
+ text = "\n".join(parts)
287
+
288
+ self._emit(
289
+ f"[tool←{marker}] {_truncate(text, 400)}",
290
+ full=f"[tool←{marker}]\n{text}",
291
+ )
292
+ elif not isinstance(item, UserMessageThreadItem):
293
+ data = json.dumps(
294
+ item.model_dump(mode="json", by_alias=True, warnings=False),
295
+ default=str,
296
+ )
297
+
298
+ self._emit(
299
+ f"[system:{item.type}] {_truncate(data, 200)}",
300
+ full=f"[system:{item.type}] {data}",
301
+ )
302
+
303
+ elif isinstance(payload, ErrorNotification):
304
+ retry = " (retrying)" if payload.will_retry else ""
305
+
306
+ self._emit(f"[system:error] {payload.error.message}{retry}")
307
+
308
+ elif isinstance(payload, TurnCompletedNotification):
309
+ turn = payload.turn
310
+
311
+ error = None
312
+ if turn.status != TurnStatus.completed:
313
+ error = (
314
+ turn.error.message
315
+ if turn.error is not None
316
+ else f"turn {turn.status.value}"
317
+ )
318
+
319
+ self.result = CodexTurnResult(
320
+ status=turn.status,
321
+ result=self._answer if self._answer is not None else self._last_message,
322
+ error=error,
323
+ num_turns=self._requests,
324
+ usage=self._usage,
325
+ duration_ms=turn.duration_ms,
326
+ )
327
+
328
+ self._emit(f"\n{'=' * 60}", always=True, stamp=False)
329
+ line = f"[done] turns={self._requests}"
330
+ if turn.status != TurnStatus.completed:
331
+ line += f" status={turn.status.value}"
332
+ # explicit cost is not available, just token usage
333
+ if self._requests:
334
+ line += f" tokens=in:{self._tokens['input']}"
335
+ line += f"(cached:{self._tokens['cached']})"
336
+ line += f",out:{self._tokens['output']}"
337
+ line += f"(reasoning:{self._tokens['reasoning']})"
338
+
339
+ if turn.duration_ms is not None:
340
+ line += f" elapsed={turn.duration_ms / 1000:.0f}s"
341
+ self._emit(line, always=True)
342
+
343
+ if error is not None:
344
+ self._emit(f"[done] ERROR: {error}", always=True)
345
+
346
+ # fallback for any other notification
347
+ else:
348
+ # skip incremental updates whose final state comes in an
349
+ # item/completed or turn/completed notification anyway
350
+ if event.method.lower().endswith("delta") or event.method in (
351
+ "item/fileChange/patchUpdated",
352
+ "item/reasoning/summaryPartAdded",
353
+ "turn/diff/updated",
354
+ ):
355
+ return
356
+
357
+ if isinstance(payload, UnknownNotification):
358
+ data = payload.params
359
+ else:
360
+ data = payload.model_dump(mode="json", by_alias=True, warnings=False)
361
+ text = json.dumps(data, default=str)
362
+
363
+ self._emit(
364
+ f"[system:{event.method}] {_truncate(text, 200)}",
365
+ full=f"[system:{event.method}] {text}",
366
+ )
@@ -0,0 +1,82 @@
1
+ """Declarative agent configuration loaded from ``hackbot.toml``.
2
+
3
+ Captures the capability declarations that are intrinsic to an agent (which
4
+ source repo it operates on, whether it needs a Firefox build) so the runtime
5
+ can prepare them on the agent's behalf. Per-run inputs and secrets are NOT here
6
+ — they arrive via environment variables.
7
+ """
8
+
9
+ import tomllib
10
+ from functools import cached_property
11
+ from importlib import metadata
12
+ from pathlib import Path
13
+
14
+ from pydantic import BaseModel
15
+
16
+
17
+ class SourceConfig(BaseModel):
18
+ """The source repository an agent operates on (see ``ensure_source_repo``)."""
19
+
20
+ repo_url: str
21
+ # Where the checkout lands. The env var SOURCE_REPO overrides this at runtime
22
+ # (the orchestrator points it at the task-local workspace).
23
+ checkout_path: Path = Path("/workspace/source")
24
+ # Optional commit/branch/tag to check out instead of remote HEAD. The env var
25
+ # SOURCE_REF overrides this at runtime (per-run inputs like a failure commit).
26
+ ref: str | None = None
27
+
28
+
29
+ class FirefoxConfig(BaseModel):
30
+ """Firefox build the agent needs (paths derived from the source checkout)."""
31
+
32
+ enabled: bool = True
33
+ # Object directory name under the source root; matches the agent-tools
34
+ # FirefoxContext default.
35
+ objdir: str = "objdir-ff-asan"
36
+
37
+
38
+ class TracingConfig(BaseModel):
39
+ """``[tracing]``: where the agent's traces go."""
40
+
41
+ # Weave project, ``project`` or ``entity/project``; ``WEAVE_PROJECT`` overrides it.
42
+ weave_project: str | None = None
43
+
44
+
45
+ class HackbotConfig(BaseModel):
46
+ """Parsed ``hackbot.toml``. Every table is optional.
47
+
48
+ An agent that does not operate on a repo omits ``[source]``; one that does
49
+ not need Firefox omits ``[firefox]``. A missing file yields an empty config.
50
+ """
51
+
52
+ source: SourceConfig | None = None
53
+ firefox: FirefoxConfig | None = None
54
+ tracing: TracingConfig = TracingConfig()
55
+ # Set by the runtime from the entry point, not read from the toml.
56
+ agent_name: str | None = None
57
+
58
+ @cached_property
59
+ def agent_version(self) -> str | None:
60
+ """The version in the agent's pyproject.toml, or None when it isn't installed."""
61
+ if self.agent_name is None:
62
+ return None
63
+ try:
64
+ return metadata.version(f"hackbot-agent-{self.agent_name}")
65
+ except metadata.PackageNotFoundError:
66
+ return None
67
+
68
+
69
+ def load_config(path: Path) -> HackbotConfig:
70
+ """Load and validate ``hackbot.toml`` at ``path``.
71
+
72
+ Strict: the file must exist. The "agent declares no capabilities" fallback is
73
+ handled by discovery (``_resolve_config`` returns an empty
74
+ :class:`HackbotConfig` when no toml is found), which never passes a missing
75
+ path here.
76
+ """
77
+ if not path.exists():
78
+ raise FileNotFoundError(f"Config file {path} does not exist")
79
+
80
+ with path.open("rb") as fh:
81
+ data = tomllib.load(fh)
82
+ return HackbotConfig.model_validate(data)