zenagent-py 0.2.2__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/PKG-INFO +27 -7
  2. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/README.md +26 -6
  3. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/pyproject.toml +1 -1
  4. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/pyproject.toml.orig +1 -1
  5. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/__init__.py +1 -1
  6. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/agent/loop.py +215 -33
  7. zenagent_py-0.4.0/zenagent/agent/result_budget.py +123 -0
  8. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/agent/session.py +64 -0
  9. zenagent_py-0.4.0/zenagent/agent/timeouts.py +60 -0
  10. zenagent_py-0.4.0/zenagent/app/chat.py +526 -0
  11. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/app/commands.py +119 -10
  12. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/app/modes.py +1 -1
  13. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/app/permissions.py +139 -20
  14. zenagent_py-0.4.0/zenagent/app/retry.py +58 -0
  15. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/app/runtime.py +265 -41
  16. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/app/sessions.py +23 -0
  17. zenagent_py-0.4.0/zenagent/app/support.py +128 -0
  18. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/app/views.py +44 -7
  19. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/completion.py +2 -0
  20. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/main.py +25 -14
  21. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/repl.py +58 -5
  22. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/rpc.py +2 -1
  23. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/app.py +183 -14
  24. zenagent_py-0.4.0/zenagent/cli/tui/history.py +82 -0
  25. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/screens/modals.py +249 -23
  26. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/status/presets.py +10 -1
  27. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/status/segments.py +29 -0
  28. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/theme.tcss +22 -0
  29. zenagent_py-0.4.0/zenagent/cli/tui/widgets/attachments.py +58 -0
  30. zenagent_py-0.4.0/zenagent/cli/tui/widgets/error_banner.py +48 -0
  31. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/widgets/prompt_input.py +2 -0
  32. zenagent_py-0.4.0/zenagent/cli/tui/widgets/rows.py +261 -0
  33. zenagent_py-0.4.0/zenagent/cli/tui/widgets/todo_hud.py +89 -0
  34. zenagent_py-0.4.0/zenagent/cli/tui/widgets/tool_card.py +221 -0
  35. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/widgets/transcript.py +55 -15
  36. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/events.py +3 -0
  37. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/mcp/client.py +13 -1
  38. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/mcp/manager.py +1 -0
  39. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/anthropic_messages.py +5 -0
  40. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/google_generative_ai.py +2 -0
  41. zenagent_py-0.4.0/zenagent/providers/limits.py +163 -0
  42. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/openai_completions.py +2 -0
  43. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/skills.py +1 -0
  44. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/telemetry.py +7 -1
  45. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/tools/__init__.py +3 -0
  46. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/tools/bash.py +102 -79
  47. zenagent_py-0.4.0/zenagent/tools/fs.py +506 -0
  48. zenagent_py-0.4.0/zenagent/tools/jobs.py +415 -0
  49. zenagent_py-0.4.0/zenagent/tools/search.py +375 -0
  50. zenagent_py-0.4.0/zenagent/tools/shell.py +252 -0
  51. zenagent_py-0.4.0/zenagent/tools/todo.py +796 -0
  52. zenagent_py-0.4.0/zenagent/tools/wait.py +192 -0
  53. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/tools/web/__init__.py +4 -0
  54. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/tools/web/tools.py +93 -8
  55. zenagent_py-0.4.0/zenagent/update_check.py +296 -0
  56. zenagent_py-0.2.2/zenagent/app/chat.py +0 -276
  57. zenagent_py-0.2.2/zenagent/app/support.py +0 -51
  58. zenagent_py-0.2.2/zenagent/cli/tui/widgets/rows.py +0 -119
  59. zenagent_py-0.2.2/zenagent/cli/tui/widgets/tool_card.py +0 -127
  60. zenagent_py-0.2.2/zenagent/tools/fs.py +0 -280
  61. zenagent_py-0.2.2/zenagent/tools/search.py +0 -200
  62. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/agent/__init__.py +0 -0
  63. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/agent/agent.py +0 -0
  64. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/agent/validate.py +0 -0
  65. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/app/__init__.py +0 -0
  66. {zenagent_py-0.2.2/zenagent/cli → zenagent_py-0.4.0/zenagent/app}/compact.py +0 -0
  67. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/app/models.py +0 -0
  68. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/app/slash_args.py +0 -0
  69. /zenagent_py-0.2.2/zenagent/cli/images.py → /zenagent_py-0.4.0/zenagent/attachments.py +0 -0
  70. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/catalog.yaml +0 -0
  71. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/__init__.py +0 -0
  72. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/doctor.py +0 -0
  73. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/exportcmd.py +0 -0
  74. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/keybindings.py +0 -0
  75. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/permissions.py +0 -0
  76. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/render.py +0 -0
  77. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/sessionscmd.py +0 -0
  78. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/theme.py +0 -0
  79. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/__init__.py +0 -0
  80. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/run.py +0 -0
  81. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/screens/palette.py +0 -0
  82. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/screens/secrets.py +0 -0
  83. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/status/__init__.py +0 -0
  84. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/widgets/command_hints.py +0 -0
  85. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/widgets/new_content.py +0 -0
  86. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/widgets/prompt_gutter.py +0 -0
  87. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/widgets/sidebar.py +0 -0
  88. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/widgets/status_band.py +0 -0
  89. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/widgets/welcome.py +0 -0
  90. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/tui/widgets/work_indicator.py +0 -0
  91. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/cli/usagecmd.py +0 -0
  92. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/config.py +0 -0
  93. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/context_files.py +0 -0
  94. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/crash.py +0 -0
  95. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/evals_runner.py +0 -0
  96. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/export.py +0 -0
  97. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/extensions.py +0 -0
  98. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/frontmatter.py +0 -0
  99. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/mcp/__init__.py +0 -0
  100. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/mcp/config.py +0 -0
  101. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/project.py +0 -0
  102. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/__init__.py +0 -0
  103. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/catalog.py +0 -0
  104. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/compat.py +0 -0
  105. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/anthropic-badjson.txt +0 -0
  106. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/anthropic-text.txt +0 -0
  107. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/anthropic-thinking-toolcall.txt +0 -0
  108. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/badjson-toolcall.txt +0 -0
  109. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/deepseek-chat-live-text.request.json +0 -0
  110. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/deepseek-chat-live-text.txt +0 -0
  111. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/deepseek-chat-live-toolcall.request.json +0 -0
  112. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/deepseek-chat-live-toolcall.txt +0 -0
  113. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/deepseek-reasoner-live-thinking.request.json +0 -0
  114. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/deepseek-reasoner-live-thinking.txt +0 -0
  115. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/deepseek-reasoner.txt +0 -0
  116. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/google-text.txt +0 -0
  117. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/google-toolcall.txt +0 -0
  118. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/multi-tool-parallel.txt +0 -0
  119. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/openai-responses-text.txt +0 -0
  120. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/openai-responses-toolcall.txt +0 -0
  121. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/zai-glm-5.3-text+thinking.txt +0 -0
  122. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/fixtures/zai-glm-5.3-toolcall.txt +0 -0
  123. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/openai_responses.py +0 -0
  124. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/registry.py +0 -0
  125. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/providers/transport.py +0 -0
  126. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/retry.py +0 -0
  127. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/settings.py +0 -0
  128. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/templates.py +0 -0
  129. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/tools/web/net.py +0 -0
  130. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/tools/web/providers.py +0 -0
  131. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/tools/web/query.py +0 -0
  132. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/tools/web/registry.py +0 -0
  133. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/tools/web/types.py +0 -0
  134. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/trace.py +0 -0
  135. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/types.py +0 -0
  136. {zenagent_py-0.2.2 → zenagent_py-0.4.0}/zenagent/usage.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: zenagent-py
