atomsh 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.
atomsh-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
atomsh-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.4
2
+ Name: atomsh
3
+ Version: 0.1.0
4
+ Summary: Your autonomous coding agent for science
5
+ Author-email: Kamal Choudhary <kchoudh2@jhu.edu>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://atomgpt.org
8
+ Project-URL: Repository, https://github.com/atomgptlab/atomsh
9
+ Keywords: agent,cli,coding-assistant,atomgpt,materials-science,jarvis
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: httpx>=0.24
14
+ Dynamic: license-file
15
+
16
+ # Atomsh
17
+
18
+ **Your autonomous coding agent for science.**
19
+
20
+ Atomsh reads and edits files, searches the codebase, and runs commands from
21
+ your terminal — and it can look a material up while doing it. It runs on
22
+ [AtomGPT](https://atomgpt.org) alone: one account, no other provider.
23
+
24
+ ## Install
25
+
26
+ ```sh
27
+ curl -fsSL https://atomgpt.org/install | bash
28
+ ```
29
+
30
+ The installer uses `uv` when it is present, falls back to a virtualenv, and
31
+ bootstraps `uv` if the system Python is unusable. Everything lands in an
32
+ isolated environment with a launcher in `~/.local/bin`. No sudo.
33
+
34
+ ## Connect
35
+
36
+ ```sh
37
+ atomsh login
38
+ ```
39
+
40
+ This opens atomgpt.org in your browser, you approve once, and the credential
41
+ is stored `0600` in `~/.config/atomsh/auth.json`. On a headless machine use
42
+ `atomsh login --key` and paste an API key instead.
43
+
44
+ ## Use
45
+
46
+ ```sh
47
+ atomsh # interactive session
48
+ atomsh "fix the failing test" # run one prompt and exit
49
+ atomsh -c # resume this directory's last session
50
+ git diff | atomsh "review this" # read a prompt from stdin
51
+ ```
52
+
53
+ | Flag | Effect |
54
+ |------|--------|
55
+ | `-m, --model` | Pick a model (default `gemma-4-26b`) |
56
+ | `-c, --continue` | Resume the most recent session for this directory |
57
+ | `--yolo` | Do not ask before writing files or running commands |
58
+ | `--readonly` | Refuse all writes and shell commands |
59
+ | `--no-materials` | Leave out the AtomGPT materials tools |
60
+
61
+ Commands: `login`, `logout`, `whoami`, `models`.
62
+
63
+ In a session: `!<command>` runs a shell command yourself, `/history` replays
64
+ the conversation, `/model` switches model, `/clear` starts a fresh thread.
65
+ **Escape** interrupts a response while it is streaming.
66
+
67
+ ## Permissions
68
+
69
+ By default atomsh asks before anything that writes a file or runs a
70
+ command; reads and searches happen unattended. Answering `a` allows that tool
71
+ for the rest of the session. A path outside the working directory always
72
+ prompts, even after `a`.
73
+
74
+ ## Models
75
+
76
+ `atomsh models` lists what your account can use. The `mcp.*` models are
77
+ excluded on purpose: those run the AtomGPT materials agent on the server and
78
+ answer in prose rather than making tool calls, so they cannot drive a coding
79
+ loop. Use them through a chat client instead.
80
+
81
+ ## Tools
82
+
83
+ `read_file`, `write_file`, `edit_file`, `list_dir`, `glob_files`,
84
+ `grep_files`, `bash`.
85
+
86
+ ### Materials tools
87
+
88
+ atomsh connects to the AtomGPT MCP server with the same credential and
89
+ carries six more tools by default: `explore`, `build`, `predict`,
90
+ `characterize`, `apply`, `validate`. Each dispatches to a family of AtomGPT apps — JARVIS-DFT lookups,
91
+ ALIGNN predictions, band structures, XRD, interfaces, protein folding — so the
92
+ agent can look a material up instead of answering from the model's memory:
93
+
94
+ ```
95
+ $ atomsh --materials "bandgap of silicon JVASP-1002 from JARVIS-DFT"
96
+ · explore(app=/jarvis_dft/query, params={"jid": "JVASP-1002"})
97
+ OptB88vdW 0.731 eV · mBJ 1.277 eV · HSE 1.22 eV
98
+ ```
99
+
100
+ The tool list is cached under `~/.local/share/atomsh/` and refreshed daily,
101
+ and the MCP session is opened on first use, so carrying them costs nothing at
102
+ startup. `--no-materials` leaves them out — worth doing for pure coding work,
103
+ where a narrower tool surface is easier for the model.
104
+
105
+ ## Development
106
+
107
+ ```sh
108
+ uv venv && uv pip install -e .
109
+ ATOMSH_API_KEY=sk-… atomsh --readonly "what does this repo do?"
110
+ ```
111
+
112
+ `ATOMSH_API_BASE` points the client at a different deployment.
113
+
114
+ `install.sh` here is the canonical installer; `atomgpt.org/install` serves a
115
+ copy of it.
116
+
117
+ ## License
118
+
119
+ Apache-2.0
atomsh-0.1.0/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # Atomsh
2
+
3
+ **Your autonomous coding agent for science.**
4
+
5
+ Atomsh reads and edits files, searches the codebase, and runs commands from
6
+ your terminal — and it can look a material up while doing it. It runs on
7
+ [AtomGPT](https://atomgpt.org) alone: one account, no other provider.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ curl -fsSL https://atomgpt.org/install | bash
13
+ ```
14
+
15
+ The installer uses `uv` when it is present, falls back to a virtualenv, and
16
+ bootstraps `uv` if the system Python is unusable. Everything lands in an
17
+ isolated environment with a launcher in `~/.local/bin`. No sudo.
18
+
19
+ ## Connect
20
+
21
+ ```sh
22
+ atomsh login
23
+ ```
24
+
25
+ This opens atomgpt.org in your browser, you approve once, and the credential
26
+ is stored `0600` in `~/.config/atomsh/auth.json`. On a headless machine use
27
+ `atomsh login --key` and paste an API key instead.
28
+
29
+ ## Use
30
+
31
+ ```sh
32
+ atomsh # interactive session
33
+ atomsh "fix the failing test" # run one prompt and exit
34
+ atomsh -c # resume this directory's last session
35
+ git diff | atomsh "review this" # read a prompt from stdin
36
+ ```
37
+
38
+ | Flag | Effect |
39
+ |------|--------|
40
+ | `-m, --model` | Pick a model (default `gemma-4-26b`) |
41
+ | `-c, --continue` | Resume the most recent session for this directory |
42
+ | `--yolo` | Do not ask before writing files or running commands |
43
+ | `--readonly` | Refuse all writes and shell commands |
44
+ | `--no-materials` | Leave out the AtomGPT materials tools |
45
+
46
+ Commands: `login`, `logout`, `whoami`, `models`.
47
+
48
+ In a session: `!<command>` runs a shell command yourself, `/history` replays
49
+ the conversation, `/model` switches model, `/clear` starts a fresh thread.
50
+ **Escape** interrupts a response while it is streaming.
51
+
52
+ ## Permissions
53
+
54
+ By default atomsh asks before anything that writes a file or runs a
55
+ command; reads and searches happen unattended. Answering `a` allows that tool
56
+ for the rest of the session. A path outside the working directory always
57
+ prompts, even after `a`.
58
+
59
+ ## Models
60
+
61
+ `atomsh models` lists what your account can use. The `mcp.*` models are
62
+ excluded on purpose: those run the AtomGPT materials agent on the server and
63
+ answer in prose rather than making tool calls, so they cannot drive a coding
64
+ loop. Use them through a chat client instead.
65
+
66
+ ## Tools
67
+
68
+ `read_file`, `write_file`, `edit_file`, `list_dir`, `glob_files`,
69
+ `grep_files`, `bash`.
70
+
71
+ ### Materials tools
72
+
73
+ atomsh connects to the AtomGPT MCP server with the same credential and
74
+ carries six more tools by default: `explore`, `build`, `predict`,
75
+ `characterize`, `apply`, `validate`. Each dispatches to a family of AtomGPT apps — JARVIS-DFT lookups,
76
+ ALIGNN predictions, band structures, XRD, interfaces, protein folding — so the
77
+ agent can look a material up instead of answering from the model's memory:
78
+
79
+ ```
80
+ $ atomsh --materials "bandgap of silicon JVASP-1002 from JARVIS-DFT"
81
+ · explore(app=/jarvis_dft/query, params={"jid": "JVASP-1002"})
82
+ OptB88vdW 0.731 eV · mBJ 1.277 eV · HSE 1.22 eV
83
+ ```
84
+
85
+ The tool list is cached under `~/.local/share/atomsh/` and refreshed daily,
86
+ and the MCP session is opened on first use, so carrying them costs nothing at
87
+ startup. `--no-materials` leaves them out — worth doing for pure coding work,
88
+ where a narrower tool surface is easier for the model.
89
+
90
+ ## Development
91
+
92
+ ```sh
93
+ uv venv && uv pip install -e .
94
+ ATOMSH_API_KEY=sk-… atomsh --readonly "what does this repo do?"
95
+ ```
96
+
97
+ `ATOMSH_API_BASE` points the client at a different deployment.
98
+
99
+ `install.sh` here is the canonical installer; `atomgpt.org/install` serves a
100
+ copy of it.
101
+
102
+ ## License
103
+
104
+ Apache-2.0
@@ -0,0 +1,6 @@
1
+ """Atomsh — your autonomous coding agent for science.
2
+
3
+ Installed as the `atomsh` command; entry point is `atomsh.cli:main`.
4
+ """
5
+
6
+ __version__ = "0.1.0"
@@ -0,0 +1,147 @@
1
+ """The agent loop: model → tool calls → tool results → model, until it stops."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from . import tools as toolkit
7
+ from .client import AtomGPT, AtomGPTError
8
+ from .config import MAX_STEPS
9
+ from .interrupt import escape_watch
10
+ from .permissions import ALLOW, Permissions
11
+ from .prompt import system_prompt
12
+
13
+ DIM = "\033[2m"
14
+ BOLD = "\033[1m"
15
+ RESET = "\033[0m"
16
+
17
+
18
+ class Agent:
19
+ """Drives one conversation against one model with one tool set."""
20
+
21
+ def __init__(self, client: AtomGPT, model: str, session,
22
+ permissions: Permissions = None, root: Path = None,
23
+ color: bool = True, remote=None):
24
+ self.client = client
25
+ self.model = model
26
+ self.session = session
27
+ self.root = root or Path.cwd()
28
+ self.permissions = permissions or Permissions("ask", self.root)
29
+ self.color = color
30
+ # An MCPClient, when --materials is on. Its tools sit alongside the
31
+ # local ones; the model does not need to know which is which.
32
+ self.remote = remote
33
+ self.remote_tools = set()
34
+ self.tool_schema = list(toolkit.SCHEMA)
35
+ if remote is not None:
36
+ remote_schema = remote.schema()
37
+ self.remote_tools = {t["function"]["name"] for t in remote_schema}
38
+ self.tool_schema += remote_schema
39
+ if not self.session.messages:
40
+ self.session.messages.append({
41
+ "role": "system",
42
+ "content": system_prompt(str(self.root),
43
+ materials=remote is not None),
44
+ })
45
+
46
+ def _dim(self, text: str) -> str:
47
+ return f"{DIM}{text}{RESET}" if self.color else text
48
+
49
+ def run(self, user_text: str) -> str:
50
+ """Run one user turn to completion. Returns the final assistant text."""
51
+ self.session.messages.append({"role": "user", "content": user_text})
52
+ final = ""
53
+
54
+ for _ in range(MAX_STEPS):
55
+ # `last` doubles as "have we printed anything this step": stripped
56
+ # channel markers leave stray blank lines, so leading whitespace is
57
+ # swallowed and the closing newline is only added if one is missing.
58
+ state = {"last": ""}
59
+
60
+ def on_text(piece, state=state):
61
+ if not state["last"] and not piece.strip():
62
+ return
63
+ state["last"] = piece
64
+ print(piece, end="", flush=True)
65
+
66
+ try:
67
+ with escape_watch() as cancelled:
68
+ result = self.client.stream(
69
+ self.session.messages, self.tool_schema, self.model,
70
+ on_text=on_text, cancelled=cancelled,
71
+ )
72
+ except AtomGPTError as e:
73
+ print(f"\n{self._dim('error:')} {e}")
74
+ return ""
75
+
76
+ message = result["message"]
77
+ if state["last"] and not state["last"].endswith("\n"):
78
+ print()
79
+ self.session.messages.append(message)
80
+ self.session.save()
81
+
82
+ if result.get("finish_reason") == "cancelled":
83
+ print(self._dim(" interrupted"))
84
+ return message.get("content") or ""
85
+
86
+ calls = message.get("tool_calls")
87
+ if not calls:
88
+ final = message.get("content") or ""
89
+ if not final and not state["last"]:
90
+ print(self._dim("(no response — try rephrasing)"))
91
+ return final
92
+
93
+ for call in calls:
94
+ self._run_tool(call)
95
+ self.session.save()
96
+
97
+ print(self._dim(f"stopped after {MAX_STEPS} steps"))
98
+ return final
99
+
100
+ def _run_tool(self, call: dict) -> None:
101
+ """Execute one tool call and append its result to the conversation."""
102
+ name = (call.get("function") or {}).get("name") or ""
103
+ raw_args = (call.get("function") or {}).get("arguments") or "{}"
104
+ try:
105
+ args = json.loads(raw_args) if raw_args.strip() else {}
106
+ except ValueError:
107
+ args = {}
108
+
109
+ handler = toolkit.HANDLERS.get(name)
110
+ if handler is None and name not in self.remote_tools:
111
+ return self._reply(call, f"Error: no such tool {name!r}.")
112
+
113
+ decision, reason = self.permissions.check(name, args)
114
+ if decision != ALLOW:
115
+ print(self._dim(f" ✗ {name} — {reason}"))
116
+ return self._reply(call, f"Denied: {reason}")
117
+
118
+ print(self._dim(f" · {name}({self._summarize(args)})"))
119
+ try:
120
+ if handler is None:
121
+ output = self.remote.call(name, args)
122
+ else:
123
+ output = handler(self.root, **args)
124
+ except TypeError as e:
125
+ output = f"Error: bad arguments for {name}: {e}"
126
+ except Exception as e: # a tool must never kill the session
127
+ output = f"Error: {name} raised {type(e).__name__}: {e}"
128
+ self._reply(call, output)
129
+
130
+ def _reply(self, call: dict, content: str) -> None:
131
+ self.session.messages.append({
132
+ "role": "tool",
133
+ "tool_call_id": call.get("id") or "",
134
+ "content": content,
135
+ })
136
+
137
+ @staticmethod
138
+ def _summarize(args: dict) -> str:
139
+ """One-line rendering of tool arguments for the activity log."""
140
+ parts = []
141
+ for key, value in args.items():
142
+ text = value if isinstance(value, str) else json.dumps(value)
143
+ text = text.replace("\n", " ")
144
+ if len(text) > 60:
145
+ text = text[:60] + "…"
146
+ parts.append(f"{key}={text}")
147
+ return ", ".join(parts)