hookbell 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.
hookbell-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yukihiko Shinoda
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ recursive-include docs *
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.4
2
+ Name: hookbell
3
+ Version: 0.1.0
4
+ Summary: Notifies Slack, as a Claude Code hook or as a notify-compatible CLI.
5
+ Author-email: Yukihiko Shinoda <yuk.hik.future@gmail.com>
6
+ Maintainer-email: Yukihiko Shinoda <yuk.hik.future@gmail.com>
7
+ License: MIT License
8
+
9
+ Copyright (c) 2026 Yukihiko Shinoda
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ Project-URL: homepage, https://github.com/yukihiko-shinoda/hookbell
30
+ Project-URL: repository, https://github.com/yukihiko-shinoda/hookbell
31
+ Keywords: hookbell
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Environment :: Console
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Natural Language :: English
37
+ Classifier: Operating System :: OS Independent
38
+ Classifier: Topic :: Communications :: Chat
39
+ Classifier: Programming Language :: Python
40
+ Classifier: Programming Language :: Python :: 3
41
+ Classifier: Programming Language :: Python :: 3.7
42
+ Classifier: Programming Language :: Python :: 3.8
43
+ Classifier: Programming Language :: Python :: 3.9
44
+ Classifier: Programming Language :: Python :: 3.10
45
+ Classifier: Programming Language :: Python :: 3.11
46
+ Classifier: Programming Language :: Python :: 3.12
47
+ Classifier: Programming Language :: Python :: 3.13
48
+ Classifier: Programming Language :: Python :: 3.14
49
+ Classifier: Typing :: Typed
50
+ Requires-Python: >=3.7
51
+ Description-Content-Type: text/markdown
52
+ License-File: LICENSE
53
+ Requires-Dist: certifi>=2026.7.22
54
+ Requires-Dist: click>=7.0
55
+ Dynamic: license-file
56
+
57
+ # Hookbell
58
+
59
+ [![Test](https://github.com/yukihiko-shinoda/hookbell/workflows/Test/badge.svg)](https://github.com/yukihiko-shinoda/hookbell/actions?query=workflow%3ATest)
60
+ [![CodeQL](https://github.com/yukihiko-shinoda/hookbell/workflows/CodeQL/badge.svg)](https://github.com/yukihiko-shinoda/hookbell/actions?query=workflow%3ACodeQL)
61
+ [![Code Coverage](https://qlty.sh/gh/yukihiko-shinoda/projects/hookbell/coverage.svg)](https://qlty.sh/gh/yukihiko-shinoda/projects/hookbell)
62
+ [![Maintainability](https://qlty.sh/gh/yukihiko-shinoda/projects/hookbell/maintainability.svg)](https://qlty.sh/gh/yukihiko-shinoda/projects/hookbell)
63
+ [![Dependabot](https://flat.badgen.net/github/dependabot/yukihiko-shinoda/hookbell?icon=dependabot)](https://github.com/yukihiko-shinoda/hookbell/security/dependabot)
64
+ [![Python versions](https://img.shields.io/pypi/pyversions/hookbell)](https://pypi.org/project/hookbell/)
65
+ [![PyPI - Downloads](https://img.shields.io/pypi/dm/hookbell)](https://pypi.org/project/hookbell/)
66
+ [![X URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Fgithub.com%2Fyukihiko-shinoda%2Fhookbell)](https://x.com/intent/post?text=Hookbell&url=https%3A%2F%2Fpypi.org%2Fproject%2Fhookbell%2F&hashtags=python)
67
+
68
+ Notifies Slack — as a Claude Code hook, or as a general "notify me when this finishes" command for
69
+ any piped output.
70
+
71
+ ## Advantage
72
+
73
+ A Claude Code hook script that only understands its own hook JSON payload
74
+ (`transcript_path`, `hook_event_name`, ...) can't double as a general-purpose notification command
75
+ for anything else you run — and a general-purpose command built without Claude Code in mind knows
76
+ nothing about its transcripts, so it can't report what the assistant actually said or which
77
+ permission it's waiting on. Maintaining one script per use case means duplicating the Slack-posting
78
+ logic each time.
79
+
80
+ Hookbell covers both with a single command: it inspects stdin and automatically picks the right
81
+ behavior. A Claude Code hook payload gets reported through its referenced transcript; anything else
82
+ is treated as free-form piped text and posted as-is.
83
+
84
+ ## Quickstart
85
+
86
+ ```bash
87
+ uv tool install hookbell
88
+ ```
89
+
90
+ Set the webhook URL from a Slack [Incoming Webhook](https://api.slack.com/messaging/webhooks):
91
+
92
+ ```bash
93
+ export SLACK_WEBHOOK_URL="https://hooks.slack.com/services/T000/B000/XXXX"
94
+ ```
95
+
96
+ Pipe any text into hookbell to post it to Slack:
97
+
98
+ ```bash
99
+ echo 'Hello world' | uvx hookbell
100
+ ```
101
+
102
+ That posts this single Slack message:
103
+
104
+ ````text
105
+ Finished!
106
+ ```
107
+ Hello world
108
+ ```
109
+ ````
110
+
111
+ Since any piped input gets wrapped the same way, piping a long-running command's own output into
112
+ hookbell delivers that output to Slack the moment the command is done, without having to watch the
113
+ terminal for it — redirecting stderr into stdout matters here, since build tools like
114
+ `docker compose build` write their progress there:
115
+
116
+ ```bash
117
+ docker compose build 2>&1 | uvx hookbell
118
+ ```
119
+
120
+ When the command's output isn't worth forwarding and only knowing it ended matters, chaining with
121
+ `;` instead leaves hookbell's stdin empty, so it just posts `Finished!` on its own:
122
+
123
+ ```bash
124
+ docker compose build; uvx hookbell
125
+ ```
126
+
127
+ <!-- markdownlint-disable no-trailing-punctuation -->
128
+ ## How do I...
129
+ <!-- markdownlint-enable no-trailing-punctuation -->
130
+
131
+ ### How do I use hookbell as a Claude Code hook?
132
+
133
+ Point Claude Code's `Notification`, `PermissionRequest`, and `Stop` hooks at hookbell in
134
+ `settings.json`:
135
+
136
+ ```json
137
+ {
138
+ "hooks": {
139
+ "Stop": [
140
+ {
141
+ "hooks": [{ "type": "command", "command": "uvx hookbell" }]
142
+ }
143
+ ]
144
+ }
145
+ }
146
+ ```
147
+
148
+ Hookbell recognizes a Claude Code hook payload by its `transcript_path` field and posts a message
149
+ built from that transcript: the assistant's own last message when there is one, or a description of
150
+ the pending permission request otherwise. A failed notification here is logged (see `slack.log`)
151
+ rather than raised, so a flaky network never turns into hook-failure noise.
152
+
153
+ ### How do I use hookbell in a Docker container?
154
+
155
+ Hookbell checks `/run/secrets/slack_webhook_url` before falling back to `SLACK_WEBHOOK_URL`, so a
156
+ [Docker secret] keeps the webhook URL out of the container's environment and image layers entirely.
157
+ With Compose, write the URL to a local file Compose reads at build/run time, and mount it as a
158
+ secret named `slack_webhook_url` so Docker places it at that exact path:
159
+
160
+ ```yaml
161
+ services:
162
+ app:
163
+ secrets:
164
+ - slack_webhook_url
165
+
166
+ secrets:
167
+ slack_webhook_url:
168
+ file: ./slack_webhook_url.txt
169
+ ```
170
+
171
+ [Docker secret]: https://docs.docker.com/compose/how-tos/use-secrets/
172
+
173
+ ## Credits
174
+
175
+ This package was created with [Cookiecutter] and the [yukihiko-shinoda/cookiecutter-pypackage] project template.
176
+
177
+ [Cookiecutter]: https://github.com/audreyr/cookiecutter
178
+ [yukihiko-shinoda/cookiecutter-pypackage]: https://github.com/audreyr/cookiecutter-pypackage
@@ -0,0 +1,122 @@
1
+ # Hookbell
2
+
3
+ [![Test](https://github.com/yukihiko-shinoda/hookbell/workflows/Test/badge.svg)](https://github.com/yukihiko-shinoda/hookbell/actions?query=workflow%3ATest)
4
+ [![CodeQL](https://github.com/yukihiko-shinoda/hookbell/workflows/CodeQL/badge.svg)](https://github.com/yukihiko-shinoda/hookbell/actions?query=workflow%3ACodeQL)
5
+ [![Code Coverage](https://qlty.sh/gh/yukihiko-shinoda/projects/hookbell/coverage.svg)](https://qlty.sh/gh/yukihiko-shinoda/projects/hookbell)
6
+ [![Maintainability](https://qlty.sh/gh/yukihiko-shinoda/projects/hookbell/maintainability.svg)](https://qlty.sh/gh/yukihiko-shinoda/projects/hookbell)
7
+ [![Dependabot](https://flat.badgen.net/github/dependabot/yukihiko-shinoda/hookbell?icon=dependabot)](https://github.com/yukihiko-shinoda/hookbell/security/dependabot)
8
+ [![Python versions](https://img.shields.io/pypi/pyversions/hookbell)](https://pypi.org/project/hookbell/)
9
+ [![PyPI - Downloads](https://img.shields.io/pypi/dm/hookbell)](https://pypi.org/project/hookbell/)
10
+ [![X URL](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Fgithub.com%2Fyukihiko-shinoda%2Fhookbell)](https://x.com/intent/post?text=Hookbell&url=https%3A%2F%2Fpypi.org%2Fproject%2Fhookbell%2F&hashtags=python)
11
+
12
+ Notifies Slack — as a Claude Code hook, or as a general "notify me when this finishes" command for
13
+ any piped output.
14
+
15
+ ## Advantage
16
+
17
+ A Claude Code hook script that only understands its own hook JSON payload
18
+ (`transcript_path`, `hook_event_name`, ...) can't double as a general-purpose notification command
19
+ for anything else you run — and a general-purpose command built without Claude Code in mind knows
20
+ nothing about its transcripts, so it can't report what the assistant actually said or which
21
+ permission it's waiting on. Maintaining one script per use case means duplicating the Slack-posting
22
+ logic each time.
23
+
24
+ Hookbell covers both with a single command: it inspects stdin and automatically picks the right
25
+ behavior. A Claude Code hook payload gets reported through its referenced transcript; anything else
26
+ is treated as free-form piped text and posted as-is.
27
+
28
+ ## Quickstart
29
+
30
+ ```bash
31
+ uv tool install hookbell
32
+ ```
33
+
34
+ Set the webhook URL from a Slack [Incoming Webhook](https://api.slack.com/messaging/webhooks):
35
+
36
+ ```bash
37
+ export SLACK_WEBHOOK_URL="https://hooks.slack.com/services/T000/B000/XXXX"
38
+ ```
39
+
40
+ Pipe any text into hookbell to post it to Slack:
41
+
42
+ ```bash
43
+ echo 'Hello world' | uvx hookbell
44
+ ```
45
+
46
+ That posts this single Slack message:
47
+
48
+ ````text
49
+ Finished!
50
+ ```
51
+ Hello world
52
+ ```
53
+ ````
54
+
55
+ Since any piped input gets wrapped the same way, piping a long-running command's own output into
56
+ hookbell delivers that output to Slack the moment the command is done, without having to watch the
57
+ terminal for it — redirecting stderr into stdout matters here, since build tools like
58
+ `docker compose build` write their progress there:
59
+
60
+ ```bash
61
+ docker compose build 2>&1 | uvx hookbell
62
+ ```
63
+
64
+ When the command's output isn't worth forwarding and only knowing it ended matters, chaining with
65
+ `;` instead leaves hookbell's stdin empty, so it just posts `Finished!` on its own:
66
+
67
+ ```bash
68
+ docker compose build; uvx hookbell
69
+ ```
70
+
71
+ <!-- markdownlint-disable no-trailing-punctuation -->
72
+ ## How do I...
73
+ <!-- markdownlint-enable no-trailing-punctuation -->
74
+
75
+ ### How do I use hookbell as a Claude Code hook?
76
+
77
+ Point Claude Code's `Notification`, `PermissionRequest`, and `Stop` hooks at hookbell in
78
+ `settings.json`:
79
+
80
+ ```json
81
+ {
82
+ "hooks": {
83
+ "Stop": [
84
+ {
85
+ "hooks": [{ "type": "command", "command": "uvx hookbell" }]
86
+ }
87
+ ]
88
+ }
89
+ }
90
+ ```
91
+
92
+ Hookbell recognizes a Claude Code hook payload by its `transcript_path` field and posts a message
93
+ built from that transcript: the assistant's own last message when there is one, or a description of
94
+ the pending permission request otherwise. A failed notification here is logged (see `slack.log`)
95
+ rather than raised, so a flaky network never turns into hook-failure noise.
96
+
97
+ ### How do I use hookbell in a Docker container?
98
+
99
+ Hookbell checks `/run/secrets/slack_webhook_url` before falling back to `SLACK_WEBHOOK_URL`, so a
100
+ [Docker secret] keeps the webhook URL out of the container's environment and image layers entirely.
101
+ With Compose, write the URL to a local file Compose reads at build/run time, and mount it as a
102
+ secret named `slack_webhook_url` so Docker places it at that exact path:
103
+
104
+ ```yaml
105
+ services:
106
+ app:
107
+ secrets:
108
+ - slack_webhook_url
109
+
110
+ secrets:
111
+ slack_webhook_url:
112
+ file: ./slack_webhook_url.txt
113
+ ```
114
+
115
+ [Docker secret]: https://docs.docker.com/compose/how-tos/use-secrets/
116
+
117
+ ## Credits
118
+
119
+ This package was created with [Cookiecutter] and the [yukihiko-shinoda/cookiecutter-pypackage] project template.
120
+
121
+ [Cookiecutter]: https://github.com/audreyr/cookiecutter
122
+ [yukihiko-shinoda/cookiecutter-pypackage]: https://github.com/audreyr/cookiecutter-pypackage
@@ -0,0 +1,133 @@
1
+ # Contributing
2
+
3
+ Contributions are welcome, and they are greatly appreciated! Every little bit
4
+ helps, and credit will always be given.
5
+
6
+ You can contribute in many ways:
7
+
8
+ ## Types of Contributions
9
+
10
+ ### Report Bugs
11
+
12
+ Report bugs at [GitHub Issues].
13
+
14
+ If you are reporting a bug, please include:
15
+
16
+ - Your operating system name and version.
17
+ - Any details about your local setup that might be helpful in troubleshooting.
18
+ - Detailed steps to reproduce the bug.
19
+
20
+ ### Fix Bugs
21
+
22
+ Look through the GitHub issues for bugs. Anything tagged with "bug" and "help
23
+ wanted" is open to whoever wants to implement it.
24
+
25
+ ### Implement Features
26
+
27
+ Look through the GitHub issues for features. Anything tagged with "enhancement"
28
+ and "help wanted" is open to whoever wants to implement it.
29
+
30
+ ### Write Documentation
31
+
32
+ Hookbell could always use more documentation, whether as part of the
33
+ official Hookbell docs, in docstrings, or even on the web in blog posts,
34
+ articles, and such.
35
+
36
+ ### Submit Feedback
37
+
38
+ The best way to send feedback is to file an issue at [GitHub Issues].
39
+
40
+ If you are proposing a feature:
41
+
42
+ - Explain in detail how it would work.
43
+ - Keep the scope as narrow as possible, to make it easier to implement.
44
+ - Remember that this is a volunteer-driven project, and that contributions
45
+ are welcome :)
46
+
47
+ <!-- markdownlint-disable no-trailing-punctuation -->
48
+ ## Get Started!
49
+ <!-- markdownlint-enaable no-trailing-punctuation -->
50
+
51
+ Ready to contribute? Here's how to set up `Hookbell` for local development.
52
+
53
+ 1. Fork the `hookbell` repo on GitHub.
54
+ 2. Clone your fork locally:
55
+
56
+ ```console
57
+ git clone git@github.com:your_name_here/hookbell.git
58
+ ```
59
+
60
+ 3. Set up your development environment.
61
+
62
+ The recommended way is to use [docker-compose-python-development](https://github.com/yukihiko-shinoda/docker-compose-python-development),
63
+ which provides a pre-configured Docker-based environment for Python projects.
64
+ Follow the setup instructions in that repository, then clone this repo into its workspace.
65
+
66
+ Alternatively, install dependencies directly with `uv`:
67
+
68
+ ```console
69
+ uv sync
70
+ ```
71
+
72
+ 4. Create a branch for local development:
73
+
74
+ ```console
75
+ git checkout -b name-of-your-bugfix-or-feature
76
+ ```
77
+
78
+ Now you can make your changes locally.
79
+
80
+ 5. When you're done making changes,
81
+ check that your changes pass Ruff, docformatter,
82
+ and the tests, including testing oldest Python version:
83
+
84
+ ```console
85
+ uv run inv style --check
86
+ uv run pytest
87
+ uv install --python 3.7
88
+ uv run pytest
89
+ ```
90
+
91
+ 6. Commit your changes and push your branch to GitHub:
92
+
93
+ ```console
94
+ git add .
95
+ git commit -m "Your detailed description of your changes."
96
+ git push origin name-of-your-bugfix-or-feature
97
+ ```
98
+
99
+ 7. Submit a pull request through the GitHub website.
100
+
101
+ ## Pull Request Guidelines
102
+
103
+ Before you submit a pull request, check that it meets these guidelines:
104
+
105
+ 1. The pull request should include tests.
106
+ 2. If the pull request adds functionality, the docs should be updated. Put
107
+ your new functionality into a function with a docstring, and add the
108
+ feature to the list in README.md.
109
+
110
+ ## Tips
111
+
112
+ To run a subset of tests:
113
+
114
+ ```console
115
+ uv run pytest tests.test_hookbell
116
+
117
+ ```
118
+
119
+ ## Deploying
120
+
121
+ A reminder for the maintainers on how to deploy.
122
+ Make sure all your changes are committed.
123
+ Then run:
124
+
125
+ ```console
126
+ bump2version patch # possible: major / minor / patch
127
+ git push
128
+ git push --tags
129
+ ```
130
+
131
+ Travis will then deploy to PyPI if tests pass.
132
+
133
+ [GitHub Issues]: https://github.com/yukihiko-shinoda/hookbell/issues
@@ -0,0 +1,6 @@
1
+ # Copyright (c) 2026 Yukihiko Shinoda
2
+ """Top-level package for Hookbell."""
3
+
4
+ __author__ = """Yukihiko Shinoda"""
5
+ __email__ = "yuk.hik.future@gmail.com"
6
+ __version__ = "0.1.0"
@@ -0,0 +1,2 @@
1
+ # Copyright (c) 2026 Yukihiko Shinoda
2
+ """Claude Code hook payload handling."""
@@ -0,0 +1,19 @@
1
+ # Copyright (c) 2026 Yukihiko Shinoda
2
+ """Composes a notification text from a Claude Code hook event."""
3
+
4
+ from hookbell.claude_code.stdin import ClaudeCodeStdin
5
+ from hookbell.claude_code.transcript import Transcript
6
+
7
+
8
+ class ClaudeCodeHookEvent:
9
+ """A Claude Code hook event, combining its stdin payload and referenced transcript."""
10
+
11
+ def __init__(self, stdin: ClaudeCodeStdin) -> None:
12
+ self.stdin = stdin
13
+ self.transcript = Transcript(stdin.transcript_path)
14
+
15
+ @property
16
+ def text(self) -> str:
17
+ """Return the notification text for this hook event."""
18
+ content = self.transcript.text_content or self.stdin.fallback_text
19
+ return f"{content}\n\nMessage type: {self.stdin.message}\n\n```{self.transcript.report()}```"
@@ -0,0 +1,57 @@
1
+ # Copyright (c) 2026 Yukihiko Shinoda
2
+ """Parses Claude Code hook stdin payloads."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from logging import getLogger
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ class ClaudeCodeStdin:
13
+ """A Claude Code hook stdin payload."""
14
+
15
+ TRANSCRIPT_PATH_KEY = "transcript_path"
16
+
17
+ def __init__(self, data: dict[str, Any]) -> None:
18
+ self.data = data
19
+
20
+ @classmethod
21
+ def parse(cls, raw_stdin: str) -> ClaudeCodeStdin | None:
22
+ """Return a ClaudeCodeStdin when raw_stdin holds a Claude Code hook payload, else None."""
23
+ try:
24
+ data = json.loads(raw_stdin)
25
+ except json.JSONDecodeError:
26
+ return None
27
+ if not isinstance(data, dict) or cls.TRANSCRIPT_PATH_KEY not in data:
28
+ return None
29
+ getLogger(__name__).debug("raw stdin: %s", raw_stdin)
30
+ return cls(data)
31
+
32
+ @property
33
+ def message(self) -> str:
34
+ """Return the hook's message, falling back to its event name."""
35
+ return str(self.data.get("message") or self.data.get("hook_event_name", "Notification"))
36
+
37
+ @property
38
+ def transcript_path(self) -> Path:
39
+ """Return the transcript file path this hook event refers to."""
40
+ return Path(self.data[self.TRANSCRIPT_PATH_KEY])
41
+
42
+ @property
43
+ def fallback_text(self) -> str:
44
+ """Return text to show when the transcript's last line has no readable text.
45
+
46
+ PermissionRequest payloads carry the pending tool call directly instead of assistant text, and Stop payloads
47
+ carry a ready-made last_assistant_message when the transcript's last line was something else (e.g. a sidechain
48
+ or summary entry).
49
+ """
50
+ last_assistant_message = self.data.get("last_assistant_message")
51
+ if last_assistant_message:
52
+ return str(last_assistant_message)
53
+ tool_name = self.data.get("tool_name")
54
+ if tool_name:
55
+ tool_input = json.dumps(self.data.get("tool_input", {}), ensure_ascii=False)
56
+ return f"Waiting for permission: {tool_name}({tool_input})"
57
+ return self.message
@@ -0,0 +1,88 @@
1
+ # Copyright (c) 2026 Yukihiko Shinoda
2
+ """Reads and sanitizes a Claude Code transcript's last entry."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ from typing import TYPE_CHECKING
9
+ from typing import Any
10
+
11
+ if TYPE_CHECKING:
12
+ import io
13
+ from pathlib import Path
14
+
15
+
16
+ class FileLastLineGetter:
17
+ """Gets the last line of a file without reading the whole file into memory."""
18
+
19
+ def __init__(self, file_path: Path) -> None:
20
+ self.file_path = file_path
21
+
22
+ def get_last_line(self) -> str:
23
+ """Return the last line of the file."""
24
+ with self.file_path.open("rb") as file_pointer:
25
+ return self._get_last_line(file_pointer)
26
+
27
+ @staticmethod
28
+ def _get_last_line(file_pointer: io.BufferedIOBase) -> str:
29
+ try:
30
+ FileLastLineGetter._seek_to_last_new_line(file_pointer)
31
+ except OSError:
32
+ # In case of a one line file
33
+ file_pointer.seek(0)
34
+ return file_pointer.readline().decode("utf-8").strip()
35
+
36
+ @staticmethod
37
+ def _seek_to_last_new_line(file_pointer: io.BufferedIOBase) -> None:
38
+ file_pointer.seek(-2, os.SEEK_END)
39
+ while file_pointer.read(1) != b"\n":
40
+ file_pointer.seek(-2, os.SEEK_CUR)
41
+
42
+
43
+ class Transcript:
44
+ """A Claude Code transcript.
45
+
46
+ The transcript's last line is not always a plain assistant text message: it may be a tool call, a sub-
47
+ agent/sidechain entry, or a compaction summary entry, each with a different shape. Every accessor here must
48
+ tolerate keys being absent rather than assume the full schema.
49
+ """
50
+
51
+ UNREADABLE_KEYS = ("parentUuid", "isSidechain", "sessionId", "version", "requestId", "uuid", "timestamp")
52
+
53
+ def __init__(self, path: Path) -> None:
54
+ transcript_json_string = FileLastLineGetter(path).get_last_line()
55
+ self.data: Any = json.loads(transcript_json_string)
56
+
57
+ def report(self) -> str:
58
+ """Return the last transcript entry as pretty-printed, sanitized JSON."""
59
+ return json.dumps(self._remove_unreadable_keys(), indent=2, ensure_ascii=False)
60
+
61
+ def _remove_unreadable_keys(self) -> dict[str, Any]:
62
+ if not isinstance(self.data, dict):
63
+ return {"raw": self.data}
64
+ data = self.data.copy()
65
+ for key in self.UNREADABLE_KEYS:
66
+ data.pop(key, None)
67
+ message = data.get("message")
68
+ if isinstance(message, dict):
69
+ self._remove_unreadable_message_keys(message)
70
+ return data
71
+
72
+ @staticmethod
73
+ def _remove_unreadable_message_keys(message: dict[str, Any]) -> None:
74
+ message.pop("id", None)
75
+ for message_content in message.get("content") or []:
76
+ if isinstance(message_content, dict):
77
+ message_content.pop("id", None)
78
+
79
+ @property
80
+ def text_content(self) -> str:
81
+ """Return the concatenated assistant text blocks of the last transcript entry."""
82
+ if not isinstance(self.data, dict):
83
+ return ""
84
+ contents = self.data.get("message", {}).get("content") or []
85
+ if not isinstance(contents, list):
86
+ return ""
87
+ texts = [item["text"] for item in contents if isinstance(item, dict) and item.get("type") == "text"]
88
+ return "\n".join(texts)