3
- Version: 0.2.2
3
+ Version: 0.4.0
4
4
  Summary: A minimal, Pythonic coding agent: streaming LLM client, async-generator agent loop, and terminal harness.
5
5
  Keywords: agent,llm,ai,cli,async,coding-agent
6
6
  Author: Justin Gao
@@ -49,6 +49,8 @@ Repo: <https://github.com/encyc/zen-agent> · PyPI package: `zenagent-py` (impor
49
49
 
50
50
  Full documentation — architecture, usage guides, internals (source tour), contracts and the
51
51
  feature map — lives in [`docs/`](docs/README.md). Start with [`docs/architecture.md`](docs/architecture.md).
52
+ Release notes: [`CHANGELOG.md`](CHANGELOG.md); the tool-kernel gap study and the next roadmap
53
+ live under [`docs/research/omp-cli-study/`](docs/research/omp-cli-study/00-README.md).
52
54
 
53
55
  ## Install
54
56
 
@@ -61,6 +63,10 @@ zen --help # imports as `zenagent`; needs Python 3.11+
61
63
  uv sync --extra cli # kernel + interactive extras (prompt_toolkit, rich)
62
64
  ```
63
65
 
66
+ The interactive TUI checks PyPI at most once a day for a newer `zenagent-py`
67
+ and prints one quiet line in the transcript when one exists; `-p`/`--json`
68
+ never check. Disable it with `ZENAGENT_NO_UPDATE_CHECK=1`.
69
+
64
70
  Requires Python 3.15+ (the project targets the current `uv` toolchain; any
65
71
  3.11+ should work for the kernel itself).
66
72
 
@@ -144,9 +150,10 @@ agent = Agent(
144
150
  await agent.prompt("explain this repo") # events via agent.subscribe(fn)
145
151
  ```
146
152
 
147
- See `examples/` for a headless run, a custom tool with a fake stream (offline),
148
- a direct MCP call, and a `zen rpc` client. For embedding with the full app layer
149
- (MCP, skills, sessions), use `Runtime` + `ChatController` — see `examples/embed.py`.
153
+ See `examples/README.md` for a headless run, a custom tool with a fake stream
154
+ (offline), a direct MCP call, and a `zen rpc` client. For embedding with the full
155
+ app layer (MCP, skills, sessions), use `Runtime` + `ChatController` — see
156
+ `examples/embed.py`.
150
157
 
151
158
  ### REPL commands
152
159
 
