hackbot-runtime 0.1.0__tar.gz

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 (65) hide show
  1. hackbot_runtime-0.1.0/.gitignore +62 -0
  2. hackbot_runtime-0.1.0/PKG-INFO +25 -0
  3. hackbot_runtime-0.1.0/VERSION +1 -0
  4. hackbot_runtime-0.1.0/hackbot_runtime/__init__.py +24 -0
  5. hackbot_runtime-0.1.0/hackbot_runtime/actions/__init__.py +41 -0
  6. hackbot_runtime-0.1.0/hackbot_runtime/actions/action_records.py +51 -0
  7. hackbot_runtime-0.1.0/hackbot_runtime/actions/agents.py +55 -0
  8. hackbot_runtime-0.1.0/hackbot_runtime/actions/bugzilla.py +232 -0
  9. hackbot_runtime-0.1.0/hackbot_runtime/actions/claude_sdk.py +49 -0
  10. hackbot_runtime-0.1.0/hackbot_runtime/actions/email.py +152 -0
  11. hackbot_runtime-0.1.0/hackbot_runtime/actions/feedback.py +60 -0
  12. hackbot_runtime-0.1.0/hackbot_runtime/actions/github.py +208 -0
  13. hackbot_runtime-0.1.0/hackbot_runtime/actions/mcp_server.py +39 -0
  14. hackbot_runtime-0.1.0/hackbot_runtime/actions/phabricator.py +234 -0
  15. hackbot_runtime-0.1.0/hackbot_runtime/actions/recorder.py +146 -0
  16. hackbot_runtime-0.1.0/hackbot_runtime/actions/slack.py +101 -0
  17. hackbot_runtime-0.1.0/hackbot_runtime/actions/testrail.py +206 -0
  18. hackbot_runtime-0.1.0/hackbot_runtime/actions/tools.py +46 -0
  19. hackbot_runtime-0.1.0/hackbot_runtime/actions/try_server.py +166 -0
  20. hackbot_runtime-0.1.0/hackbot_runtime/artifacts.py +89 -0
  21. hackbot_runtime-0.1.0/hackbot_runtime/changes.py +431 -0
  22. hackbot_runtime-0.1.0/hackbot_runtime/claude.py +96 -0
  23. hackbot_runtime-0.1.0/hackbot_runtime/codex.py +366 -0
  24. hackbot_runtime-0.1.0/hackbot_runtime/config.py +82 -0
  25. hackbot_runtime-0.1.0/hackbot_runtime/context.py +362 -0
  26. hackbot_runtime-0.1.0/hackbot_runtime/errors.py +7 -0
  27. hackbot_runtime-0.1.0/hackbot_runtime/providers.py +46 -0
  28. hackbot_runtime-0.1.0/hackbot_runtime/pull_request.py +130 -0
  29. hackbot_runtime-0.1.0/hackbot_runtime/results.py +13 -0
  30. hackbot_runtime-0.1.0/hackbot_runtime/revision.py +238 -0
  31. hackbot_runtime-0.1.0/hackbot_runtime/runtime.py +244 -0
  32. hackbot_runtime-0.1.0/hackbot_runtime/searchfox.py +182 -0
  33. hackbot_runtime-0.1.0/hackbot_runtime/slack_kit.py +51 -0
  34. hackbot_runtime-0.1.0/hackbot_runtime/source.py +157 -0
  35. hackbot_runtime-0.1.0/hackbot_runtime/tracing.py +230 -0
  36. hackbot_runtime-0.1.0/hackbot_runtime/transcript.py +61 -0
  37. hackbot_runtime-0.1.0/hackbot_runtime/uploader.py +76 -0
  38. hackbot_runtime-0.1.0/hackbot_runtime/wif.py +359 -0
  39. hackbot_runtime-0.1.0/pyproject.toml +45 -0
  40. hackbot_runtime-0.1.0/tests/test_agents_actions.py +53 -0
  41. hackbot_runtime-0.1.0/tests/test_artifacts.py +42 -0
  42. hackbot_runtime-0.1.0/tests/test_bugzilla_actions.py +71 -0
  43. hackbot_runtime-0.1.0/tests/test_changes.py +362 -0
  44. hackbot_runtime-0.1.0/tests/test_claude.py +36 -0
  45. hackbot_runtime-0.1.0/tests/test_claude_sdk.py +176 -0
  46. hackbot_runtime-0.1.0/tests/test_codex.py +166 -0
  47. hackbot_runtime-0.1.0/tests/test_config.py +84 -0
  48. hackbot_runtime-0.1.0/tests/test_context.py +519 -0
  49. hackbot_runtime-0.1.0/tests/test_email_actions.py +122 -0
  50. hackbot_runtime-0.1.0/tests/test_github_actions.py +163 -0
  51. hackbot_runtime-0.1.0/tests/test_mcp_server.py +64 -0
  52. hackbot_runtime-0.1.0/tests/test_phabricator_actions.py +173 -0
  53. hackbot_runtime-0.1.0/tests/test_providers.py +26 -0
  54. hackbot_runtime-0.1.0/tests/test_pull_request.py +243 -0
  55. hackbot_runtime-0.1.0/tests/test_recorder.py +298 -0
  56. hackbot_runtime-0.1.0/tests/test_revision.py +561 -0
  57. hackbot_runtime-0.1.0/tests/test_runtime.py +357 -0
  58. hackbot_runtime-0.1.0/tests/test_searchfox.py +194 -0
  59. hackbot_runtime-0.1.0/tests/test_slack_actions.py +70 -0
  60. hackbot_runtime-0.1.0/tests/test_slack_kit.py +110 -0
  61. hackbot_runtime-0.1.0/tests/test_source.py +299 -0
  62. hackbot_runtime-0.1.0/tests/test_testrail_action.py +218 -0
  63. hackbot_runtime-0.1.0/tests/test_tracing.py +310 -0
  64. hackbot_runtime-0.1.0/tests/test_try_server_actions.py +202 -0
  65. hackbot_runtime-0.1.0/tests/test_wif.py +322 -0
