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,431 @@
1
+ """Collect an agent's source-tree changes into a git-am patch + metadata.
2
+
3
+ After an agent runs, its work may be committed locally (each commit with its own
4
+ message/author) or left uncommitted/untracked. This module captures all of it,
5
+ relative to the commit the checkout started from, as a single mbox patch that
6
+ ``git am`` applies in one command — preserving the local commit history — plus a
7
+ JSON summary of the commits and files touched.
8
+
9
+ Any uncommitted remainder is wrapped into one synthetic commit first, so nothing
10
+ is lost. The checkout is ephemeral (one run per container), so mutating its index
11
+ and creating that commit is safe.
12
+ """
13
+
14
+ import base64
15
+ import contextlib
16
+ import itertools
17
+ import logging
18
+ import os
19
+ import re
20
+ import subprocess
21
+ import tempfile
22
+ from collections.abc import Iterator
23
+ from pathlib import Path
24
+ from typing import NamedTuple
25
+
26
+ log = logging.getLogger("hackbot_runtime.changes")
27
+
28
+ _FULL_SHA_RE = re.compile(r"[0-9a-f]{40}")
29
+
30
+ # Author stamped on the synthetic commit that wraps any uncommitted remainder.
31
+ _WIP_NAME = "Hackbot"
32
+ _WIP_EMAIL = "hackbot@mozilla.tld"
33
+ WIP_MESSAGE = "Uncommitted agent changes"
34
+
35
+ # Record separator for parsing ``git log`` output (NUL avoids clashing with
36
+ # anything in commit messages).
37
+ _FIELD_SEP = "\x1f"
38
+ _RECORD_SEP = "\x1e"
39
+
40
+
41
+ class ChangeSet(NamedTuple):
42
+ """The collected agent changes: an mbox patch plus its metadata."""
43
+
44
+ patch: bytes
45
+ metadata: dict
46
+
47
+
48
+ def _git(repo: Path, *args: str) -> str:
49
+ """Run a git command in ``repo`` and return its stdout (text)."""
50
+ return subprocess.run(
51
+ ["git", "-C", str(repo), *args],
52
+ check=True,
53
+ capture_output=True,
54
+ text=True,
55
+ ).stdout
56
+
57
+
58
+ def _git_bytes(repo: Path, *args: str) -> bytes:
59
+ """Run a git command in ``repo`` and return its stdout (bytes).
60
+
61
+ Used for ``format-patch``, whose output may contain binary diffs.
62
+ """
63
+ return subprocess.run(
64
+ ["git", "-C", str(repo), *args],
65
+ check=True,
66
+ capture_output=True,
67
+ ).stdout
68
+
69
+
70
+ def base_commit(repo: Path) -> str:
71
+ """Return the current HEAD sha — the base the agent starts editing from."""
72
+ return _git(repo, "rev-parse", "HEAD").strip()
73
+
74
+
75
+ # Where publish_changes() puts the run's patch; the same key downstream reads.
76
+ PATCH_ARTIFACT = "changes/changes.patch"
77
+
78
+
79
+ def has_changes(repo: Path, base: str) -> bool:
80
+ """Whether the agent left anything for :func:`collect` to publish.
81
+
82
+ Read-only, unlike ``collect``, which commits the working tree as it goes: for
83
+ code that needs the answer mid-run without disturbing what the agent is
84
+ editing.
85
+ """
86
+ return _has_uncommitted(repo) or bool(
87
+ _git(repo, "rev-list", "-1", f"{base}..HEAD").strip()
88
+ )
89
+
90
+
91
+ def _has_uncommitted(repo: Path) -> bool:
92
+ return bool(_git(repo, "status", "--porcelain").strip())
93
+
94
+
95
+ def commit_all(repo: Path, message: str, *, author: str | None = None) -> bool:
96
+ """Stage everything in ``repo`` and commit it, if there is anything to commit.
97
+
98
+ Returns ``True`` if a commit was made, ``False`` if the tree was clean.
99
+
100
+ The committer identity is passed explicitly because agent containers often
101
+ have no git identity configured, which would make ``git commit`` fail
102
+ outright. ``author`` (``"Name <email>"``) attributes the change to someone
103
+ else, for commits that replay another author's work; the committer stays
104
+ hackbot either way, which is the honest split and what `git` is designed for.
105
+ """
106
+ if not _has_uncommitted(repo):
107
+ return False
108
+ _git(repo, "add", "-A")
109
+ _git(
110
+ repo,
111
+ "-c",
112
+ f"user.name={_WIP_NAME}",
113
+ "-c",
114
+ f"user.email={_WIP_EMAIL}",
115
+ "commit",
116
+ "--no-verify",
117
+ *(["--author", author] if author else []),
118
+ "-m",
119
+ message,
120
+ )
121
+ return True
122
+
123
+
124
+ def _commit_metadata(repo: Path, base: str) -> list[dict]:
125
+ """Structured info for each commit in ``base..HEAD`` (oldest first)."""
126
+ fmt = _FIELD_SEP.join(["%H", "%an", "%ae", "%aI", "%s", "%b"]) + _RECORD_SEP
127
+ out = _git(repo, "log", "--reverse", f"--format={fmt}", f"{base}..HEAD")
128
+ commits = []
129
+ for record in out.split(_RECORD_SEP):
130
+ record = record.strip("\n")
131
+ if not record:
132
+ continue
133
+ sha, author_name, author_email, authored_date, subject, body = record.split(
134
+ _FIELD_SEP
135
+ )
136
+ commits.append(
137
+ {
138
+ "sha": sha,
139
+ "author_name": author_name,
140
+ "author_email": author_email,
141
+ "authored_date": authored_date,
142
+ "subject": subject,
143
+ "body": body,
144
+ }
145
+ )
146
+ return commits
147
+
148
+
149
+ def _synthetic_commit(repo: Path, base: str) -> str:
150
+ """Create a detached commit object squashing ``base..HEAD``'s tree.
151
+
152
+ Doesn't touch the working tree, index, or branch pointer — `commit-tree`
153
+ just writes one new commit object with `base` as its sole parent, giving
154
+ `build_phabricator_diff` a single commit to diff (moz-phab's diff-tree
155
+ based diffing only supports one commit vs. its immediate parent, no
156
+ range).
157
+ """
158
+ tree = _git(repo, "rev-parse", "HEAD^{tree}").strip()
159
+ # Pass an explicit identity (as commit_all does): the synthetic
160
+ # commit's author is throwaway — only its tree diff is used — but
161
+ # `commit-tree` errors under `user.useConfigOnly=true` and otherwise
162
+ # invents a `user@hostname` author when the container has no git identity
163
+ # configured. A fixed identity keeps it deterministic and unconditional.
164
+ return _git(
165
+ repo,
166
+ "-c",
167
+ f"user.name={_WIP_NAME}",
168
+ "-c",
169
+ f"user.email={_WIP_EMAIL}",
170
+ "commit-tree",
171
+ tree,
172
+ "-p",
173
+ base,
174
+ "-m",
175
+ "hackbot: squashed changes for Phabricator diff",
176
+ ).strip()
177
+
178
+
179
+ def _local_commits_property(repo: Path, node: str, base: str) -> dict:
180
+ """The git side of moz-phab's ``local:commits`` diff property for ``node``.
181
+
182
+ Phabricator stores this alongside the diff so ``moz-phab patch`` can
183
+ reconstruct a real local commit from the revision; without it, patching a
184
+ hackbot-created revision fails with "a diff without commit information
185
+ detected". Only the fields knowable from git are set here (author, time,
186
+ tree, node, parents); the apply-side handler fills in ``summary`` and the
187
+ arc-formatted ``message`` once it has the revision URL, matching moz-phab's
188
+ ``conduit.set_diff_property``.
189
+ """
190
+ fmt = _FIELD_SEP.join(["%an", "%ae", "%at", "%T"])
191
+ out = _git(repo, "show", "-s", f"--format={fmt}", node)
192
+ author_name, author_email, epoch, tree = out.rstrip("\n").split(_FIELD_SEP)
193
+ return {
194
+ node: {
195
+ "author": author_name,
196
+ "authorEmail": author_email,
197
+ "time": int(epoch),
198
+ "commit": node,
199
+ "parents": [base],
200
+ "tree": tree,
201
+ }
202
+ }
203
+
204
+
205
+ @contextlib.contextmanager
206
+ def _ambient_git_identity() -> Iterator[None]:
207
+ """Give moz-phab an ambient git identity for its `git config --list` check.
208
+
209
+ moz-phab's git client reads ``user.email`` from the *ambient* git config
210
+ (not the target repo's local config) and refuses to run without it. Agent
211
+ containers and CI often have no global identity, so point
212
+ ``GIT_CONFIG_GLOBAL`` at a throwaway config carrying a hackbot identity for
213
+ the duration of the call (moz-phab copies ``os.environ`` when it builds its
214
+ git client). The identity is cosmetic: moz-phab is only ever asked to build
215
+ a diff or apply a patch here, never to author a commit.
216
+ """
217
+ with tempfile.NamedTemporaryFile("w", suffix=".gitconfig") as gc:
218
+ gc.write(f"[user]\n\temail = {_WIP_EMAIL}\n\tname = {_WIP_NAME}\n")
219
+ gc.flush()
220
+ overrides = {"GIT_CONFIG_GLOBAL": gc.name, "GIT_CONFIG_SYSTEM": os.devnull}
221
+ previous = {k: os.environ.get(k) for k in overrides}
222
+ os.environ.update(overrides)
223
+ try:
224
+ yield
225
+ finally:
226
+ for key, prev in previous.items():
227
+ if prev is None:
228
+ os.environ.pop(key, None)
229
+ else:
230
+ os.environ[key] = prev
231
+
232
+
233
+ def build_phabricator_diff(repo: Path, base: str, repo_url: str) -> dict | None:
234
+ """Build the artifact for submitting a Phabricator revision.
235
+
236
+ Returns ``{"diff": <differential.creatediff payload>, "local_commits":
237
+ <partial local:commits property>}`` (or ``None`` on failure), published as a
238
+ single ``phabricator_diff.json`` artifact. The apply-side handler sends
239
+ ``diff`` to ``differential.creatediff``, completes ``local_commits`` (summary
240
+ + message), and stores it on the resulting diff via
241
+ ``differential.setdiffproperty`` so ``moz-phab patch`` can reconstruct a real
242
+ commit from the revision (see `_local_commits_property`).
243
+
244
+ Uses ``moz-phab``'s own diff-building code (``mozphab.git``/``mozphab.diff``,
245
+ imported as a library — requires the ``hackbot-runtime[phabricator]``
246
+ extra) against ``repo``, which the agent already has fully checked out
247
+ for its own work — no separate clone or checkout happens here. Returns
248
+ ``None`` if building the diff fails for any reason (e.g. the checkout
249
+ lacks an ``.arcconfig``, or nothing actually changed) — this is
250
+ best-effort, gated by the caller on whether a Phabricator patch action
251
+ was even recorded, so a failure here shouldn't break an otherwise
252
+ successful run.
253
+
254
+ ``repositoryPHID`` is deliberately not included here — it's resolved by
255
+ the apply-side handler instead, since it's specific to which Phabricator
256
+ instance/environment (staging vs. prod) the diff actually gets submitted
257
+ to, and that shouldn't be baked into an artifact built at agent-run time.
258
+ """
259
+ try:
260
+ from mozphab.args import parse_args
261
+ from mozphab.commits import Commit
262
+ from mozphab.git import Git
263
+ except ImportError:
264
+ log.warning(
265
+ "hackbot-runtime[phabricator] extra not installed; "
266
+ "cannot build a Phabricator diff"
267
+ )
268
+ return None
269
+
270
+ try:
271
+ node = _synthetic_commit(repo, base)
272
+ with _ambient_git_identity():
273
+ mozphab_repo = Git(str(repo))
274
+ # `set_args` needs a fully-populated argparse.Namespace matching what
275
+ # moz-phab's own CLI would build (several unrelated code paths read
276
+ # attributes off it) — going through its real parser instead of
277
+ # hand-listing the handful of attributes get_diff() happens to touch
278
+ # today, which would silently bit-rot on a moz-phab upgrade.
279
+ mozphab_repo.set_args(parse_args(["submit", "--yes"]))
280
+ diff = mozphab_repo.get_diff(Commit(node=node))
281
+ except Exception:
282
+ log.warning("Could not build Phabricator diff for %s", repo, exc_info=True)
283
+ return None
284
+
285
+ changes_payload = [change.to_conduit(node) for change in diff.changes.values()]
286
+ if not changes_payload:
287
+ return None
288
+
289
+ diff_payload = {
290
+ "changes": changes_payload,
291
+ "sourceMachine": repo_url,
292
+ "sourcePath": str(repo),
293
+ "sourceControlBaseRevision": base,
294
+ "sourceControlPath": "/",
295
+ "sourceControlSystem": "git",
296
+ "branch": "HEAD",
297
+ "creationMethod": "hackbot",
298
+ "lintStatus": "none",
299
+ "unitStatus": "none",
300
+ }
301
+ return {
302
+ "diff": diff_payload,
303
+ "local_commits": _local_commits_property(repo, node, base),
304
+ }
305
+
306
+
307
+ def build_try_push(repo: Path, base: str) -> dict | None:
308
+ """Build the artifact for pushing the agent's changes to the try server."""
309
+ if not _FULL_SHA_RE.fullmatch(base):
310
+ log.warning(
311
+ "Cannot build a try push from base commit %r: Lando needs a full "
312
+ "40-character published commit hash",
313
+ base,
314
+ )
315
+ return None
316
+
317
+ # Normally already done by `collect`; repeated here (it is a no-op on a
318
+ # clean tree) so this does not silently drop the agent's uncommitted work if
319
+ # it is ever called on its own.
320
+ commit_all(repo, WIP_MESSAGE)
321
+
322
+ revisions = _git(repo, "rev-list", "--reverse", f"{base}..HEAD").split()
323
+ if not revisions:
324
+ return None
325
+
326
+ return {
327
+ "base_commit": base,
328
+ "base_commit_vcs": "git",
329
+ "patch_format": "git-format-patch",
330
+ "patches": [
331
+ base64.b64encode(
332
+ _git_bytes(repo, "format-patch", "--binary", "--stdout", "-1", revision)
333
+ ).decode("ascii")
334
+ for revision in revisions
335
+ ],
336
+ }
337
+
338
+
339
+ # A submodule entry: its tree entry points at a commit, not a blob.
340
+ _GITLINK_MODE = "160000"
341
+
342
+
343
+ def _github_file_changes(repo: Path, parent: str, commit: str) -> list[dict]:
344
+ """The tree entries ``commit`` changes relative to ``parent``.
345
+
346
+ Each entry is ``{"path", "mode"}`` plus one of ``"content"`` (the new blob,
347
+ base64-encoded so binary files survive JSON), ``"sha"`` (a submodule's new
348
+ commit) or ``"deleted": True``. Renames are reported as a deletion plus an
349
+ addition, which is how a git tree records them anyway.
350
+ """
351
+ out = _git_bytes(
352
+ repo, "diff-tree", "-r", "-z", "--no-renames", "--no-commit-id", parent, commit
353
+ )
354
+ # -z output is ":<srcmode> <dstmode> <srcsha> <dstsha> <status>\0<path>\0" per
355
+ # entry, with paths unquoted. --no-renames keeps it to one path per entry (a
356
+ # rename or copy would carry two), and strict pairing raises if that ever
357
+ # stops holding. A commit that changes no files prints nothing at all. GitHub
358
+ # only takes UTF-8 paths, so any other path raises here rather than being
359
+ # pushed mangled.
360
+ fields = out.removesuffix(b"\0").split(b"\0") if out else []
361
+ entries = []
362
+ for header, raw_path in itertools.batched(fields, 2, strict=True):
363
+ src_mode, dst_mode, _src_sha, dst_sha, status = header.lstrip(b":").split()
364
+ path = raw_path.decode("utf-8")
365
+ if status == b"D":
366
+ entries.append({"path": path, "mode": src_mode.decode(), "deleted": True})
367
+ elif dst_mode.decode() == _GITLINK_MODE:
368
+ entries.append(
369
+ {"path": path, "mode": _GITLINK_MODE, "sha": dst_sha.decode()}
370
+ )
371
+ else:
372
+ blob = _git_bytes(repo, "cat-file", "blob", dst_sha.decode())
373
+ entries.append(
374
+ {
375
+ "path": path,
376
+ "mode": dst_mode.decode(),
377
+ "content": base64.b64encode(blob).decode("ascii"),
378
+ }
379
+ )
380
+ return entries
381
+
382
+
383
+ def build_github_commit(repo: Path, base: str, repo_url: str) -> dict | None:
384
+ """Build the artifact for pushing the agent's changes to GitHub.
385
+
386
+ hackbot-api has no git checkout (or git binary) to ``git am`` the run's
387
+ patch into, so this captures ``base..HEAD`` squashed into one commit, as
388
+ for Phabricator, in the shape GitHub's Git Data API takes: the files it
389
+ changes, with their new contents. The apply-side handler creates that
390
+ commit on top of ``base`` from this alone.
391
+
392
+ ``base`` must be a commit the GitHub repository already has (the published
393
+ base, as for a try push), since the new commit is parented on it. Returns
394
+ ``None`` when the tree is unchanged from ``base``.
395
+ """
396
+ # Normally already done by `collect`; repeated here (a no-op on a clean
397
+ # tree) so this does not drop uncommitted work if called on its own.
398
+ commit_all(repo, WIP_MESSAGE)
399
+
400
+ file_changes = _github_file_changes(repo, base, "HEAD")
401
+ if not file_changes:
402
+ return None
403
+ return {"repo_url": repo_url, "base_commit": base, "changes": file_changes}
404
+
405
+
406
+ def collect(
407
+ repo: Path, base: str, repo_url: str, message: str = WIP_MESSAGE
408
+ ) -> ChangeSet | None:
409
+ """Collect changes in ``repo`` since ``base`` as a patch plus metadata.
410
+
411
+ Returns ``None`` when the agent made no changes at all (nothing committed and
412
+ a clean working tree). Otherwise returns a :class:`ChangeSet` whose ``patch``
413
+ is an mbox (``git format-patch`` output) applied with ``git am`` and whose
414
+ ``metadata`` describes the base, the commits, and the files touched.
415
+
416
+ ``repo_url`` is carried into the metadata (not derived from ``repo``, a local
417
+ path) so a later, out-of-process apply step — e.g. the Phabricator submit
418
+ handler, which needs to re-check-out this same base commit — knows where
419
+ to clone from without re-deriving agent-specific config.
420
+ """
421
+ wrapped = commit_all(repo, message)
422
+ patch = _git_bytes(repo, "format-patch", "--stdout", "--binary", f"{base}..HEAD")
423
+ if not patch.strip():
424
+ return None
425
+ metadata = {
426
+ "base_commit": base,
427
+ "repo_url": repo_url,
428
+ "wrapped_uncommitted": wrapped,
429
+ "commits": _commit_metadata(repo, base),
430
+ }
431
+ return ChangeSet(patch=patch, metadata=metadata)
@@ -0,0 +1,96 @@
1
+ """Shared claude-agent-sdk helpers for hackbot agents.
2
+
3
+ Generic, agent-neutral building blocks that every claude-agent-sdk agent would
4
+ otherwise copy verbatim. Agents still assemble their own ``ClaudeAgentOptions``
5
+ and drive the ``ClaudeSDKClient`` loop — these just remove the boilerplate of
6
+ rendering the streamed messages.
7
+
8
+ Requires the ``claude-sdk`` optional extra of hackbot-runtime.
9
+ """
10
+
11
+ import json
12
+ import time
13
+
14
+ from claude_agent_sdk import (
15
+ AssistantMessage,
16
+ ResultMessage,
17
+ SystemMessage,
18
+ TextBlock,
19
+ ThinkingBlock,
20
+ ToolResultBlock,
21
+ ToolUseBlock,
22
+ UserMessage,
23
+ )
24
+
25
+ from hackbot_runtime.transcript import TranscriptLog, _truncate
26
+
27
+
28
+ class Reporter(TranscriptLog):
29
+ """Routes streamed claude-agent-sdk messages to stdout and/or a log file."""
30
+
31
+ def message(self, msg) -> None:
32
+ if isinstance(msg, AssistantMessage):
33
+ is_main = msg.parent_tool_use_id is None
34
+ label = "agent" if is_main else "subagent"
35
+ if is_main:
36
+ self._turn += 1
37
+ self._emit(f"\n--- turn {self._turn} ---")
38
+ for block in msg.content:
39
+ if isinstance(block, TextBlock):
40
+ self._emit(f"[{label}] {block.text}", always=is_main)
41
+ elif isinstance(block, ThinkingBlock):
42
+ thinking = block.thinking.strip()
43
+ snippet = thinking.split("\n", 1)[0]
44
+ self._emit(
45
+ f"[{label}:thinking] {_truncate(snippet, 120)}",
46
+ full=f"[{label}:thinking]\n{thinking}",
47
+ )
48
+ elif isinstance(block, ToolUseBlock):
49
+ inp = json.dumps(block.input, default=str)
50
+ inp_full = json.dumps(block.input, indent=2, default=str)
51
+ self._emit(
52
+ f"[{label}→tool] {block.name}({_truncate(inp, 300)})",
53
+ full=f"[{label}→tool] {block.name}\n{inp_full}",
54
+ )
55
+
56
+ elif isinstance(msg, UserMessage):
57
+ if isinstance(msg.content, list):
58
+ for block in msg.content:
59
+ if isinstance(block, ToolResultBlock):
60
+ marker = "ERROR" if block.is_error else "ok"
61
+ if isinstance(block.content, str):
62
+ text = block.content
63
+ elif isinstance(block.content, list):
64
+ parts = [
65
+ c.get("text", "")
66
+ for c in block.content
67
+ if isinstance(c, dict) and c.get("type") == "text"
68
+ ]
69
+ text = "\n".join(parts)
70
+ else:
71
+ text = str(block.content)
72
+ self._emit(
73
+ f"[tool←{marker}] {_truncate(text, 400)}",
74
+ full=f"[tool←{marker}]\n{text}",
75
+ )
76
+
77
+ elif isinstance(msg, SystemMessage):
78
+ if msg.subtype == "init":
79
+ model = msg.data.get("model", "?")
80
+ self._emit(f"[system] session started (model={model})")
81
+ else:
82
+ data = json.dumps(msg.data, default=str)
83
+ self._emit(
84
+ f"[system:{msg.subtype}] {_truncate(data, 200)}",
85
+ full=f"[system:{msg.subtype}] {data}",
86
+ )
87
+
88
+ elif isinstance(msg, ResultMessage):
89
+ self._emit(f"\n{'=' * 60}", always=True, stamp=False)
90
+ line = f"[done] turns={msg.num_turns}"
91
+ if msg.total_cost_usd:
92
+ line += f" cost=${msg.total_cost_usd:.4f}"
93
+ line += f" elapsed={time.monotonic() - self._started:.0f}s"
94
+ self._emit(line, always=True)
95
+ if msg.is_error:
96
+ self._emit(f"[done] ERROR: {msg.result}", always=True)