@@ -256,12 +263,25 @@ extra.
256
263
  result, so the transcript never carries a dangling `tool_call`.
257
264
  - **Every event carries a `partial` snapshot**, so the UI never assembles deltas
258
265
  itself; assembly belongs to the adapter and happens once.
266
+ - **Tools declare their approval tier** (`read` / `write` / `exec`); the kernel
267
+ does not enforce it — the harness permission gate does. Plan/`--read-only`
268
+ therefore allow `web_search`/`fetch` and MCP tools with `readOnlyHint: true`,
269
+ while the kernel stays policy-free.
270
+ - **Every tool result goes through one budget.** Over 40 KB keeps the head and
271
+ tail with a uniform truncation notice; overlong lines are middle-truncated.
272
+ Per-tool caps remain the first line of defense, MCP/extension tools get the
273
+ same safety net.
259
274
 
260
275
  ## Tools
261
276
 
262
- `read_file`, `write_file`, `edit_file` (exactly-one-match replacement),
263
- `list_dir`, `bash` (merged output, 30 KB head+tail truncation, process-group
264
- kill on timeout/abort), `glob`, `grep` (ripgrep when available, Python fallback).
277
+ `read_file` (paged: 400 lines per call by default, `offset`/`limit` for the next
278
+ page), `write_file` (refuses writing back a truncated read page),
279
+ `edit_file` (exactly-one-match replacement), `list_dir`, `bash` (merged output,
280
+ 30 KB head+tail truncation, process-group kill on timeout/abort, non-interactive
281
+ environment, optional `cwd`), `glob`, `grep` (ripgrep when available, Python
282
+ fallback), `web_search` (provider chain), `fetch` (URL → readable text), `wait`
283
+ (background-job results) and `todo` (session-scoped checklist with a TUI HUD).
284
+ `bash` supports `async` background jobs; job results are collected with `wait`.
265
285
 
266
286
  ## Tests
267
287
 
@@ -21,6 +21,8 @@ Repo: <https://github.com/encyc/zen-agent> · PyPI package: `zenagent-py` (impor
21
21
 
22
22
  Full documentation — architecture, usage guides, internals (source tour), contracts and the
23
23
  feature map — lives in [`docs/`](docs/README.md). Start with [`docs/architecture.md`](docs/architecture.md).
24
+ Release notes: [`CHANGELOG.md`](CHANGELOG.md); the tool-kernel gap study and the next roadmap
25
+ live under [`docs/research/omp-cli-study/`](docs/research/omp-cli-study/00-README.md).
24
26
 
25
27
  ## Install
26
28
 
@@ -33,6 +35,10 @@ zen --help # imports as `zenagent`; needs Python 3.11+
33
35
  uv sync --extra cli # kernel + interactive extras (prompt_toolkit, rich)
34
36
  ```
35
37
 
38
+ The interactive TUI checks PyPI at most once a day for a newer `zenagent-py`
39
+ and prints one quiet line in the transcript when one exists; `-p`/`--json`
40
+ never check. Disable it with `ZENAGENT_NO_UPDATE_CHECK=1`.
41
+
36
42
  Requires Python 3.15+ (the project targets the current `uv` toolchain; any
37
43
  3.11+ should work for the kernel itself).
38
44
 
@@ -116,9 +122,10 @@ agent = Agent(
116
122
  await agent.prompt("explain this repo") # events via agent.subscribe(fn)
117
123
  ```
118
124
 
119
- See `examples/` for a headless run, a custom tool with a fake stream (offline),
120
- a direct MCP call, and a `zen rpc` client. For embedding with the full app layer
121
- (MCP, skills, sessions), use `Runtime` + `ChatController` — see `examples/embed.py`.
125
+ See `examples/README.md` for a headless run, a custom tool with a fake stream
126
+ (offline), a direct MCP call, and a `zen rpc` client. For embedding with the full
127
+ app layer (MCP, skills, sessions), use `Runtime` + `ChatController` — see
128
+ `examples/embed.py`.
122
129
 
123
130
  ### REPL commands
124
131
 
@@ -228,12 +235,25 @@ extra.
228
235
  result, so the transcript never carries a dangling `tool_call`.
229
236
  - **Every event carries a `partial` snapshot**, so the UI never assembles deltas
230
237
  itself; assembly belongs to the adapter and happens once.
238
+ - **Tools declare their approval tier** (`read` / `write` / `exec`); the kernel
239
+ does not enforce it — the harness permission gate does. Plan/`--read-only`
240
+ therefore allow `web_search`/`fetch` and MCP tools with `readOnlyHint: true`,
241
+ while the kernel stays policy-free.
242
+ - **Every tool result goes through one budget.** Over 40 KB keeps the head and
243
+ tail with a uniform truncation notice; overlong lines are middle-truncated.
244
+ Per-tool caps remain the first line of defense, MCP/extension tools get the
245
+ same safety net.
231
246
 
232
247
  ## Tools
233
248
 