@@ -0,0 +1,62 @@
1
+ *model
2
+ *model.zst
3
+ *model.zst.etag
4
+ *data_X
5
+ *data_y
6
+ *data_X.zst
7
+ *data_X.zst.etag
8
+ *data_y.zst
9
+ *data_y.zst.etag
10
+ feature_importance.png
11
+ importance.html
12
+ importances.json
13
+ metrics.json
14
+ probs.json
15
+ services/bugbug-api/models/*model*
16
+
17
+ data/
18
+ sheets/
19
+
20
+ .mypy_cache/
21
+ .pytest_cache/
22
+ *.pyc
23
+ .coverage
24
+
25
+ # Distribution / packaging
26
+ .Python
27
+ build/
28
+ develop-eggs/
29
+ dist/
30
+ downloads/
31
+ eggs/
32
+ .eggs/
33
+ lib/
34
+ lib64/
35
+ parts/
36
+ sdist/
37
+ var/
38
+ wheels/
39
+ pip-wheel-metadata/
40
+ share/python-wheels/
41
+ *.egg-info/
42
+ .installed.cfg
43
+ *.egg
44
+ MANIFEST
45
+ cache/
46
+ node_modules/
47
+
48
+ # Logs
49
+ *.log
50
+ # Desktop Service Store
51
+ *.DS_Store
52
+
53
+ # Local env files
54
+ .env
55
+ /services/bugbug-api/docker-compose.override.yml
56
+
57
+ # Local files
58
+ *.local.*
59
+
60
+ # Claude Code local state
61
+ .claude/worktrees/
62
+ .claude/.cc-writes/
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.5
2
+ Name: hackbot-runtime
3
+ Version: 0.1.0
4
+ Summary: Agent-side runtime for hackbot-api: signed-policy upload, summary contract, exception handling
5
+ Requires-Python: >=3.14
6
+ Requires-Dist: google-auth>=2.0.0
7
+ Requires-Dist: google-cloud-storage>=2.16.0
8
+ Requires-Dist: httpx>=0.26.0
9
+ Requires-Dist: moz-agent-tools
10
+ Requires-Dist: moz-phabricator-client
11
+ Requires-Dist: pydantic-settings>=2.1.0
12
+ Requires-Dist: requests>=2.32.0
13
+ Requires-Dist: sentry-sdk>=2.51.0
14
+ Requires-Dist: slack-sdk>=3.27.0
15
+ Requires-Dist: weave>=0.53.12
16
+ Provides-Extra: claude-sdk
17
+ Requires-Dist: claude-agent-sdk>=0.1.30; extra == 'claude-sdk'
18
+ Requires-Dist: moz-agent-tools[claude-sdk]; extra == 'claude-sdk'
19
+ Provides-Extra: codex-sdk
20
+ Requires-Dist: moz-agent-tools[mcp-server]; extra == 'codex-sdk'
21
+ Requires-Dist: openai-codex>=0.163.0; extra == 'codex-sdk'
22
+ Provides-Extra: mcp-server
23
+ Requires-Dist: moz-agent-tools[mcp-server]; extra == 'mcp-server'
24
+ Provides-Extra: phabricator
25
+ Requires-Dist: mozphab==2.15.3; extra == 'phabricator'
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,24 @@
1
+ from hackbot_runtime.actions.recorder import ActionsRecorder
2
+ from hackbot_runtime.config import HackbotConfig
3
+ from hackbot_runtime.context import HackbotContext
4
+ from hackbot_runtime.errors import AgentError
5
+ from hackbot_runtime.pull_request import checkout_pull_request
6
+ from hackbot_runtime.results import HackbotAgentResult
7
+ from hackbot_runtime.revision import checkout_revision
8
+ from hackbot_runtime.runtime import run, run_async
9
+ from hackbot_runtime.source import ensure_source_repo
10
+ from hackbot_runtime.uploader import SignedPolicyUploader
11
+
12
+ __all__ = [
13
+ "ActionsRecorder",
14
+ "AgentError",
15
+ "HackbotAgentResult",
16
+ "HackbotConfig",
17
+ "HackbotContext",
18
+ "SignedPolicyUploader",
19
+ "checkout_pull_request",
20
+ "checkout_revision",
21
+ "ensure_source_repo",
22
+ "run",
23
+ "run_async",
24
+ ]
@@ -0,0 +1,41 @@
1
+ """Recordable actions for hackbot agents.
2
+
3
+ ``ActionsRecorder`` is the framework-neutral sink whose collected actions the
4
+ runtime serialises into ``summary.json``. The action *declarations* live in
5
+ domain modules (``bugzilla``, ...) and use the shared ``@tool`` decorator from
6
+ agent-tools, so one mechanism backs both read tools and write-actions. The
7
+ framework adapters are ``hackbot_runtime.actions.claude_sdk.actions_server_for``
8
+ and ``hackbot_runtime.actions.mcp_server.actions_server_for``.
9
+ """
10
+
11
+ from hackbot_runtime.actions import (
12
+ action_records,
13
+ agents,
14
+ bugzilla,
15
+ email,
16
+ feedback,
17
+ github,
18
+ phabricator,
19
+ slack,
20
+ testrail,
21
+ try_server,
22
+ )
23
+ from hackbot_runtime.actions.recorder import ActionHook, ActionsRecorder
24
+
25
+ ACTIONS_SERVER_NAME = "actions"
26
+
27
+ __all__ = [
28
+ "ACTIONS_SERVER_NAME",
29
+ "ActionHook",
30
+ "ActionsRecorder",
31
+ "action_records",
32
+ "agents",
33
+ "bugzilla",
34
+ "email",
35
+ "feedback",
36
+ "github",
37
+ "phabricator",
38
+ "slack",
39
+ "testrail",
40
+ "try_server",
41
+ ]
@@ -0,0 +1,51 @@
1
+ """Agent-facing tools for inspecting and retracting recorded actions."""
2
+
3
+ from typing import Annotated
4
+
5
+ from agent_tools.registry import tool, tools_in
6
+ from pydantic import Field
7
+
8
+ from hackbot_runtime.actions.recorder import ActionsRecorder
9
+
10
+
11
+ def _table_cell(value: str | None) -> str:
12
+ """Format one value for a Markdown table cell."""
13
+ if value is None:
14
+ return ""
15
+ return "<br>".join(value.splitlines()).replace("|", r"\|")
16
+
17
+
18
+ @tool
19
+ async def list_actions(recorder: ActionsRecorder) -> str:
20
+ """List the actions currently proposed by this agent run.
21
+
22
+ Returns a Markdown table with each action's ID, type, and reasoning.
23
+ """
24
+ actions = recorder.list_actions()
25
+ if not actions:
26
+ return "No recorded actions."
27
+
28
+ rows = ["| ID | Action | Reasoning |", "| --- | --- | --- |"]
29
+ rows.extend(
30
+ f"| {_table_cell(action['action_id'])} "
31
+ f"| {_table_cell(action['type'])} "
32
+ f"| {_table_cell(action.get('reasoning'))} |"
33
+ for action in actions
34
+ )
35
+ return "\n".join(rows)
36
+
37
+
38
+ @tool
39
+ async def remove_action(
40
+ recorder: ActionsRecorder,
41
+ action_id: Annotated[
42
+ str,
43
+ Field(description="ID of the action to remove."),
44
+ ],
45
+ ) -> str:
46
+ """Remove the recorded action with the given ID."""
47
+ recorder.remove_action(action_id)
48
+ return f"Removed recorded action {action_id}."
49
+
50
+
51
+ TOOLS = tools_in(__name__)
@@ -0,0 +1,55 @@
1
+ """Agent-chaining recordable action.
2
+
3
+ A run records that another agent should continue its work; the apply side starts
4
+ that run once this one has succeeded (see ``handlers/agents_handler.py``). The
5
+ downstream run receives this run's id as ``PARENT_RUN_ID`` and its artifacts are
6
+ downloaded before its ``main()`` runs (see ``HackbotContext.parent_artifacts_dir``).
7
+
8
+ An agent may only start the agents it declared with :func:`allow_agents`; without
9
+ that the tool refuses every name.
10
+ """
11
+
12
+ from collections.abc import Iterable
13
+ from typing import Annotated
14
+ from weakref import WeakKeyDictionary
15
+
16
+ from agent_tools.registry import ToolError, tool, tools_in
17
+ from pydantic import Field
18
+
19
+ from hackbot_runtime.actions.recorder import ActionsRecorder, confirmation
20
+
21
+ ACTION_TYPE = "agents.start_run"
22
+
23
+ _allowed: WeakKeyDictionary[ActionsRecorder, frozenset[str]] = WeakKeyDictionary()
24
+
25
+
26
+ def allow_agents(recorder: ActionsRecorder, agents: Iterable[str]) -> None:
27
+ """Let the run recording into ``recorder`` start only ``agents``."""
28
+ _allowed[recorder] = frozenset(agents)
29
+
30
+
31
+ @tool
32
+ async def start_run(
33
+ recorder: ActionsRecorder,
34
+ agent: Annotated[str, Field(description="Name of the agent to start.")],
35
+ reasoning: Annotated[
36
+ str,
37
+ Field(description="Why the work should continue (for audit log)."),
38
+ ],
39
+ ) -> str:
40
+ """Start another agent on this run's output once this run has finished.
41
+
42
+ Recorded into the run summary -- nothing starts until the run succeeds.
43
+ """
44
+ agent = agent.strip()
45
+ allowed = _allowed.get(recorder, frozenset())
46
+ if agent not in allowed:
47
+ raise ToolError(
48
+ f"{agent!r} cannot be started from this run; allowed: "
49
+ + (", ".join(sorted(allowed)) or "none")
50
+ )
51
+ action = recorder.record(ACTION_TYPE, {"agent": agent}, reasoning=reasoning)
52
+ return confirmation(action)
53
+
54
+
55
+ TOOLS = tools_in(__name__)
@@ -0,0 +1,232 @@
1
+ """Bugzilla-domain recordable actions.
2
+
3
+ Each handler takes the ``ActionsRecorder`` as its first positional parameter
4
+ (excluded from the agent-facing schema) plus the agent-facing args annotated
5
+ with ``Annotated[T, Field(...)]``. Declared with the shared ``@tool`` decorator
6
+ from agent-tools so the same mechanism backs read tools and write-actions.
7
+ Handlers record an intended change (nothing is mutated) and return a short
8
+ confirmation string, raising ``ToolError`` on invalid input.
9
+ """
10
+
11
+ import mimetypes
12
+ import os
13
+ from pathlib import Path
14
+ from typing import Annotated, Any
15
+
16
+ from agent_tools.registry import ToolError, tool, tools_in
17
+ from pydantic import Field
18
+
19
+ from hackbot_runtime.actions.recorder import ActionsRecorder, confirmation
20
+
21
+ UPDATE_BUG_ACTION_TYPE = "bugzilla.update_bug"
22
+ ADD_COMMENT_ACTION_TYPE = "bugzilla.add_comment"
23
+ ADD_ATTACHMENT_ACTION_TYPE = "bugzilla.add_attachment"
24
+ CREATE_BUG_ACTION_TYPE = "bugzilla.create_bug"
25
+
26
+ _COMMENT_FOOTER = (
27
+ "If you'd like to provide feedback on this comment, please use the 👍 or 👎 "
28
+ "reaction."
29
+ )
30
+
31
+
32
+ @tool
33
+ async def update_bug(
34
+ recorder: ActionsRecorder,
35
+ bug_id: Annotated[int, Field(description="Bug ID to change.")],
36
+ changes: Annotated[
37
+ dict[str, Any],
38
+ Field(
39
+ description=(
40
+ "Field → new value. Accepts any field the Bugzilla REST "
41
+ "PUT endpoint accepts (status, resolution, priority, "
42
+ "severity, whiteboard, assigned_to, component, product, "
43
+ "version, ...). For list fields (keywords, cc, blocks, "
44
+ "depends_on, see_also) you may pass "
45
+ '{"add": [...], "remove": [...], "set": [...]}.'
46
+ )
47
+ ),
48
+ ],
49
+ reasoning: Annotated[
50
+ str,
51
+ Field(
52
+ description=(
53
+ "Why you are recording this change. Stored alongside the "
54
+ "action so the human reviewer can audit."
55
+ )
56
+ ),
57
+ ],
58
+ ) -> str:
59
+ """Record an intended change to a Bugzilla bug.
60
+
61
+ Recorded into the run summary for human review — does not modify Bugzilla.
62
+ """
63
+ action = recorder.record(
64
+ UPDATE_BUG_ACTION_TYPE,
65
+ {"bug_id": bug_id, "changes": changes},
66
+ reasoning=reasoning,
67
+ )
68
+ return confirmation(action)
69
+
70
+
71
+ @tool
72
+ async def add_comment(
73
+ recorder: ActionsRecorder,
74
+ bug_id: Annotated[int, Field(description="Bug ID to comment on.")],
75
+ text: Annotated[str, Field(description="Comment body (Markdown supported).")],
76
+ reasoning: Annotated[
77
+ str, Field(description="Why you are recording this comment (for audit log).")
78
+ ],
79
+ is_private: Annotated[
80
+ bool,
81
+ Field(
82
+ description="Mark the comment private (security group only).",
83
+ ),
84
+ ] = False,
85
+ ) -> str:
86
+ """Record an intended comment on a bug.
87
+
88
+ Use is_private=true for security-sensitive notes. Recorded into the run
89
+ summary for human review — does not post to Bugzilla.
90
+ """
91
+ text_with_footer = text.rstrip() + "\n\n---\n\n" + _COMMENT_FOOTER
92
+ action = recorder.record(
93
+ ADD_COMMENT_ACTION_TYPE,
94
+ {"bug_id": bug_id, "text": text_with_footer, "is_private": is_private},
95
+ reasoning=reasoning,
96
+ )
97
+ return confirmation(action)
98
+
99
+
100
+ @tool
101
+ async def add_attachment(
102
+ recorder: ActionsRecorder,
103
+ bug_id: Annotated[int, Field(description="Bug ID to attach to.")],
104
+ file_path: Annotated[
105
+ str,
106
+ Field(
107
+ description=(
108
+ "Local path to the file. The runtime uploads a copy as an "
109
+ "artifact so the apply step can fetch it; the local path "
110
+ "is not persisted."
111
+ )
112
+ ),
113
+ ],
114
+ reasoning: Annotated[
115
+ str, Field(description="Why you are attaching this (for audit log).")
116
+ ],
117
+ summary: Annotated[
118
+ str | None,
119
+ Field(
120
+ description="Short description of the attachment. Defaults to the filename.",
121
+ ),
122
+ ] = None,
123
+ content_type: Annotated[
124
+ str | None,
125
+ Field(
126
+ description=(
127
+ "MIME type. Guessed from extension if omitted. Ignored "
128
+ "when is_patch=true."
129
+ ),
130
+ ),
131
+ ] = None,
132
+ is_patch: Annotated[
133
+ bool,
134
+ Field(
135
+ description=(
136
+ "Mark as a patch (Bugzilla forces text/plain and enables diff view)."
137
+ ),
138
+ ),
139
+ ] = False,
140
+ comment: Annotated[
141
+ str | None,
142
+ Field(
143
+ description="Optional comment to record alongside the attachment.",
144
+ ),
145
+ ] = None,
146
+ ) -> str:
147
+ """Record an intended file attachment on a bug.
148
+
149
+ Pass a local filesystem path — the runtime uploads a copy of the file
150
+ alongside summary.json so the apply step can fetch it. For patches, set
151
+ is_patch=true and omit content_type. Recorded into the run summary for human
152
+ review — does not upload to Bugzilla.
153
+ """
154
+ if not os.path.isfile(file_path):
155
+ raise ToolError(f"file not found: {file_path}")
156
+
157
+ file_name = os.path.basename(file_path)
158
+ resolved_summary = summary or file_name
159
+ size = os.path.getsize(file_path)
160
+ if is_patch:
161
+ resolved_content_type = "text/plain"
162
+ else:
163
+ resolved_content_type = content_type or (
164
+ mimetypes.guess_type(file_path)[0] or "application/octet-stream"
165
+ )
166
+
167
+ params: dict[str, Any] = {
168
+ "bug_id": bug_id,
169
+ "file_name": file_name,
170
+ "summary": resolved_summary,
171
+ "content_type": resolved_content_type,
172
+ "is_patch": is_patch,
173
+ "size_bytes": size,
174
+ }
175
+ if comment:
176
+ params["comment"] = comment
177
+
178
+ action = recorder.record(
179
+ ADD_ATTACHMENT_ACTION_TYPE,
180
+ params,
181
+ reasoning=reasoning,
182
+ attachments={"file": Path(file_path)},
183
+ )
184
+ return confirmation(action)
185
+
186
+
187
+ @tool
188
+ async def create_bug(
189
+ recorder: ActionsRecorder,
190
+ product: Annotated[str, Field(description="Bugzilla product.")],
191
+ component: Annotated[str, Field(description="Bugzilla component.")],
192
+ summary: Annotated[str, Field(description="Bug summary (title).")],
193
+ version: Annotated[str, Field(description="Product version affected.")],
194
+ description: Annotated[str, Field(description="Comment 0. Markdown is enabled.")],
195
+ reasoning: Annotated[
196
+ str, Field(description="Why you are filing this bug (for audit log).")
197
+ ],
198
+ extra: Annotated[
199
+ dict[str, Any] | None,
200
+ Field(
201
+ description=(
202
+ "Optional additional fields accepted by Bugzilla's POST /bug "
203
+ "endpoint (severity, priority, keywords, whiteboard, blocks, "
204
+ "depends_on, cc, groups, op_sys, platform, assigned_to, "
205
+ "see_also, ...). Merged into the recorded body — explicit "
206
+ "top-level args win on conflict."
207
+ ),
208
+ ),
209
+ ] = None,
210
+ ) -> str:
211
+ """Record an intended new-bug filing.
212
+
213
+ The description becomes comment 0 and is rendered as Markdown. Recorded into
214
+ the run summary for human review — does not file in Bugzilla.
215
+
216
+ Later actions can reference its `bug_id` and `url`.
217
+ """
218
+ body: dict[str, Any] = {
219
+ "product": product,
220
+ "component": component,
221
+ "summary": summary,
222
+ "version": version,
223
+ "description": description,
224
+ }
225
+ for k, v in (extra or {}).items():
226
+ body.setdefault(k, v)
227
+
228
+ action = recorder.record(CREATE_BUG_ACTION_TYPE, body, reasoning=reasoning)
229
+ return confirmation(action)
230
+
231
+
232
+ TOOLS = tools_in(__name__)
@@ -0,0 +1,49 @@
1
+ """Build the claude-agent-sdk ``actions`` MCP server from recordable actions.
2
+
3
+ Thin wrapper over agent-tools' generic adapter: the ``ActionsRecorder`` is the
4
+ tool context, and tools are namespace-prefixed (one ``actions`` server hosts
5
+ every domain). Requires the ``claude-sdk`` optional extra.
6
+ """
7
+
8
+ from pathlib import Path
9
+
10
+ from agent_tools.claude_sdk import build_sdk_server
11
+ from agent_tools.registry import tool_name_for
12
+
13
+ from hackbot_runtime.actions import ACTIONS_SERVER_NAME
14
+ from hackbot_runtime.actions.recorder import ActionsRecorder
15
+ from hackbot_runtime.actions.tools import ACTIONS_INSTRUCTIONS, action_tools
16
+
17
+
18
+ def actions_server_for(
19
+ recorder: ActionsRecorder | None,
20
+ types: list[str] | None = None,
21
+ *,
22
+ fallback_artifacts_dir: Path = Path("artifacts"),
23
+ ):
24
+ """Return ``(recorder, sdk_server)`` for the enabled recordable actions.
25
+
26
+ ``recorder=None`` creates a local recorder that copies attachments under
27
+ ``fallback_artifacts_dir`` (standalone/script runs with no uploader).
28
+ ``types`` selects a subset by dotted id (e.g. ``bugzilla.update_bug``);
29
+ ``None`` exposes all.
30
+ """
31
+ if recorder is None:
32
+ recorder = ActionsRecorder(artifacts_dir=fallback_artifacts_dir)
33
+ return recorder, build_sdk_server(
34
+ ACTIONS_SERVER_NAME,
35
+ recorder,
36
+ action_tools(types),
37
+ prefix_namespace=True,
38
+ instructions=ACTIONS_INSTRUCTIONS,
39
+ )
40
+
41
+
42
+ def actions_to_tool_names(types: list[str]) -> list[str]:
43
+ """claude-agent-sdk tool ids for the given action types.
44
+
45
+ e.g. ``"bugzilla.update_bug"`` -> ``"mcp__actions__bugzilla_update_bug"``.
46
+ Kept beside ``actions_server_for`` so the ids stay in sync with the server it
47
+ builds (same server name + tool-name mapping).
48
+ """
49
+ return [f"mcp__{ACTIONS_SERVER_NAME}__{tool_name_for(t)}" for t in types]
@@ -0,0 +1,152 @@
1
+ """Email-domain recordable action.
2
+
3
+ An agent -- or the deterministic code around it, via :func:`record_email` --
4
+ records a report it wants delivered by email; the apply side sends it with
5
+ SendGrid (see ``handlers/email_handler.py``).
6
+
7
+ Recording rather than sending gives a notification the same properties as every
8
+ other action -- visible in the UI before it lands, delivered at most once, and
9
+ never sent at all for a run that did not succeed.
10
+
11
+ The team address, the sender and the local-testing override live apply-side, so
12
+ an agent only names the individuals its result concerns.
13
+ """
14
+
15
+ import re
16
+ from collections.abc import Iterable
17
+ from typing import Annotated
18
+
19
+ from agent_tools.registry import ToolError, tool, tools_in
20
+ from pydantic import Field
21
+
22
+ from hackbot_runtime.actions.recorder import ActionsRecorder, confirmation
23
+
24
+ ACTION_TYPE = "email.send"
25
+
26
+ # Substituted with the run's patch when the mail is sent. The agent decides
27
+ # whether the body mentions the patch at all, and how it is framed; this only
28
+ # says where the text goes.
29
+ PATCH_PLACEHOLDER = "{patch}"
30
+
31
+
32
+ def _params(
33
+ to: Iterable[str],
34
+ subject: str,
35
+ body_markdown: str,
36
+ attach_patch: bool = False,
37
+ ) -> dict:
38
+ subject = subject.strip()
39
+ body_markdown = body_markdown.strip()
40
+ if not subject:
41
+ raise ToolError("subject must not be blank")
42
+ if not body_markdown:
43
+ raise ToolError("body_markdown must not be blank")
44
+
45
+ recipients: list[str] = []
46
+ for address in to:
47
+ address = address.strip()
48
+ if address and address not in recipients:
49
+ recipients.append(address)
50
+
51
+ return {
52
+ "to": recipients,
53
+ "subject": subject,
54
+ "body_markdown": body_markdown,
55
+ "attach_patch": attach_patch,
56
+ }
57
+
58
+
59
+ @tool
60
+ async def send(
61
+ recorder: ActionsRecorder,
62
+ to: Annotated[
63
+ list[str],
64
+ Field(
65
+ description=(
66
+ "Who the report concerns, as email addresses. May be empty for a "
67
+ "report that concerns no individual; the team address is added "
68
+ "when the mail is sent, so never list it here."
69
+ )
70
+ ),
71
+ ],
72
+ subject: Annotated[
73
+ str,
74
+ Field(
75
+ description=(
76
+ "Subject line. Lead with the verdict, so it reads in an inbox "
77
+ "listing without opening the mail."
78
+ )
79
+ ),
80
+ ],
81
+ body_markdown: Annotated[
82
+ str,
83
+ Field(
84
+ description=(
85
+ "Body in Markdown: headings, lists, tables and fenced code all "
86
+ "render. Link every identifier a recipient would otherwise have "
87
+ "to look up."
88
+ )
89
+ ),
90
+ ],
91
+ reasoning: Annotated[
92
+ str,
93
+ Field(description="Why these recipients need to hear about it (audit log)."),
94
+ ],
95
+ ) -> str:
96
+ """Record an intended email.
97
+
98
+ Recorded into the run summary for human review -- does not send any mail.
99
+ """
100
+ action = recorder.record(
101
+ ACTION_TYPE, _params(to, subject, body_markdown), reasoning=reasoning
102
+ )
103
+ return confirmation(action)
104
+
105
+
106
+ def record_email(
107
+ recorder: ActionsRecorder,
108
+ *,
109
+ to: Iterable[str] = (),
110
+ subject: str,
111
+ body_markdown: str,
112
+ attach_patch: bool = False,
113
+ ) -> dict:
114
+ """Record a report the agent was never asked to decide on.
115
+
116
+ For a run whose outcome is always worth reporting: the wording is code, not a
117
+ model turn. ``to`` may be empty for a report that concerns no individual; the
118
+ handler still addresses the team.
119
+
120
+ The run's patch can travel two ways, independently: inline, by putting
121
+ :data:`PATCH_PLACEHOLDER` in the body, and as a file, with ``attach_patch``.
122
+ Either way it is read once when the mail is sent, so the diff a recipient
123
+ reads and the file they save cannot differ.
124
+ """
125
+ return recorder.record(
126
+ ACTION_TYPE,
127
+ _params(to, subject, body_markdown, attach_patch),
128
+ )
129
+
130
+
131
+ def demote_headings(md: str, by: int = 2) -> str:
132
+ """Shift ATX headings down ``by`` levels so agent prose nests under our own.
133
+
134
+ Lines inside code fences (and ``#include`` and the like, which lack the
135
+ required space after ``#``) are left untouched.
136
+ """
137
+ out = []
138
+ in_fence = False
139
+ for line in md.splitlines():
140
+ if line.lstrip().startswith(("```", "~~~")):
141
+ in_fence = not in_fence
142
+ out.append(line)
143
+ continue
144
+ match = re.match(r"(#{1,6}) ", line) if not in_fence else None
145
+ if match:
146
+ level = min(len(match.group(1)) + by, 6)
147
+ line = "#" * level + line[len(match.group(1)) :]
148
+ out.append(line)
149
+ return "\n".join(out)
150
+
151
+
152
+ TOOLS = tools_in(__name__)