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,208 @@
1
+ """GitHub-domain recordable actions.
2
+
3
+ Mirrors ``actions/phabricator.py``'s shape: the tools record an intended comment
4
+ or change (nothing is sent to GitHub here) and return a short confirmation
5
+ string. See hackbot-api's ``app/action_handlers/github_handler.py`` for the
6
+ apply side, which posts the comments, or pushes a branch carrying the run's
7
+ changes and opens a pull request.
8
+ """
9
+
10
+ from typing import Annotated, Any
11
+
12
+ from agent_tools.registry import ToolError, tool, tools_in
13
+ from pydantic import (
14
+ BaseModel,
15
+ Field,
16
+ StringConstraints,
17
+ ValidationError,
18
+ model_validator,
19
+ )
20
+
21
+ from hackbot_runtime.actions.recorder import ActionsRecorder, confirmation
22
+
23
+ ADD_COMMENT_ACTION_TYPE = "github.add_comment"
24
+ ADD_INLINE_COMMENTS_ACTION_TYPE = "github.add_inline_comments"
25
+ SUBMIT_PATCH_ACTION_TYPE = "github.submit_patch"
26
+
27
+ # Actions that deliver the working directory's changes to GitHub, gating the
28
+ # commit artifact built in ``context.publish_changes``. The GitHub counterpart
29
+ # of ``phabricator.PATCH_ACTION_TYPES``: kept separate so a GitHub submission
30
+ # does not also build a Phabricator diff, and vice versa.
31
+ PATCH_ACTION_TYPES = frozenset({SUBMIT_PATCH_ACTION_TYPE})
32
+
33
+ _Text = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]
34
+
35
+
36
+ class InlineComment(BaseModel):
37
+ path: Annotated[
38
+ _Text, Field(description="Path of the file in the repository, e.g. src/a.py.")
39
+ ]
40
+ line: Annotated[
41
+ int,
42
+ Field(
43
+ ge=1,
44
+ description=(
45
+ "Line in the new version of the file. It must appear in the pull "
46
+ "request's diff, as a changed line or the context around one."
47
+ ),
48
+ ),
49
+ ]
50
+ body: Annotated[_Text, Field(description="Comment body (Markdown supported).")]
51
+ start_line: Annotated[
52
+ int | None,
53
+ Field(
54
+ ge=1,
55
+ description="First line of a multi-line comment ending at `line`.",
56
+ ),
57
+ ] = None
58
+
59
+ @model_validator(mode="after")
60
+ def _start_line_before_line(self) -> InlineComment:
61
+ if self.start_line is not None and self.start_line >= self.line:
62
+ raise ValueError("start_line must be before line")
63
+ return self
64
+
65
+
66
+ # The tool adapters pass the agent's arguments through unvalidated, so these
67
+ # models are the enforcement; the tool signatures below are the agent's schema.
68
+ class _PullRequest(BaseModel):
69
+ # GitHub's own rules for owner and repository names.
70
+ repo: Annotated[str, Field(pattern=r"^[A-Za-z0-9-]+/[A-Za-z0-9._-]+$")]
71
+ pull_number: Annotated[int, Field(ge=1)]
72
+
73
+
74
+ class _Comment(_PullRequest):
75
+ text: _Text
76
+
77
+
78
+ class _InlineComments(_PullRequest):
79
+ comments: Annotated[list[InlineComment], Field(min_length=1)]
80
+ summary: _Text | None = None
81
+
82
+
83
+ def _validated(model: type[BaseModel], **values: Any) -> dict[str, Any]:
84
+ try:
85
+ validated = model.model_validate(values)
86
+ except ValidationError as exc:
87
+ raise ToolError(
88
+ "invalid GitHub action",
89
+ payload={
90
+ "error": "invalid GitHub action",
91
+ "details": exc.errors(include_url=False),
92
+ },
93
+ ) from exc
94
+ return validated.model_dump(mode="json", exclude_none=True)
95
+
96
+
97
+ _Repo = Annotated[
98
+ str,
99
+ Field(description='The repository, as "owner/name" (e.g. mozilla/ai-dev).'),
100
+ ]
101
+ _PullNumber = Annotated[int, Field(description="The pull request number.")]
102
+ _Reasoning = Annotated[
103
+ str, Field(description="Why you are recording this comment (for audit log).")
104
+ ]
105
+
106
+
107
+ @tool
108
+ async def add_comment(
109
+ recorder: ActionsRecorder,
110
+ repo: _Repo,
111
+ pull_number: _PullNumber,
112
+ text: Annotated[str, Field(description="Comment body (Markdown supported).")],
113
+ reasoning: _Reasoning,
114
+ ) -> str:
115
+ """Record an intended comment on a GitHub pull request's conversation.
116
+
117
+ Use this to reply on a pull request, for example to answer a question, or for
118
+ feedback that is not about particular lines; for those, use
119
+ ``add_inline_comments``. Recorded into the run summary for human review;
120
+ nothing is posted to GitHub during the run.
121
+ """
122
+ params = _validated(_Comment, repo=repo, pull_number=pull_number, text=text)
123
+ action = recorder.record(ADD_COMMENT_ACTION_TYPE, params, reasoning=reasoning)
124
+ return confirmation(action)
125
+
126
+
127
+ @tool
128
+ async def add_inline_comments(
129
+ recorder: ActionsRecorder,
130
+ repo: _Repo,
131
+ pull_number: _PullNumber,
132
+ comments: Annotated[
133
+ list[InlineComment],
134
+ Field(min_length=1, description="The line comments, at least one."),
135
+ ],
136
+ reasoning: _Reasoning,
137
+ summary: Annotated[
138
+ str | None,
139
+ Field(description="Optional overall comment shown above the line comments."),
140
+ ] = None,
141
+ ) -> str:
142
+ """Record an intended review of a GitHub pull request: comments on its lines.
143
+
144
+ The comments are posted together as one review, so pass every line comment
145
+ for the pull request in a single call; each call becomes a separate review.
146
+ Recorded into the run summary for human review; nothing is posted to GitHub
147
+ during the run.
148
+ """
149
+ params = _validated(
150
+ _InlineComments,
151
+ repo=repo,
152
+ pull_number=pull_number,
153
+ comments=comments,
154
+ summary=summary,
155
+ )
156
+ action = recorder.record(
157
+ ADD_INLINE_COMMENTS_ACTION_TYPE, params, reasoning=reasoning
158
+ )
159
+ return confirmation(action)
160
+
161
+
162
+ @tool
163
+ async def submit_patch(
164
+ recorder: ActionsRecorder,
165
+ title: Annotated[
166
+ str,
167
+ Field(
168
+ description=(
169
+ "Title for the new pull request: a single line describing the "
170
+ "fix, as you would write a commit message subject."
171
+ )
172
+ ),
173
+ ],
174
+ reasoning: Annotated[
175
+ str, Field(description="Why you are submitting this patch (for audit log).")
176
+ ],
177
+ body: Annotated[
178
+ str | None,
179
+ Field(
180
+ description=(
181
+ "Pull request description (GitHub Markdown). Explain what the "
182
+ "change does and how you verified it. Keep it concise and do not "
183
+ "narrate the investigation."
184
+ ),
185
+ ),
186
+ ] = None,
187
+ ) -> str:
188
+ """Submit your fix for review as a new GitHub pull request.
189
+
190
+ This is how you deliver a code fix to a repository hosted on GitHub. The
191
+ pull request is opened from a new branch against the repository's default
192
+ branch, as a draft.
193
+
194
+ You do not supply a patch file. Your final code changes in the working
195
+ directory (and any commits you made) are squashed into the pull request's
196
+ one commit, with its title and description as the message, so make and
197
+ verify all your edits first, then call this once you are done. Calling it
198
+ records the submission as a proposed action for review; nothing is sent to
199
+ GitHub during the run.
200
+
201
+ Later actions can reference its `url`.
202
+ """
203
+ params: dict = {"title": title, "body": body}
204
+ action = recorder.record(SUBMIT_PATCH_ACTION_TYPE, params, reasoning=reasoning)
205
+ return confirmation(action)
206
+
207
+
208
+ TOOLS = tools_in(__name__)
@@ -0,0 +1,39 @@
1
+ """Build the ``actions`` MCP server from recordable actions.
2
+
3
+ Thin wrapper over agent-tools' MCP server adapter: the ``ActionsRecorder`` is
4
+ the tool context, and tools are namespace-prefixed (one ``actions`` server hosts
5
+ every domain). Requires the ``mcp-server`` optional extra.
6
+ """
7
+
8
+ from pathlib import Path
9
+
10
+ from agent_tools.mcp_server import build_mcp_server
11
+ from fastmcp import FastMCP
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
+ ) -> tuple[ActionsRecorder, FastMCP]:
24
+ """Return ``(recorder, 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_mcp_server(
34
+ ACTIONS_SERVER_NAME,
35
+ recorder,
36
+ action_tools(types),
37
+ prefix_namespace=True,
38
+ instructions=ACTIONS_INSTRUCTIONS,
39
+ )
@@ -0,0 +1,234 @@
1
+ """Phabricator-domain recordable actions.
2
+
3
+ Mirrors ``actions/bugzilla.py``'s shape: the handler records an intended
4
+ change (nothing is submitted to Phabricator here) and returns a short
5
+ confirmation string. See ``actions/handlers/phabricator_handler.py`` for the
6
+ apply side.
7
+
8
+ Creating a revision and updating one are deliberately two tools: each takes
9
+ only the parameters its own case needs, so the agent cannot create a revision
10
+ when it meant to update one (or invent a revision id) by getting one optional
11
+ argument wrong.
12
+ """
13
+
14
+ import re
15
+ from typing import Annotated
16
+
17
+ from agent_tools.registry import ToolError, tool, tools_in
18
+ from pydantic import Field
19
+
20
+ from hackbot_runtime.actions.recorder import ActionsRecorder, confirmation
21
+
22
+ SUBMIT_PATCH_ACTION_TYPE = "phabricator.submit_patch"
23
+ UPDATE_PATCH_ACTION_TYPE = "phabricator.update_patch"
24
+ ADD_COMMENT_ACTION_TYPE = "phabricator.add_comment"
25
+
26
+ # Both patch actions submit the working directory's changes as a diff, so
27
+ # anything gated on "this run submits a patch" — today the diff artifact built
28
+ # in ``context.publish_changes`` — has to cover both types.
29
+ PATCH_ACTION_TYPES = frozenset({SUBMIT_PATCH_ACTION_TYPE, UPDATE_PATCH_ACTION_TYPE})
30
+
31
+ _PHABRICATOR_TEST_PLAN_HEADER_RE = re.compile(
32
+ r"^(?:Test Plan|Testplan|Tested|Tests):",
33
+ re.IGNORECASE | re.MULTILINE,
34
+ )
35
+
36
+
37
+ def _validate_summary(summary: str | None, tool_name: str) -> None:
38
+ if not summary:
39
+ return
40
+
41
+ match = _PHABRICATOR_TEST_PLAN_HEADER_RE.search(summary)
42
+ if match:
43
+ raise ToolError(
44
+ f'Invalid Phabricator summary: "{match.group()}" at the beginning of '
45
+ "a line belongs in the Test Plan field. Move the verification details "
46
+ f"to the test_plan argument and call {tool_name} again."
47
+ )
48
+
49
+
50
+ @tool
51
+ async def submit_patch(
52
+ recorder: ActionsRecorder,
53
+ bug_id: Annotated[
54
+ int | str,
55
+ Field(
56
+ description=(
57
+ "Bug this patch fixes: a bug number, or a reference to a bug "
58
+ "filed by create_bug in this run."
59
+ )
60
+ ),
61
+ ],
62
+ title: Annotated[
63
+ str,
64
+ Field(
65
+ description=(
66
+ "Title for the new revision: a single line describing the fix, "
67
+ "as you would write a commit message subject. Do not include "
68
+ "reviewer annotations (r=... or r?...): reviewer selection is "
69
+ "handled on the Phabricator side."
70
+ )
71
+ ),
72
+ ],
73
+ reasoning: Annotated[
74
+ str, Field(description="Why you are submitting this patch (for audit log).")
75
+ ],
76
+ test_plan: Annotated[
77
+ str | None,
78
+ Field(
79
+ description=(
80
+ "Revision test plan. If you recorded a Try push, link it here."
81
+ )
82
+ ),
83
+ ] = None,
84
+ summary: Annotated[
85
+ str | None,
86
+ Field(
87
+ description=(
88
+ "Revision summary/description. Keep it concise and useful for permanent "
89
+ "history. Do not restate the bug, narrate the investigation or "
90
+ "implementation process. Keep test and verification details in "
91
+ "test_plan instead."
92
+ ),
93
+ ),
94
+ ] = None,
95
+ parent_revision_id: Annotated[
96
+ int | None,
97
+ Field(
98
+ description=(
99
+ "The revision this patch stacks on (the number after D), when it "
100
+ "belongs on top of an existing revision rather than on its own."
101
+ ),
102
+ ),
103
+ ] = None,
104
+ ) -> str:
105
+ """Submit your fix for review as a new Phabricator revision.
106
+
107
+ This is how you deliver a code fix. Do not attach the patch to a bug: a
108
+ Phabricator revision is the correct destination for a fix, not a bug
109
+ attachment. If the fix belongs on a revision that already exists (for
110
+ example, you were asked for changes on it), use ``update_patch`` instead.
111
+
112
+ You do not supply a patch file. Your final code changes in the working
113
+ directory are submitted as the revision's diff, so make and verify all your
114
+ edits first, then call this once you are done. Calling it records the
115
+ submission as a proposed action for review; it is not sent to Phabricator
116
+ during the run.
117
+
118
+ Later actions can reference its `revision_id` and `url`.
119
+ """
120
+ _validate_summary(summary, "submit_patch")
121
+ params: dict = {
122
+ "bug_id": bug_id,
123
+ "title": title,
124
+ "summary": summary,
125
+ "test_plan": test_plan,
126
+ }
127
+ if parent_revision_id is not None:
128
+ params["parent_revision_id"] = parent_revision_id
129
+ action = recorder.record(SUBMIT_PATCH_ACTION_TYPE, params, reasoning=reasoning)
130
+ return confirmation(action)
131
+
132
+
133
+ @tool
134
+ async def update_patch(
135
+ recorder: ActionsRecorder,
136
+ revision_id: Annotated[
137
+ int,
138
+ Field(
139
+ description=(
140
+ "The existing Phabricator revision to attach the new diff to, as "
141
+ "a number (12345 for D12345). Only pass a revision id you were "
142
+ "given or read from the bug: never guess one."
143
+ )
144
+ ),
145
+ ],
146
+ reasoning: Annotated[
147
+ str, Field(description="Why you are updating this patch (for audit log).")
148
+ ],
149
+ title: Annotated[
150
+ str | None,
151
+ Field(
152
+ description=(
153
+ "New title for the revision: the commit message subject line. "
154
+ "Do not include reviewer annotations (r=... or r?...). "
155
+ "Leave unset to keep the same title."
156
+ )
157
+ ),
158
+ ] = None,
159
+ summary: Annotated[
160
+ str | None,
161
+ Field(
162
+ description=(
163
+ "New summary for the revision: the commit message body. "
164
+ "Replaces the current summary entirely, so pass the full text. "
165
+ "Keep test and verification details in test_plan instead. "
166
+ "Leave unset to keep the same summary."
167
+ )
168
+ ),
169
+ ] = None,
170
+ test_plan: Annotated[
171
+ str | None,
172
+ Field(
173
+ description=(
174
+ "New test plan for the revision. Replaces the current one "
175
+ "entirely. Leave unset to keep the same test plan."
176
+ )
177
+ ),
178
+ ] = None,
179
+ ) -> str:
180
+ """Submit your fix as a new diff on an existing Phabricator revision.
181
+
182
+ Use this only when a revision for this work already exists (for example, you
183
+ are addressing review comments on it) and you know its id. To deliver a fix
184
+ that has no revision yet, use ``submit_patch`` instead. If the review only
185
+ asks a question and no code change is warranted, use ``add_comment``.
186
+
187
+ You do not supply a patch file. Your final code changes in the working
188
+ directory are submitted as the new diff, so make and verify all your edits
189
+ first, then call this once you are done. Calling it records the submission as
190
+ a proposed action for review; it is not sent to Phabricator during the run.
191
+
192
+ The revision keeps its title, summary, test plan, and bug association
193
+ unless you pass a new title, summary, or test_plan.
194
+ """
195
+ _validate_summary(summary, "update_patch")
196
+
197
+ params: dict = {"revision_id": revision_id}
198
+ if title:
199
+ params["title"] = title
200
+ if summary:
201
+ params["summary"] = summary
202
+ if test_plan:
203
+ params["test_plan"] = test_plan
204
+ action = recorder.record(UPDATE_PATCH_ACTION_TYPE, params, reasoning=reasoning)
205
+ return confirmation(action)
206
+
207
+
208
+ @tool
209
+ async def add_comment(
210
+ recorder: ActionsRecorder,
211
+ revision_id: Annotated[
212
+ int, Field(description="Differential revision to comment on (the D number).")
213
+ ],
214
+ text: Annotated[str, Field(description="Comment body (Remarkup supported).")],
215
+ reasoning: Annotated[
216
+ str, Field(description="Why you are recording this comment (for audit log).")
217
+ ],
218
+ ) -> str:
219
+ """Record an intended comment on a Phabricator revision.
220
+
221
+ Use this to reply on a revision — for example, to answer a question — when
222
+ no code change is required. This does not deliver a fix: to submit code
223
+ changes, use ``submit_patch`` instead. Recorded into the run summary for
224
+ human review; nothing is posted to Phabricator during the run.
225
+ """
226
+ action = recorder.record(
227
+ ADD_COMMENT_ACTION_TYPE,
228
+ {"revision_id": revision_id, "text": text},
229
+ reasoning=reasoning,
230
+ )
231
+ return confirmation(action)
232
+
233
+
234
+ TOOLS = tools_in(__name__)
@@ -0,0 +1,146 @@
1
+ import copy
2
+ import uuid
3
+ from collections.abc import Callable, Mapping, Sequence
4
+ from pathlib import Path
5
+
6
+ from agent_tools.registry import ToolError
7
+
8
+ from hackbot_runtime.artifacts import publish_file
9
+ from hackbot_runtime.uploader import SignedPolicyUploader
10
+
11
+ # Callback run on an action of one type before it is recorded. It receives the
12
+ # action dict (``type``/``params``/``reasoning``) and
13
+ # may mutate it in place; the return value is ignored. Raising aborts the
14
+ # recording (nothing is appended and no attachment is published), so a hook
15
+ # doubles as a validation gate: raise ``ToolError`` to report the reason back to
16
+ # the agent.
17
+ ActionHook = Callable[[dict], None]
18
+
19
+
20
+ def confirmation(action: dict) -> str:
21
+ """Return the agent-facing confirmation for a recorded action."""
22
+ return f"Recorded {action['type']} (ID: {action['action_id']})."
23
+
24
+
25
+ class ActionsRecorder:
26
+ """Collects structured actions an agent decided to take.
27
+
28
+ The runtime serialises the collected list into the
29
+ ``actions`` array of ``summary.json``; a downstream apply step picks
30
+ them up from there.
31
+
32
+ Framework-agnostic: knows nothing about MCP, LangChain, or any specific
33
+ action domain. Per-framework adapters wrap this and translate their
34
+ native tool calls into ``record(...)`` calls.
35
+
36
+ ``hooks`` maps an action type to the :data:`ActionHook` callbacks to run,
37
+ in order, before that action is appended. They live here rather than in the
38
+ action declarations so the runtime can attach behaviour that cuts across
39
+ domains (enrichment, validation) without every ``@tool`` handler knowing
40
+ about it.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ uploader: SignedPolicyUploader | None = None,
46
+ artifacts_dir: Path | None = None,
47
+ hooks: Mapping[str, Sequence[ActionHook]] = {},
48
+ ) -> None:
49
+ self._actions: dict[str, dict] = {}
50
+ self._uploader = uploader
51
+ self._artifacts_dir = artifacts_dir
52
+ self._hooks = {
53
+ action_type: list(action_hooks)
54
+ for action_type, action_hooks in hooks.items()
55
+ }
56
+
57
+ def add_hook(self, action_type: str, hook: ActionHook) -> None:
58
+ """Append ``hook`` to the hooks run for ``action_type``.
59
+
60
+ For wiring a hook after construction; it runs after any hook already
61
+ registered for that type.
62
+ """
63
+ self._hooks.setdefault(action_type, []).append(hook)
64
+
65
+ def record(
66
+ self,
67
+ action_type: str,
68
+ params: dict,
69
+ *,
70
+ reasoning: str | None = None,
71
+ attachments: dict[str, Path] | None = None,
72
+ ) -> dict:
73
+ """Record an action and return a detached copy with its ID.
74
+
75
+ ``action_type`` uses ``<domain>.<verb>`` (e.g. ``bugzilla.update_bug``,
76
+ ``phabricator.create_revision``). ``params`` is action-specific data
77
+ the apply step will need. ``attachments`` maps a logical name to a
78
+ local file path; each file is preserved under the stable key
79
+ ``attachments/<action_id>/<name>``: uploaded via the runtime
80
+ uploader when one is configured, otherwise copied into the local
81
+ artifacts directory (so it is retrievable from compose/direct runs).
82
+ The recorded action references it by that key; the original local path
83
+ is not persisted (it disappears with the container).
84
+
85
+ ``params`` may reference an earlier action's apply-time result by its
86
+ action ID (e.g. a Bugzilla comment's text containing
87
+ ``{{actions.<action_id>.url}}`` after a ``phabricator.submit_patch``
88
+ action). Resolved by the apply step, since the result doesn't exist yet
89
+ at record time.
90
+
91
+ Any hooks registered for ``action_type`` run on the action, in
92
+ registration order, and may still change it (see :data:`ActionHook`). A
93
+ hook that raises propagates to the caller and the action is not
94
+ recorded. Hooks run before ``attachments`` are published, so an aborted
95
+ recording leaves nothing behind: the action the hooks see carries no
96
+ ``attachments`` key yet.
97
+ """
98
+ action_id = uuid.uuid7().hex
99
+ action: dict = {
100
+ "type": action_type,
101
+ "params": params,
102
+ "reasoning": reasoning,
103
+ }
104
+
105
+ for hook in self._hooks.get(action_type, ()):
106
+ hook(action)
107
+
108
+ if attachments:
109
+ recorded_attachments: list[dict] = []
110
+ for name, path in attachments.items():
111
+ key = publish_file(
112
+ self._uploader,
113
+ self._artifacts_dir,
114
+ f"attachments/{action_id}/{name}",
115
+ path,
116
+ )
117
+ recorded_attachments.append({"name": name, "uploaded_key": key})
118
+ action["attachments"] = recorded_attachments
119
+
120
+ self._actions[action_id] = action
121
+ return _detach(action_id, action)
122
+
123
+ def list_actions(self) -> list[dict]:
124
+ """Return complete copies of the current actions with stable in-run IDs."""
125
+ return [
126
+ _detach(action_id, action) for action_id, action in self._actions.items()
127
+ ]
128
+
129
+ def remove_action(self, action_id: str) -> dict:
130
+ """Remove the action with the given ID and return a copy of it."""
131
+ action = self._actions.get(action_id)
132
+ if action is None:
133
+ raise ToolError(f"No recorded action with ID {action_id!r}.")
134
+
135
+ removed = _detach(action_id, action)
136
+ del self._actions[action_id]
137
+ return removed
138
+
139
+ @property
140
+ def actions(self) -> list[dict]:
141
+ return list(self._actions.values())
142
+
143
+
144
+ def _detach(action_id: str, action: dict) -> dict:
145
+ """Return a detached copy of an action with its ID."""
146
+ return {**copy.deepcopy(action), "action_id": action_id}