234
- `read_file`, `write_file`, `edit_file` (exactly-one-match replacement),
235
- `list_dir`, `bash` (merged output, 30 KB head+tail truncation, process-group
236
- kill on timeout/abort), `glob`, `grep` (ripgrep when available, Python fallback).
249
+ `read_file` (paged: 400 lines per call by default, `offset`/`limit` for the next
250
+ page), `write_file` (refuses writing back a truncated read page),
251
+ `edit_file` (exactly-one-match replacement), `list_dir`, `bash` (merged output,
252
+ 30 KB head+tail truncation, process-group kill on timeout/abort, non-interactive
253
+ environment, optional `cwd`), `glob`, `grep` (ripgrep when available, Python
254
+ fallback), `web_search` (provider chain), `fetch` (URL → readable text), `wait`
255
+ (background-job results) and `todo` (session-scoped checklist with a TUI HUD).
256
+ `bash` supports `async` background jobs; job results are collected with `wait`.
237
257
 
238
258
  ## Tests
239
259
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "zenagent-py"
3
- version = "0.2.2"
3
+ version = "0.4.0"
4
4
  description = "A minimal, Pythonic coding agent: streaming LLM client, async-generator agent loop, and terminal harness."
5
5
  readme = "README.md"
6
6
  keywords = [
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "zenagent-py"
3
- version = "0.2.2"
3
+ version = "0.4.0"
4
4
  description = "A minimal, Pythonic coding agent: streaming LLM client, async-generator agent loop, and terminal harness."
5
5
  readme = "README.md"
6
6
  keywords = ["agent", "llm", "ai", "cli", "async", "coding-agent"]
@@ -1,4 +1,4 @@
1
1
 
2
2
  from __future__ import annotations
3
3
 
4
- __version__ = "0.2.2"
4
+ __version__ = "0.4.0"
@@ -31,10 +31,14 @@ from __future__ import annotations
31
31
 
32
32
  import asyncio
33
33
  import inspect
34
+ import json
35
+ import re
34
36
  import time
35
37
  from collections.abc import AsyncIterator, Awaitable, Callable
36
38
  from dataclasses import dataclass, field
37
39
 
40
+ from zenagent.agent.result_budget import apply_result_budget
41
+ from zenagent.agent.timeouts import effective_timeout
38
42
  from zenagent.agent.validate import validate_arguments
39
43
  from zenagent.events import AbortToken, AgentEvent
40
44
  from zenagent.providers.catalog import Model
@@ -77,6 +81,10 @@ class ToolResultAgent:
77
81
  details: dict = field(default_factory=dict)
78
82
  is_error: bool = False
79
83
  terminate: bool = False
84
+ #: Machine-readable failure category ('' for success). The loop fills in
85
+ #: its own kinds (unknown_tool/invalid_arguments/policy/tool_error/timeout);
86
+ #: tools may set a more specific one in the result they return.
87
+ error_kind: str = ""
80
88
 
81
89
 
82
90
  @dataclass
@@ -88,6 +96,13 @@ class AgentTool:
88
96
  for streaming partial results (ignored by most tools). ``execution_mode=
89
97
  "sequential"`` opts the tool out of the concurrent batch: such tools run one
90
98
  at a time, in the order the assistant requested them.
99
+
100
+ ``approval`` is the tool's own capability declaration consumed by the
101
+ harness permission gate: ``"read"`` (never needs confirmation, allowed in
102
+ read-only modes), ``"write"`` (mutates files/state) or ``"exec"`` (runs
103
+ commands; the default when a tool does not say). The kernel does not
104
+ enforce it — the declaration lets the harness classify tools without a
105
+ hard-coded name list.
91
106
  """
92
107
 
93
108
  name: str
@@ -103,6 +118,11 @@ class AgentTool:
103
118
  ]
104
119
  | None
105
120
  ) = None
121
+ #: Capability tier declared by the tool (``read``/``write``/``exec``).
122
+ approval: str = "exec"
123
+ #: Per-tool wall-clock budget; the loop wraps the call in ``wait_for``.
124
+ #: None means "no kernel deadline" (the tool manages its own, e.g. bash).
125
+ timeout_s: float | None = None
106
126
 
107
127
 
108
128
  @dataclass
@@ -111,9 +131,11 @@ class AgentConfig:
111
131
 
112
132
  Hooks (all optional, all may be sync or async unless typed otherwise):
113
133
 
114
- * ``before_tool_call(tool_call, args)`` — return ``{"block": True,
134
+ * ``before_tool_call(tool_call, args, tool)`` — return ``{"block": True,
115
135
  "reason": str}`` to veto the call; the tool result becomes an is_error
116
- carrying the reason and ``execute`` is never invoked.
136
+ carrying the reason and ``execute`` is never invoked. ``tool`` is the
137
+ resolved :class:`AgentTool`, so policy can read its declarations. A
138
+ 2-argument hook is still accepted (the v0.3 signature).
117
139
  * ``after_tool_call(tool_call, result)`` — return a ``ToolResultAgent`` to
118
140
  replace the result, or a ``{"content"/"is_error"/"terminate"}`` dict to
119
141
  patch individual fields.
@@ -166,6 +188,24 @@ class _ToolOutcome:
166
188
  duration_ms: int
167
189
 
168
190
 
191
+ def _hook_accepts_tool(hook) -> bool:
192
+ """Whether a before hook accepts the resolved tool as a third argument.
193
+
194
+ The 3-arg form is the current contract; the 2-arg form was the v0.3
195
+ contract and is still accepted for library users (a TypeError escaping the
196
+ hook would otherwise abort the whole run, outside the tool try/except).
197
+ """
198
+ try:
199
+ signature = inspect.signature(hook)
200
+ except (TypeError, ValueError): # C callable: assume the current contract
201
+ return True
202
+ try:
203
+ signature.bind(None, {}, None)
204
+ except TypeError:
205
+ return False
206
+ return True
207
+
208
+
169
209
  async def _maybe_await(value):
170
210
  """Await ``value`` if it is awaitable (sync-or-async hook support)."""
171
211
  if inspect.isawaitable(value):
@@ -189,8 +229,10 @@ def _run_cost(messages: list[Message]) -> float:
189
229
  )
190
230
 
191
231
 
192
- def _error_result(text: str) -> ToolResultAgent:
193
- return ToolResultAgent(content=[TextContent(text=text)], is_error=True)
232
+ def _error_result(text: str, *, kind: str = "tool_error") -> ToolResultAgent:
233
+ return ToolResultAgent(
234
+ content=[TextContent(text=text)], is_error=True, error_kind=kind
235
+ )
194
236
 
195
237
 
196
238
  def _truncated_call_outcome(call: ToolCall) -> _ToolOutcome:
@@ -200,7 +242,8 @@ def _truncated_call_outcome(call: ToolCall) -> _ToolOutcome:
200
242
  result=_error_result(
201
243
  f"tool call {call.name!r} was not executed: the response hit the "
202
244
  "output token limit, so its arguments may be truncated. "
203
- "Re-issue the call with complete arguments."
245
+ "Re-issue the call with complete arguments.",
246
+ kind="invalid_arguments",
204
247
  ),
205
248
  duration_ms=0,
206
249
  )
@@ -225,24 +268,43 @@ async def _execute_tool(
225
268
  result: ToolResultAgent | None = None
226
269
 
227
270
  if tool is None:
228
- result = _error_result(f"unknown tool: {call.name}")
271
+ result = _error_result(f"unknown tool: {call.name}", kind="unknown_tool")
229
272
  elif call.arguments_error is not None:
230
- result = _error_result(call.arguments_error)
273
+ result = _error_result(call.arguments_error, kind="invalid_arguments")
231
274
  elif not isinstance(call.arguments, dict):
232
275
  result = _error_result(
233
276
  f"invalid arguments for tool {call.name}: expected a JSON object, "
234
- f"got {type(call.arguments).__name__}"
277
+ f"got {type(call.arguments).__name__}",
278
+ kind="invalid_arguments",
235
279
  )
236
280
  elif (problem := validate_arguments(tool.parameters, call.arguments)) is not None:
237
- result = _error_result(f"invalid arguments for tool {call.name}: {problem}")
281
+ result = _error_result(
282
+ f"invalid arguments for tool {call.name}: {problem}",
283
+ kind="invalid_arguments",
284
+ )
238
285
  else:
239
286
  verdict = None
240
287
  if config.before_tool_call is not None:
241
- verdict = await _maybe_await(config.before_tool_call(call, call.arguments))
288
+ # The resolved tool object accompanies the call so harness hooks can
289
+ # read the tool's own declarations (approval tier, timeout, …)
290
+ # instead of keeping a name list in sync with the tool registry.
291
+ # v0.3-style 2-arg hooks keep working.
292
+ if _hook_accepts_tool(config.before_tool_call):
293
+ verdict = await _maybe_await(
294
+ config.before_tool_call(call, call.arguments, tool)
295
+ )
296
+ else:
297
+ verdict = await _maybe_await(
298
+ config.before_tool_call(call, call.arguments)
299
+ )
242
300
  if isinstance(verdict, dict) and verdict.get("block"):
243
- result = _error_result(str(verdict.get("reason", "blocked")))
301
+ result = _error_result(
302
+ str(verdict.get("reason", "blocked")), kind="policy"
303
+ )
244
304
  elif tool.execute is None:
245
- result = _error_result(f"tool {call.name} has no execute callable")
305
+ result = _error_result(
306
+ f"tool {call.name} has no execute callable", kind="tool_error"
307
+ )
246
308
  else:
247
309
  accepting = True
248
310
 
@@ -251,10 +313,34 @@ async def _execute_tool(
251
313
  if accepting and on_update is not None:
252
314
  on_update(partial)
253
315
 
316
+ timeout = effective_timeout(tool, call.name)
254
317
  try:
255
- result = await tool.execute(call.id, call.arguments, abort, forward)
318
+ if timeout is not None:
319
+ result = await asyncio.wait_for(
320
+ tool.execute(call.id, call.arguments, abort, forward),
321
+ timeout=timeout,
322
+ )
323
+ else:
324
+ result = await tool.execute(
325
+ call.id, call.arguments, abort, forward
326
+ )
327
+ except TimeoutError as exc:
328
+ if timeout is not None:
329
+ result = _error_result(
330
+ f"tool {call.name!r} timed out after {timeout:g}s",
331
+ kind="timeout",
332
+ )
333
+ else:
334
+ # The tool raised TimeoutError itself; with no kernel
335
+ # deadline this is a normal tool failure, not a run-abort.
336
+ result = _error_result(
337
+ f"{type(exc).__name__}: {exc}"[:_MAX_ERROR_TEXT],
338
+ kind="tool_error",
339
+ )
256
340
  except Exception as exc: # noqa: BLE001 - degrade, never crash the loop
257
- result = _error_result(f"{type(exc).__name__}: {exc}"[:_MAX_ERROR_TEXT])
341
+ result = _error_result(
342
+ f"{type(exc).__name__}: {exc}"[:_MAX_ERROR_TEXT]
343
+ )
258
344
  finally:
259
345
  accepting = False
260
346
 
@@ -271,17 +357,34 @@ async def _execute_tool(
271
357
  if "terminate" in patched:
272
358
  result.terminate = patched["terminate"]
273
359
 
360
+ # Safety net above the per-tool caps: every result — including MCP and
361
+ # extension tools that enforce no cap of their own — gets the same byte
362
+ # budget and truncation notice before it enters the transcript.
363
+ result = apply_result_budget(result)
364
+
274
365
  duration_ms = round((time.monotonic() - started) * 1000)
275
366
  return _ToolOutcome(call=call, result=result, duration_ms=duration_ms)
276
367
 
277
368
 
369
+ def _is_exclusive(tool: AgentTool | None) -> bool:
370
+ """Whether a call must run alone, after the rest of the batch.
371
+
372
+ Two declarations mean exclusive: ``execution_mode="sequential"`` and the
373
+ ``write`` approval tier (file mutations). This mirrors omp's
374
+ ``concurrency="exclusive"`` for edit/write without hard-coding tool names.
375
+ """
376
+ if tool is None:
377
+ return False
378
+ return tool.execution_mode == "sequential" or tool.approval == "write"
379
+
380
+
278
381
  async def _run_tool_batch(
279
382
  calls: list[ToolCall],
280
383
  config: AgentConfig,
281
384
  abort: AbortToken | None,
282
385
  emit_update: Callable[[AgentEvent], None] | None = None,
283
386
  ) -> list[_ToolOutcome]:
284
- """Execute a tool batch: parallel tools concurrently, sequential in order.
387
+ """Execute a tool batch: parallel tools concurrently, exclusive ones after.
285
388
 
286
389
  Returns outcomes in assistant source order regardless of completion order.
287
390
  ``emit_update`` receives one ``tool_execution_update`` event per streamed
@@ -289,18 +392,12 @@ async def _run_tool_batch(
289
392
  """
290
393
  tools_by_name = {t.name: t for t in config.tools}
291
394
  outcomes: list[_ToolOutcome | None] = [None] * len(calls)
292
- parallel = [
293
- i
294
- for i, call in enumerate(calls)
295
- if tools_by_name.get(call.name) is None
296
- or tools_by_name[call.name].execution_mode != "sequential"
297
- ]
298
- sequential = [
395
+ exclusive = [
299
396
  i
300
397
  for i, call in enumerate(calls)
301
- if tools_by_name.get(call.name) is not None
302
- and tools_by_name[call.name].execution_mode == "sequential"
398
+ if _is_exclusive(tools_by_name.get(call.name))
303
399
  ]
400
+ parallel = [i for i in range(len(calls)) if i not in exclusive]
304
401
 
305
402
  async def run_one(index: int) -> None:
306
403
  call = calls[index]
@@ -319,17 +416,58 @@ async def _run_tool_batch(
319
416
 
320
417
  outcomes[index] = await _execute_tool(call, config, abort, forward)
321
418
 
322
- async def run_parallel() -> None:
419
+ # Two phases: the parallel batch fans out, then exclusive tools run one at
420
+ # a time, in call order. Exclusive tools must not overlap the parallel
421
+ # batch — that is what "exclusive" means (the old implementation ran both
422
+ # tracks concurrently, which was not omp's semantics).
423
+ if parallel:
323
424
  await asyncio.gather(*(run_one(i) for i in parallel))
425
+ for index in exclusive:
426
+ await run_one(index)
427
+ return [outcome for outcome in outcomes if outcome is not None]
324
428
 
325
- async def run_sequential() -> None:
326
- for index in sequential:
327
- await run_one(index)
328
429
 
329
- # Two tracks: the parallel batch fans out while the sequential tools run
330
- # one after another in call order.
331
- await asyncio.gather(run_parallel(), run_sequential())
332
- return [outcome for outcome in outcomes if outcome is not None]
430
+ #: Consecutive identical tool rounds before the loop injects a corrective notice.
431
+ _LOOP_GUARD_THRESHOLD = 5
432
+
433
+ #: Prefix of the synthetic, non-persisted corrective message (the UI filters it).
434
+ LOOP_GUARD_PREFIX = "[tool-loop guard]"
435
+
436
+ _LOOP_GUARD_TEXT = (
437
+ LOOP_GUARD_PREFIX + " The same tool call has repeated {n} times with identical "
438
+ "arguments and produced no new progress. Stop repeating it: change the "
439
+ "arguments, use a different tool, or explain to the user what is blocking you."
440
+ )
441
+
442
+ #: Commands that are legitimate to repeat: they observe a changing state.
443
+ _POLL_COMMAND = re.compile(r"^\s*(sleep|wait|tail|ps|pgrep|top|jobs)\b")
444
+
445
+
446
+ def is_loop_guard_message(message: object) -> bool:
447
+ """Whether ``message`` is the synthetic loop-guard corrective."""
448
+ return isinstance(message, UserMessage) and str(
449
+ getattr(message, "content", "")
450
+ ).startswith(LOOP_GUARD_PREFIX)
451
+
452
+
453
+ def _is_poll_call(call: ToolCall) -> bool:
454
+ """Whether this call is a pure wait/observe poll (exempt from the guard)."""
455
+ if call.name == "wait":
456
+ # Waiting for a background job is exactly the legitimate long poll.
457
+ return True
458
+ if call.name != "bash":
459
+ return False
460
+ return bool(_POLL_COMMAND.match(str(call.arguments.get("command", ""))))
461
+
462
+
463
+ def _calls_signature(calls: list[ToolCall]) -> tuple:
464
+ """Stable signature of a tool batch, for detecting identical repeats."""
465
+ return tuple(
466
+ sorted(
467
+ (call.name, json.dumps(call.arguments, sort_keys=True, default=str))
468
+ for call in calls
469
+ )
470
+ )
333
471
 
334
472
 
335
473
  async def agent_loop(
@@ -358,6 +496,10 @@ async def agent_loop(
358
496
  turns = 0
359
497
  length_failures = 0
360
498
  termination = "stop"
499
+ last_signature: tuple | None = None
500
+ repeat_streak = 0
501
+ guard_injected = False
502
+ tool_stats: dict[str, dict] = {}
361
503
  try:
362
504
  # Input typed while the previous run was finishing is still queued: pick
363
505
  # it up before the first request instead of waiting for a tool round.
@@ -506,6 +648,12 @@ async def agent_loop(
506
648
  )
507
649
  state.messages.append(message)
508
650
  new_messages.append(message)
651
+ stats = tool_stats.setdefault(
652
+ outcome.call.name, {"calls": 0, "errors": 0, "ms": 0}
653
+ )
654
+ stats["calls"] += 1
655
+ stats["errors"] += int(bool(outcome.result.is_error))
656
+ stats["ms"] += outcome.duration_ms
509
657
  yield AgentEvent(
510
658
  type="tool_execution_end",
511
659
  tool_call_id=outcome.call.id,
@@ -524,6 +672,29 @@ async def agent_loop(
524
672
  if length_failures >= _MAX_LENGTH_FAILURES:
525
673
  break # truncation is not resolving: stop instead of re-asking forever
526
674
 
675
+ # Cross-turn loop guard: a model repeating the same call(s) with
676
+ # identical arguments is stuck. Inject one corrective message per
677
+ # run (as a user-role notice) instead of burning max_turns.
678
+ signature = _calls_signature(calls)
679
+ poll_like = all(_is_poll_call(call) for call in calls)
680
+ if poll_like:
681
+ repeat_streak = 0
682
+ elif signature == last_signature:
683
+ repeat_streak += 1
684
+ else:
685
+ last_signature = signature
686
+ repeat_streak = 1
687
+ if repeat_streak >= _LOOP_GUARD_THRESHOLD and not guard_injected:
688
+ guard_injected = True
689
+ notice = UserMessage(
690
+ content=_LOOP_GUARD_TEXT.format(n=repeat_streak),
691
+ timestamp=int(time.time()),
692
+ )
693
+ # Model-facing only: appended to the request context but NOT to
694
+ # new_messages and with no message events, so it is never
695
+ # persisted, rendered as a user turn, or counted by fork/retry.
696
+ state.messages.append(notice)
697
+
527
698
  if config.get_steering_messages is not None:
528
699
  for message in await config.get_steering_messages():
529
700
  state.messages.append(message)
@@ -532,5 +703,16 @@ async def agent_loop(
532
703
  yield AgentEvent(type="message_end", message=message)
533
704
  # else / loop continues: another round with the tool results in context
534
705
  finally:
706
+ # The corrective exists only for the turns after it fired: drop it from
707
+ # the durable transcript so resume/retry/fork never see synthetic text.
708
+ state.messages[:] = [
709
+ message
710
+ for message in state.messages
711
+ if not is_loop_guard_message(message)
712
+ ]
535
713
  state.termination = termination
536
- yield AgentEvent(type="agent_end", new_messages=new_messages)
714
+ yield AgentEvent(
715
+ type="agent_end",
716
+ new_messages=new_messages,
717
+ tool_stats={"tools": tool_stats} if tool_stats else None,
718
+ )
@@ -0,0 +1,123 @@
1
+ """Kernel-level result budget (safety net above the per-tool caps).
2
+
3
+ Every tool — built-in, MCP or extension — runs its result through this policy
4
+ before it is written back to the transcript:
5
+ - a single overlong line is capped (logs/minified files would otherwise blow
6
+ up one line at a time);
7
+ - a result whose text payload exceeds ``MAX_RESULT_BYTES`` keeps its head and
8
+ tail and gets one uniform truncation notice;
9
+ - image blocks are preserved untouched.
10
+
11
+ The module deliberately does not import the loop at runtime (the loop imports
12
+ this), so the result object is handled structurally.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import TYPE_CHECKING
18
+
19
+ from zenagent.types import ImageContent, TextContent
20
+
21
+ if TYPE_CHECKING: # pragma: no cover - typing only
22
+ from zenagent.agent.loop import ToolResultAgent
23
+
24
+ __all__ = [
25
+ "HEAD_BYTES",
26
+ "LINE_TRUNCATION_MARKER",
27
+ "MAX_LINE_CHARS",
28
+ "MAX_RESULT_BYTES",
29
+ "TAIL_BYTES",
30
+ "apply_result_budget",
31
+ ]
32
+
33
+ #: A single line longer than this (in characters) is capped.
34
+ MAX_LINE_CHARS = 2_000
35
+
36
+ #: Total text bytes above which the result keeps only head and tail.
37
+ MAX_RESULT_BYTES = 40_000
38
+
39
+ #: Bytes kept from the head / tail of an oversized result.
40
+ HEAD_BYTES = 20_000
41
+ TAIL_BYTES = 12_000
42
+
43
+ #: Marker inserted where an overlong line was middle-truncated.
44
+ LINE_TRUNCATION_MARKER = " …[line truncated]"
45
+ _LINE_MARKER = LINE_TRUNCATION_MARKER
46
+
47
+
48
+ def _cap_long_lines(text: str) -> tuple[str, int]:
49
+ """Middle-truncate overlong lines; returns the text and changed-line count.
50
+
51
+ Keeping both ends of the line matters: after the byte budget has kept the
52
+ head and tail of the whole payload, a naive prefix cut on the head line
53
+ would throw the tail away again.
54
+ """
55
+ truncated = 0
56
+ out: list[str] = []
57
+ keep = MAX_LINE_CHARS // 2
58
+ for line in text.split("\n"):
59
+ if len(line) > MAX_LINE_CHARS:
60
+ out.append(line[:keep] + _LINE_MARKER + line[-keep:])
61
+ truncated += 1
62
+ else:
63
+ out.append(line)
64
+ return "\n".join(out), truncated
65
+
66
+
67
+ def _truncate_bytes(text: str, total_bytes: int) -> str:
68
+ """Keep the head and tail of ``text`` and mark the removed middle."""
69
+ raw = text.encode("utf-8")
70
+ head = raw[:HEAD_BYTES].decode("utf-8", "ignore")
71
+ tail = raw[-TAIL_BYTES:].decode("utf-8", "ignore")
72
+ removed = total_bytes - HEAD_BYTES - TAIL_BYTES
73
+ notice = (
74
+ f"\n\n… [truncated {removed} of {total_bytes} bytes: kept the first "
75
+ f"{HEAD_BYTES} and last {TAIL_BYTES} (long lines trimmed); narrow the "
76
+ "tool call (read with offset/limit, or grep) for the rest] …\n\n"
77
+ )
78
+ return head + notice + tail
79
+
80
+
81
+ def apply_result_budget(result: ToolResultAgent) -> ToolResultAgent:
82
+ """Cap one tool result's text payloads; image blocks pass through."""
83
+ texts = [
84
+ block.text for block in result.content if isinstance(block, TextContent)
85
+ ]
86
+ if not texts:
87
+ return result
88
+ # Idempotent: a second pass must not re-wrap or double-count.
89
+ if result.details.get("budget", {}).get("truncated") is True:
90
+ return result
91
+
92
+ text = "\n".join(texts)
93
+ original_bytes = len(text.encode("utf-8"))
94
+ if original_bytes <= MAX_RESULT_BYTES:
95
+ # Under budget the payload is returned untouched. Capping a single
96
+ # long line here would destroy one-line payloads (minified HTML/JSON,
97
+ # compact `jq -c` output) that are small enough to keep whole.
98
+ return result
99
+
100
+ budget: dict = {"truncated": True, "original_bytes": original_bytes}
101
+ # Byte-budget first: a single overlong line must not swallow the head and
102
+ # tail that make the truncation recoverable.
103
+ capped = _truncate_bytes(text, original_bytes)
104
+ capped, truncated_lines = _cap_long_lines(capped)
105
+ if truncated_lines:
106
+ budget["truncated_lines"] = truncated_lines
107
+
108
+ images = [
109
+ block for block in result.content if isinstance(block, ImageContent)
110
+ ]
111
+ details = dict(result.details)
112
+ details["budget"] = budget
113
+ # ``type(result)`` avoids importing the loop at module load time (it imports
114
+ # us); the loop's contract is that a tool returns that dataclass, and using
115
+ # the actual class keeps any subclass intact when it has the same fields.
116
+ return type(result)(
117
+ content=[TextContent(text=capped), *images],
118
+ details=details,
119
+ is_error=result.is_error,
120
+ terminate=result.terminate,
121
+ error_kind=result.error_kind,
122
+ )
123
+