leashd 2.2.0__tar.gz → 2.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 (126) hide show
  1. {leashd-2.2.0 → leashd-2.4.0}/CHANGELOG.md +12 -0
  2. {leashd-2.2.0 → leashd-2.4.0}/PKG-INFO +12 -2
  3. {leashd-2.2.0 → leashd-2.4.0}/README.md +11 -1
  4. {leashd-2.2.0 → leashd-2.4.0}/leashd/__init__.py +1 -1
  5. leashd-2.4.0/leashd/agents/runtimes/hook_relay.py +149 -0
  6. {leashd-2.2.0 → leashd-2.4.0}/leashd/agents/runtimes/tmux_session.py +199 -9
  7. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/engine.py +118 -6
  8. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/events.py +1 -0
  9. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/safety/analyzer.py +187 -4
  10. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/safety/audit.py +20 -0
  11. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/safety/gatekeeper.py +27 -0
  12. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/safety/policy.py +33 -3
  13. {leashd-2.2.0 → leashd-2.4.0}/leashd/policies/autonomous.yaml +2 -2
  14. {leashd-2.2.0 → leashd-2.4.0}/leashd/policies/default.yaml +2 -2
  15. {leashd-2.2.0 → leashd-2.4.0}/leashd/policies/permissive.yaml +1 -1
  16. {leashd-2.2.0 → leashd-2.4.0}/leashd/web/tmux_hooks.py +18 -5
  17. {leashd-2.2.0 → leashd-2.4.0}/pyproject.toml +1 -1
  18. {leashd-2.2.0 → leashd-2.4.0}/scripts/_harness/multisession_suite.py +126 -3
  19. {leashd-2.2.0 → leashd-2.4.0}/.claude/settings.json +0 -0
  20. {leashd-2.2.0 → leashd-2.4.0}/.gitignore +0 -0
  21. {leashd-2.2.0 → leashd-2.4.0}/LICENSE +0 -0
  22. {leashd-2.2.0 → leashd-2.4.0}/leashd/__main__.py +0 -0
  23. {leashd-2.2.0 → leashd-2.4.0}/leashd/agents/base.py +0 -0
  24. {leashd-2.2.0 → leashd-2.4.0}/leashd/agents/capabilities.py +0 -0
  25. {leashd-2.2.0 → leashd-2.4.0}/leashd/agents/registry.py +0 -0
  26. {leashd-2.2.0 → leashd-2.4.0}/leashd/agents/runtimes/_helpers.py +0 -0
  27. {leashd-2.2.0 → leashd-2.4.0}/leashd/agents/runtimes/tmux.py +0 -0
  28. {leashd-2.2.0 → leashd-2.4.0}/leashd/agents/runtimes/tmux_manifest.py +0 -0
  29. {leashd-2.2.0 → leashd-2.4.0}/leashd/agents/types.py +0 -0
  30. {leashd-2.2.0 → leashd-2.4.0}/leashd/app.py +0 -0
  31. {leashd-2.2.0 → leashd-2.4.0}/leashd/browser_profile.py +0 -0
  32. {leashd-2.2.0 → leashd-2.4.0}/leashd/cc_plugins.py +0 -0
  33. {leashd-2.2.0 → leashd-2.4.0}/leashd/cli.py +0 -0
  34. {leashd-2.2.0 → leashd-2.4.0}/leashd/cli_run.py +0 -0
  35. {leashd-2.2.0 → leashd-2.4.0}/leashd/config_store.py +0 -0
  36. {leashd-2.2.0 → leashd-2.4.0}/leashd/connectors/base.py +0 -0
  37. {leashd-2.2.0 → leashd-2.4.0}/leashd/connectors/multi.py +0 -0
  38. {leashd-2.2.0 → leashd-2.4.0}/leashd/connectors/telegram.py +0 -0
  39. {leashd-2.2.0 → leashd-2.4.0}/leashd/connectors/telegram_approval.py +0 -0
  40. {leashd-2.2.0 → leashd-2.4.0}/leashd/connectors/telegram_commands.py +0 -0
  41. {leashd-2.2.0 → leashd-2.4.0}/leashd/connectors/telegram_markdown.py +0 -0
  42. {leashd-2.2.0 → leashd-2.4.0}/leashd/connectors/telegram_sessions.py +0 -0
  43. {leashd-2.2.0 → leashd-2.4.0}/leashd/connectors/web.py +0 -0
  44. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/chat_sessions.py +0 -0
  45. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/config.py +0 -0
  46. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/file_delivery.py +0 -0
  47. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/interactions.py +0 -0
  48. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/message_logger.py +0 -0
  49. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/plan_gate.py +0 -0
  50. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/queue.py +0 -0
  51. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/runtime_settings.py +0 -0
  52. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/safety/approval_card.py +0 -0
  53. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/safety/approvals.py +0 -0
  54. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/safety/sandbox.py +0 -0
  55. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/session.py +0 -0
  56. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/session_title.py +0 -0
  57. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/task.py +0 -0
  58. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/task_events.py +0 -0
  59. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/task_memory.py +0 -0
  60. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/task_profile.py +0 -0
  61. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/test_output.py +0 -0
  62. {leashd-2.2.0 → leashd-2.4.0}/leashd/core/workspace.py +0 -0
  63. {leashd-2.2.0 → leashd-2.4.0}/leashd/daemon.py +0 -0
  64. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/SKILL.md +0 -0
  65. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/references/authentication.md +0 -0
  66. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/references/commands.md +0 -0
  67. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/references/profiling.md +0 -0
  68. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/references/proxy-support.md +0 -0
  69. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/references/session-management.md +0 -0
  70. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/references/snapshot-refs.md +0 -0
  71. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/references/trust-boundaries.md +0 -0
  72. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/references/video-recording.md +0 -0
  73. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/references/webgpu.md +0 -0
  74. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/templates/authenticated-session.sh +0 -0
  75. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/templates/capture-workflow.sh +0 -0
  76. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/agent-browser/templates/form-automation.sh +0 -0
  77. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/skills/search-batch.sh +0 -0
  78. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/webui/app.js +0 -0
  79. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/webui/icons/icon-192.png +0 -0
  80. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/webui/icons/icon-512.png +0 -0
  81. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/webui/index.html +0 -0
  82. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/webui/manifest.json +0 -0
  83. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/webui/service-worker.js +0 -0
  84. {leashd-2.2.0 → leashd-2.4.0}/leashd/data/webui/style.css +0 -0
  85. {leashd-2.2.0 → leashd-2.4.0}/leashd/exceptions.py +0 -0
  86. {leashd-2.2.0 → leashd-2.4.0}/leashd/git/formatter.py +0 -0
  87. {leashd-2.2.0 → leashd-2.4.0}/leashd/git/handler.py +0 -0
  88. {leashd-2.2.0 → leashd-2.4.0}/leashd/git/models.py +0 -0
  89. {leashd-2.2.0 → leashd-2.4.0}/leashd/git/service.py +0 -0
  90. {leashd-2.2.0 → leashd-2.4.0}/leashd/main.py +0 -0
  91. {leashd-2.2.0 → leashd-2.4.0}/leashd/middleware/auth.py +0 -0
  92. {leashd-2.2.0 → leashd-2.4.0}/leashd/middleware/base.py +0 -0
  93. {leashd-2.2.0 → leashd-2.4.0}/leashd/middleware/rate_limit.py +0 -0
  94. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/base.py +0 -0
  95. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/_task_prompts.py +0 -0
  96. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/audit_plugin.py +0 -0
  97. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/browser_tools.py +0 -0
  98. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/merge_resolver.py +0 -0
  99. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/playbooks/linkedin_comment.yaml +0 -0
  100. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/task_orchestrator.py +0 -0
  101. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/test_config_loader.py +0 -0
  102. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/web_agent.py +0 -0
  103. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/web_checkpoint.py +0 -0
  104. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/web_interaction_logger.py +0 -0
  105. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/builtin/workflow.py +0 -0
  106. {leashd-2.2.0 → leashd-2.4.0}/leashd/plugins/registry.py +0 -0
  107. {leashd-2.2.0 → leashd-2.4.0}/leashd/policies/.gitkeep +0 -0
  108. {leashd-2.2.0 → leashd-2.4.0}/leashd/policies/dev-tools.yaml +0 -0
  109. {leashd-2.2.0 → leashd-2.4.0}/leashd/policies/strict.yaml +0 -0
  110. {leashd-2.2.0 → leashd-2.4.0}/leashd/setup.py +0 -0
  111. {leashd-2.2.0 → leashd-2.4.0}/leashd/skills.py +0 -0
  112. {leashd-2.2.0 → leashd-2.4.0}/leashd/storage/base.py +0 -0
  113. {leashd-2.2.0 → leashd-2.4.0}/leashd/storage/memory.py +0 -0
  114. {leashd-2.2.0 → leashd-2.4.0}/leashd/storage/sqlite.py +0 -0
  115. {leashd-2.2.0 → leashd-2.4.0}/leashd/tunnel.py +0 -0
  116. {leashd-2.2.0 → leashd-2.4.0}/leashd/web/app.py +0 -0
  117. {leashd-2.2.0 → leashd-2.4.0}/leashd/web/auth.py +0 -0
  118. {leashd-2.2.0 → leashd-2.4.0}/leashd/web/models.py +0 -0
  119. {leashd-2.2.0 → leashd-2.4.0}/leashd/web/push.py +0 -0
  120. {leashd-2.2.0 → leashd-2.4.0}/leashd/web/routes.py +0 -0
  121. {leashd-2.2.0 → leashd-2.4.0}/leashd/web/tmux_jsonl.py +0 -0
  122. {leashd-2.2.0 → leashd-2.4.0}/leashd/web/tmux_server.py +0 -0
  123. {leashd-2.2.0 → leashd-2.4.0}/leashd/web/ws_handler.py +0 -0
  124. {leashd-2.2.0 → leashd-2.4.0}/scripts/_harness/drive.py +0 -0
  125. {leashd-2.2.0 → leashd-2.4.0}/scripts/_harness/soak_model.py +0 -0
  126. {leashd-2.2.0 → leashd-2.4.0}/scripts/_harness/tmux_harness.py +0 -0
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.4.0] - 2026-10-17
4
+ - **changed**: "Approve all" now survives `/clear` and `/stop`; a directory or mode change still drops it.
5
+ - **changed**: fewer prompts for reads that already ran unasked in another spelling: SQL fed to `psql` by heredoc on a trusted SSH host, `begin read only; … commit` transactions, and `grep -c` counts of a `.env` variable prefix.
6
+ - **fixed**: approval prompts name the gated command instead of a `$(…)` inside it or a `case` pattern (`Bash::*queued*`), sourcing a file names the file, and `/usr/bin/grep` is treated as `grep`.
7
+
8
+ ## [2.3.0] - 2026-10-10
9
+ - **added**: while background subagents are still working after Claude's turn has ended, the chat shows a line under the last reply naming them, until they report back.
10
+ - **added**: a `tool_ran_ungated` audit entry and `tmux_tool_ran_ungated` log line for any tool call that finishes without having gone through the gate.
11
+ - **fixed**: a tool call could run with no policy check and no audit entry (about 1 in 900) when its hook hit a connection the daemon had just closed, or arrived while the daemon was restarting. The gating hooks now retry until leashd answers and deny if it never does.
12
+ - **fixed**: a tool line left under a reply by a background subagent is cleared when the agent finishes, and its hand-back no longer shows as "Running: …".
13
+ - **fixed**: opening a running conversation in your own terminal (`claude` → `/resume`) no longer posts Claude Code's "No response requested." placeholder into the chat as the agent's reply.
14
+
3
15
  ## [2.2.0] - 2026-10-03
4
16
  - **added**: conversations name themselves, so `/session`, the switch banner and the "replied" / "waiting on you" notices read `#2 · Login test fix · api`. The name is Claude Code's own session title, or the first line of your first message until it has one.
5
17
  - **added**: fewer prompts: read-only `gh` commands (`gh run list`, `gh pr view`…), `git fetch`, `git add`, `mkdir`, `node --check` and `vitest`/`jest` no longer ask when chained to an approved `curl` or `ssh`.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: leashd
3
- Version: 2.2.0
3
+ Version: 2.4.0
4
4
  Summary: Run Claude Code as a governed daemon: a real claude TUI in tmux behind a sandbox, YAML policies and human-in-the-loop approval
5
5
  Project-URL: Homepage, https://github.com/vmehera123/leashd
6
6
  Project-URL: Repository, https://github.com/vmehera123/leashd
@@ -152,6 +152,8 @@ Every tool call the agent makes passes through three layers before it can execut
152
152
 
153
153
  The pipeline is connector-agnostic: same sandbox, same rules, same buttons whether you're in the browser or on your phone. Every attempt and decision is appended to `.leashd/audit.jsonl`.
154
154
 
155
+ The gate fails closed. If a tool call cannot reach leashd, for example while the daemon restarts, it waits up to 60 seconds for an answer and is denied if none comes. A call that still finishes without a verdict is written to the audit log as `tool_ran_ungated`, so `grep tool_ran_ungated .leashd/audit.jsonl` should always print nothing.
156
+
155
157
  **Five policies ship in `policies/`:**
156
158
 
157
159
  | Policy | Auto-allows | Requires approval |
@@ -179,6 +181,12 @@ LEASHD_POLICY_FILES=policies/default.yaml,policies/my-overrides.yaml # merged,
179
181
 
180
182
  leashd spawns a real interactive `claude` TUI in a tmux pane and talks to it the way a human would — so native slash commands pass straight through from chat, dialogs the CLI opens (model picker, consent prompts) get bridged to inline buttons, and `/screen` gives you a live snapshot of the terminal. Tool calls are intercepted by Claude Code `PreToolUse` hooks and routed back into leashd's gatekeeper, so nothing escapes the pipeline.
181
183
 
184
+ **Background subagents stay visible.** Claude can start subagents in the background and end its turn while they work. The chat then shows one line under the last reply until they report back, and Claude's follow-up arrives as a normal reply:
185
+
186
+ ```
187
+ ⏳ 2 background agents are still working: Audit the API routes, Check test coverage. Claude replies here when they report back.
188
+ ```
189
+
182
190
  **Restarting is safe.** tmux panes live on a tmux server of their own, so `leashd restart` — to pick up a fix, a config change, a new build — no longer ends the work in them. The daemon writes what it needs to find each pane again, leaves them running on the way out, and re-adopts them on the way in: same conversation, same session, same directory. A turn that was still running keeps streaming into the chat where it left off, and a Telegram message you send during the restart runs once the daemon is back. `leashd stop --end-agents` ends them instead. See [docs/agents.md](docs/agents.md#restarting-without-losing-work).
183
191
 
184
192
  **Adding a runtime** — the runtime registry (`agents/registry.py`) is kept for that: register a factory and select it with `LEASHD_AGENT_RUNTIME`. Embedders can also pass any `BaseAgent` to `build_engine(agent=...)` to put their own agent behind the same pipeline.
@@ -276,7 +284,7 @@ Available in both the Web UI and Telegram.
276
284
 
277
285
  | Command | Description |
278
286
  |---|---|
279
- | `/task <description>` | Autonomous: implement → verify → PR |
287
+ | `/task <description>` | Autonomous: implement → verify, plus an opt-in review |
280
288
  | `/goal <condition>` | Set a completion condition the agent works toward across turns until a fast model confirms it's met |
281
289
  | `/web <instruction>` | Autonomous web automation with content-level human approval |
282
290
  | `/plan <text>` | Plan mode — agent proposes, you approve before execution |
@@ -366,6 +374,7 @@ leashd model show / set <opus|sonnet|claude-…> / clear
366
374
 
367
375
  # Task orchestrator
368
376
  leashd orchestrator enable / disable / show
377
+ leashd run "fix the flaky login test" # submit a /task and block until it finishes
369
378
 
370
379
  # Web UI
371
380
  leashd webui show / enable / disable / url
@@ -388,6 +397,7 @@ leashd ssh show
388
397
  # Agent tuning
389
398
  leashd effort show / set <low|medium|high|xhigh|max> # default: medium
390
399
  leashd turns show / set <N> # default: 120
400
+ leashd tool-calls show / set <N> # -1 for unlimited
391
401
 
392
402
  # Plugins and skills
393
403
  leashd plugin list / add <source> / remove <name> / enable <name> / disable <name>
@@ -104,6 +104,8 @@ Every tool call the agent makes passes through three layers before it can execut
104
104
 
105
105
  The pipeline is connector-agnostic: same sandbox, same rules, same buttons whether you're in the browser or on your phone. Every attempt and decision is appended to `.leashd/audit.jsonl`.
106
106
 
107
+ The gate fails closed. If a tool call cannot reach leashd, for example while the daemon restarts, it waits up to 60 seconds for an answer and is denied if none comes. A call that still finishes without a verdict is written to the audit log as `tool_ran_ungated`, so `grep tool_ran_ungated .leashd/audit.jsonl` should always print nothing.
108
+
107
109
  **Five policies ship in `policies/`:**
108
110
 
109
111
  | Policy | Auto-allows | Requires approval |
@@ -131,6 +133,12 @@ LEASHD_POLICY_FILES=policies/default.yaml,policies/my-overrides.yaml # merged,
131
133
 
132
134
  leashd spawns a real interactive `claude` TUI in a tmux pane and talks to it the way a human would — so native slash commands pass straight through from chat, dialogs the CLI opens (model picker, consent prompts) get bridged to inline buttons, and `/screen` gives you a live snapshot of the terminal. Tool calls are intercepted by Claude Code `PreToolUse` hooks and routed back into leashd's gatekeeper, so nothing escapes the pipeline.
133
135
 
136
+ **Background subagents stay visible.** Claude can start subagents in the background and end its turn while they work. The chat then shows one line under the last reply until they report back, and Claude's follow-up arrives as a normal reply:
137
+
138
+ ```
139
+ ⏳ 2 background agents are still working: Audit the API routes, Check test coverage. Claude replies here when they report back.
140
+ ```
141
+
134
142
  **Restarting is safe.** tmux panes live on a tmux server of their own, so `leashd restart` — to pick up a fix, a config change, a new build — no longer ends the work in them. The daemon writes what it needs to find each pane again, leaves them running on the way out, and re-adopts them on the way in: same conversation, same session, same directory. A turn that was still running keeps streaming into the chat where it left off, and a Telegram message you send during the restart runs once the daemon is back. `leashd stop --end-agents` ends them instead. See [docs/agents.md](docs/agents.md#restarting-without-losing-work).
135
143
 
136
144
  **Adding a runtime** — the runtime registry (`agents/registry.py`) is kept for that: register a factory and select it with `LEASHD_AGENT_RUNTIME`. Embedders can also pass any `BaseAgent` to `build_engine(agent=...)` to put their own agent behind the same pipeline.
@@ -228,7 +236,7 @@ Available in both the Web UI and Telegram.
228
236
 
229
237
  | Command | Description |
230
238
  |---|---|
231
- | `/task <description>` | Autonomous: implement → verify → PR |
239
+ | `/task <description>` | Autonomous: implement → verify, plus an opt-in review |
232
240
  | `/goal <condition>` | Set a completion condition the agent works toward across turns until a fast model confirms it's met |
233
241
  | `/web <instruction>` | Autonomous web automation with content-level human approval |
234
242
  | `/plan <text>` | Plan mode — agent proposes, you approve before execution |
@@ -318,6 +326,7 @@ leashd model show / set <opus|sonnet|claude-…> / clear
318
326
 
319
327
  # Task orchestrator
320
328
  leashd orchestrator enable / disable / show
329
+ leashd run "fix the flaky login test" # submit a /task and block until it finishes
321
330
 
322
331
  # Web UI
323
332
  leashd webui show / enable / disable / url
@@ -340,6 +349,7 @@ leashd ssh show
340
349
  # Agent tuning
341
350
  leashd effort show / set <low|medium|high|xhigh|max> # default: medium
342
351
  leashd turns show / set <N> # default: 120
352
+ leashd tool-calls show / set <N> # -1 for unlimited
343
353
 
344
354
  # Plugins and skills
345
355
  leashd plugin list / add <source> / remove <name> / enable <name> / disable <name>
@@ -1,3 +1,3 @@
1
1
  """leashd — Remote AI-assisted development with safety constraints."""
2
2
 
3
- __version__ = "2.2.0"
3
+ __version__ = "2.4.0"
@@ -0,0 +1,149 @@
1
+ """Deliver one gating Claude Code hook to leashd, failing closed.
2
+
3
+ Claude Code runs a tool when its hook cannot be delivered. This command posts
4
+ the hook over a fresh connection, keeps trying while the daemon is away (a
5
+ restart), and answers ``deny`` itself when no verdict can be had. Standard
6
+ library only: it runs once per tool call, under ``python -I -S``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import http.client
12
+ import json
13
+ import sys
14
+ import time
15
+ from typing import TYPE_CHECKING, Any
16
+ from urllib.parse import urlsplit
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Callable
20
+ from typing import BinaryIO, TextIO
21
+
22
+ CONNECT_TIMEOUT_SECONDS = 2.0
23
+ RETRY_BUDGET_SECONDS = 60.0
24
+ FIRST_RETRY_DELAY_SECONDS = 0.1
25
+ LONGEST_RETRY_DELAY_SECONDS = 2.0
26
+ PERMISSION_REQUEST = "PermissionRequest"
27
+ PANE_TOKEN_HEADER = "X-Leashd-Pane" # noqa: S105
28
+ UNREACHABLE_REASON = (
29
+ "leashd could not be reached to check this tool call, so it did not run. "
30
+ "Nothing is wrong with the call itself; try again once leashd is back."
31
+ )
32
+ REFUSED_REASON = (
33
+ "leashd refused this pane's safety hook, so the tool call did not run. "
34
+ "This pane has to be restarted."
35
+ )
36
+ BROKEN_REASON = "leashd's safety hook failed, so the tool call did not run."
37
+
38
+
39
+ def deny(event: str, reason: str) -> dict[str, Any]:
40
+ if event == PERMISSION_REQUEST:
41
+ return {
42
+ "hookSpecificOutput": {
43
+ "hookEventName": PERMISSION_REQUEST,
44
+ "decision": {"behavior": "deny"},
45
+ }
46
+ }
47
+ return {
48
+ "hookSpecificOutput": {
49
+ "hookEventName": "PreToolUse",
50
+ "permissionDecision": "deny",
51
+ "permissionDecisionReason": reason,
52
+ }
53
+ }
54
+
55
+
56
+ def read_headers(header_file: str) -> dict[str, str]:
57
+ headers: dict[str, str] = {}
58
+ with open(header_file) as handle:
59
+ for line in handle:
60
+ name, separator, value = line.partition(":")
61
+ if separator:
62
+ headers[name.strip()] = value.strip()
63
+ return headers
64
+
65
+
66
+ def post(url: str, headers: dict[str, str], body: bytes) -> tuple[int, bytes]:
67
+ target = urlsplit(url)
68
+ connection = http.client.HTTPConnection(
69
+ target.hostname or "127.0.0.1", target.port, timeout=CONNECT_TIMEOUT_SECONDS
70
+ )
71
+ try:
72
+ connection.connect()
73
+ connection.sock.settimeout(None)
74
+ connection.request(
75
+ "POST",
76
+ target.path,
77
+ body=body,
78
+ headers={
79
+ **headers,
80
+ "Content-Type": "application/json",
81
+ "Connection": "close",
82
+ },
83
+ )
84
+ response = connection.getresponse()
85
+ return response.status, response.read()
86
+ finally:
87
+ connection.close()
88
+
89
+
90
+ def verdict_in(payload: bytes) -> dict[str, Any] | None:
91
+ try:
92
+ verdict = json.loads(payload)
93
+ except ValueError:
94
+ return None
95
+ if isinstance(verdict, dict) and isinstance(
96
+ verdict.get("hookSpecificOutput"), dict
97
+ ):
98
+ return verdict
99
+ return None
100
+
101
+
102
+ def relay(
103
+ event: str,
104
+ url: str,
105
+ headers: dict[str, str],
106
+ body: bytes,
107
+ *,
108
+ send: Callable[[str, dict[str, str], bytes], tuple[int, bytes]] = post,
109
+ clock: Callable[[], float] = time.monotonic,
110
+ sleep: Callable[[float], None] = time.sleep,
111
+ budget: float = RETRY_BUDGET_SECONDS,
112
+ ) -> dict[str, Any]:
113
+ give_up_at = clock() + budget
114
+ delay = FIRST_RETRY_DELAY_SECONDS
115
+ while True:
116
+ status: int | None
117
+ try:
118
+ status, payload = send(url, headers, body)
119
+ except (OSError, http.client.HTTPException):
120
+ status, payload = None, b""
121
+ if status == 200:
122
+ verdict = verdict_in(payload)
123
+ if verdict is not None:
124
+ return verdict
125
+ elif status is not None and 400 <= status < 500:
126
+ return deny(event, REFUSED_REASON)
127
+ if clock() + delay > give_up_at:
128
+ return deny(event, UNREACHABLE_REASON)
129
+ sleep(delay)
130
+ delay = min(delay * 2, LONGEST_RETRY_DELAY_SECONDS)
131
+
132
+
133
+ def main(argv: list[str], stdin: BinaryIO, stdout: TextIO) -> int:
134
+ event = argv[1] if len(argv) > 1 else "PreToolUse"
135
+ try:
136
+ _, _, url, header_file, pane_token = argv
137
+ headers = read_headers(header_file)
138
+ if pane_token:
139
+ headers[PANE_TOKEN_HEADER] = pane_token
140
+ verdict = relay(event, url, headers, stdin.read())
141
+ except Exception:
142
+ verdict = deny(event, BROKEN_REASON)
143
+ stdout.write(json.dumps(verdict))
144
+ stdout.flush()
145
+ return 0
146
+
147
+
148
+ if __name__ == "__main__":
149
+ sys.exit(main(sys.argv, sys.stdin.buffer, sys.stdout))
@@ -30,6 +30,7 @@ import secrets
30
30
  import shlex
31
31
  import shutil
32
32
  import subprocess
33
+ import sys
33
34
  import time
34
35
  import unicodedata
35
36
  from dataclasses import dataclass
@@ -54,7 +55,7 @@ from leashd.agents.runtimes.tmux_manifest import (
54
55
  session_id_from_tmux_name,
55
56
  write_manifest,
56
57
  )
57
- from leashd.core.events import LATE_REPLY, SESSION_TITLED, Event
58
+ from leashd.core.events import BACKGROUND_AGENTS, LATE_REPLY, SESSION_TITLED, Event
58
59
  from leashd.core.safety.gatekeeper import FILE_EDIT_TOOLS
59
60
  from leashd.core.safety.policy import normalize_tool_name
60
61
  from leashd.exceptions import AgentError
@@ -102,6 +103,15 @@ def _api_error_kind(record: dict[str, Any]) -> str | None:
102
103
  return str(record.get("error") or "unknown")
103
104
 
104
105
 
106
+ def _is_placeholder_reply(record: dict[str, Any]) -> bool:
107
+ message = record.get("message")
108
+ return (
109
+ isinstance(message, dict)
110
+ and message.get("model") == _SYNTHETIC_MODEL
111
+ and record.get("isApiErrorMessage") is not True
112
+ )
113
+
114
+
105
115
  def _is_interrupt_record(record: dict[str, Any]) -> bool:
106
116
  message = record.get("message")
107
117
  content = message.get("content") if isinstance(message, dict) else None
@@ -142,6 +152,35 @@ def _is_followup_text(queued: str, followup: str) -> bool:
142
152
  return queued == followup or queued.endswith(f" {followup}")
143
153
 
144
154
 
155
+ _UNANNOUNCED_TOOLS = frozenset({"SubagentHandback"})
156
+ _TASK_NOTIFICATION_ID_RE = re.compile(
157
+ r"\A\s*<task-notification>\s*<task-id>([^<\s]+)</task-id>"
158
+ )
159
+
160
+
161
+ def _launched_background_agent(record: dict[str, Any]) -> tuple[str, str] | None:
162
+ """The id and description of a subagent this record started in the background."""
163
+ result = record.get("toolUseResult")
164
+ if not isinstance(result, dict) or result.get("isAsync") is not True:
165
+ return None
166
+ if result.get("status") != "async_launched":
167
+ return None
168
+ agent_id = result.get("agentId")
169
+ if not isinstance(agent_id, str) or not agent_id:
170
+ return None
171
+ description = result.get("description")
172
+ return agent_id, description.strip() if isinstance(description, str) else ""
173
+
174
+
175
+ def _notified_task_id(record: dict[str, Any]) -> str | None:
176
+ """The background task a queued ``<task-notification>`` reports on."""
177
+ content = record.get("content")
178
+ if not isinstance(content, str):
179
+ return None
180
+ match = _TASK_NOTIFICATION_ID_RE.match(content)
181
+ return match.group(1) if match else None
182
+
183
+
145
184
  def _prompt_text(record: dict[str, Any]) -> str:
146
185
  message = record.get("message")
147
186
  content = message.get("content") if isinstance(message, dict) else None
@@ -784,6 +823,8 @@ _PERM_UNMATCHED_SETTLE_S = 2.0
784
823
  _ORPHANED_PERM_SETTLE_S = 3.0
785
824
  _TRANSCRIPT_TAIL_BYTES = 4 * 1024 * 1024
786
825
  _HOOKED_CALLS_KEPT = 64
826
+ _GATED_CALL_IDS_KEPT = 2048
827
+ _HOOK_RELAY_SCRIPT = Path(__file__).with_name("hook_relay.py")
787
828
  _PERM_QUESTION_WRAP_ROWS = 2
788
829
  _QUEUED_INPUT_HINT_RE = re.compile(r"^ \S.*\bto send now\s*$")
789
830
  _SPINNER_SCAN_ROWS = 6
@@ -2257,6 +2298,7 @@ class TmuxClaudeSession:
2257
2298
  self.pane_token: str | None = None
2258
2299
  self.claude_uuid: str | None = None
2259
2300
  self.title: str | None = None
2301
+ self.background_agents: dict[str, str] = {}
2260
2302
  self.turn: TmuxTurn | None = None
2261
2303
  # Per-turn plan-gate state — shared logic with the engine's
2262
2304
  # can_use_tool. Recreated each turn in begin_turn() so it survives
@@ -2294,6 +2336,7 @@ class TmuxClaudeSession:
2294
2336
  self.permission_hooks_inflight = 0
2295
2337
  self.regate_active = False
2296
2338
  self.hooked_calls: dict[str, tuple[str, dict[str, Any]]] = {}
2339
+ self.gated_call_ids: dict[str, None] = {}
2297
2340
  self._hooked_at: dict[str, float] = {}
2298
2341
  self.billed_message_ids: set[str] = set()
2299
2342
  self.unreported_usage = TurnUsage()
@@ -4363,6 +4406,10 @@ class TmuxClaudeSession:
4363
4406
  def note_hooked_call(
4364
4407
  self, tool_use_id: str, tool_name: str, tool_input: dict[str, Any]
4365
4408
  ) -> None:
4409
+ if tool_use_id:
4410
+ self.gated_call_ids[tool_use_id] = None
4411
+ while len(self.gated_call_ids) > _GATED_CALL_IDS_KEPT:
4412
+ del self.gated_call_ids[next(iter(self.gated_call_ids))]
4366
4413
  key = tool_use_id or _tool_identity_key("", tool_name, tool_input)
4367
4414
  self.hooked_calls.pop(key, None)
4368
4415
  self.hooked_calls[key] = (tool_name, tool_input)
@@ -4372,6 +4419,18 @@ class TmuxClaudeSession:
4372
4419
  del self.hooked_calls[oldest]
4373
4420
  self._hooked_at.pop(oldest, None)
4374
4421
 
4422
+ def ran_without_the_gate(self, tool_use_id: str) -> bool:
4423
+ """Did a finished call never come through this session's ``PreToolUse``?
4424
+
4425
+ Only answerable once this session object has gated a call: a pane
4426
+ adopted after a restart finishes calls the previous daemon gated.
4427
+ """
4428
+ return bool(
4429
+ tool_use_id
4430
+ and self.gated_call_ids
4431
+ and tool_use_id not in self.gated_call_ids
4432
+ )
4433
+
4375
4434
  def forget_hooked_call(
4376
4435
  self,
4377
4436
  tool_use_id: str,
@@ -4945,14 +5004,42 @@ class TmuxSessionManager:
4945
5004
  "matcher": ".*",
4946
5005
  "hooks": [
4947
5006
  {
4948
- "type": "http",
4949
- "url": self._hook_url(event),
5007
+ "type": "command",
5008
+ "command": self._relay_command(event, pane_token),
4950
5009
  "timeout": self._pre_tool_hook_timeout(),
4951
- "headers": self._hook_headers(pane_token),
4952
5010
  }
4953
5011
  ],
4954
5012
  }
4955
5013
 
5014
+ def _relay_command(self, event: str, pane_token: str | None) -> str:
5015
+ """The shell command that carries one gating hook to leashd.
5016
+
5017
+ Claude Code runs the tool when an HTTP hook cannot be delivered, so a
5018
+ reset connection or a restarting daemon let a call past the gate. The
5019
+ relay retries and then denies. The secret stays in a private file; the
5020
+ pane token is this spawn's alone and travels in argv, so a replaced
5021
+ pane can never pick up its successor's.
5022
+ """
5023
+ return shlex.join(
5024
+ [
5025
+ sys.executable,
5026
+ "-I",
5027
+ "-S",
5028
+ str(_HOOK_RELAY_SCRIPT),
5029
+ event,
5030
+ self._hook_url(event),
5031
+ str(self._relay_secret_file()),
5032
+ pane_token or "",
5033
+ ]
5034
+ )
5035
+
5036
+ def _relay_secret_file(self) -> Path:
5037
+ path = self._socket_dir / "hook-relay-headers"
5038
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
5039
+ with os.fdopen(fd, "w") as handle:
5040
+ handle.write(f"X-Leashd-Token: {self._secret}\n")
5041
+ return path
5042
+
4956
5043
  def native_allow_for_chat(self, chat_id: str | None) -> list[str]:
4957
5044
  """``permissions.allow`` entries for a chat, or empty when safety is
4958
5045
  unbound (tests / sandbox spawns) or a blanket auto-approve is in force.
@@ -5127,6 +5214,7 @@ class TmuxSessionManager:
5127
5214
  await cs.teardown()
5128
5215
  if self._tmux_session_exists(cs.tmux_name) is not False:
5129
5216
  self._kill_tmux_session(cs.tmux_name)
5217
+ await self._forget_background_agents(cs)
5130
5218
 
5131
5219
  def sessions_for_chat(self, chat_id: str) -> list[TmuxClaudeSession]:
5132
5220
  return [cs for cs in self._sessions.values() if cs.chat_id == chat_id]
@@ -5437,6 +5525,7 @@ class TmuxSessionManager:
5437
5525
  old = self._sessions.pop(session_id, None)
5438
5526
  if old is not None:
5439
5527
  await old.teardown()
5528
+ await self._forget_background_agents(old)
5440
5529
  for uuid_key, sid in list(self._by_uuid.items()):
5441
5530
  if sid == session_id:
5442
5531
  del self._by_uuid[uuid_key]
@@ -5839,8 +5928,12 @@ class TmuxSessionManager:
5839
5928
  cs.note_hooked_call(tool_use_id, tool_name, tool_input)
5840
5929
  if cs is not None and cs.turn is not None:
5841
5930
  cs.turn.mark_activity()
5842
- if cs.turn.on_tool_activity is not None and cs.turn.claim_hook_activity(
5843
- _tool_identity_key("", tool_name, tool_input)
5931
+ if (
5932
+ cs.turn.on_tool_activity is not None
5933
+ and tool_name not in _UNANNOUNCED_TOOLS
5934
+ and cs.turn.claim_hook_activity(
5935
+ _tool_identity_key("", tool_name, tool_input)
5936
+ )
5844
5937
  ):
5845
5938
  await safe_callback(
5846
5939
  cs.turn.on_tool_activity,
@@ -6046,6 +6139,36 @@ class TmuxSessionManager:
6046
6139
  # model and the pane hung.)
6047
6140
  return _permission_to_hook(decision)
6048
6141
 
6142
+ def _record_ungated_call(self, cs: TmuxClaudeSession, body: dict[str, Any]) -> None:
6143
+ """Put a call that ran without leashd's verdict on the audit trail.
6144
+
6145
+ The relay makes this unreachable for a pane spawned with it; a pane
6146
+ still on HTTP hooks, or a hook Claude Code skipped, lands here. The
6147
+ audit log is the record of what an agent did, so a call the gate never
6148
+ saw is written to it rather than left out.
6149
+ """
6150
+ tool_use_id = str(body.get("tool_use_id") or "")
6151
+ if not cs.ran_without_the_gate(tool_use_id):
6152
+ return
6153
+ cs.gated_call_ids[tool_use_id] = None
6154
+ tool_name = str(body.get("tool_name", ""))
6155
+ tool_input = body.get("tool_input")
6156
+ logger.warning(
6157
+ "tmux_tool_ran_ungated",
6158
+ session_id=cs.session_id,
6159
+ chat_id=cs.chat_id,
6160
+ tool_name=tool_name,
6161
+ tool_use_id=tool_use_id,
6162
+ )
6163
+ if self._audit is not None:
6164
+ self._audit.log_ungated_tool(
6165
+ cs.session_id,
6166
+ tool_name,
6167
+ tool_input if isinstance(tool_input, dict) else {},
6168
+ tool_use_id,
6169
+ session_mode=cs.mode,
6170
+ )
6171
+
6049
6172
  def stuck_permission_id(self, cs: TmuxClaudeSession) -> str | None:
6050
6173
  """A short fingerprint of the permission dialog on screen, when nobody
6051
6174
  is answering it.
@@ -6498,6 +6621,7 @@ class TmuxSessionManager:
6498
6621
  return
6499
6622
  if event == "PostToolUse":
6500
6623
  tool_input = body.get("tool_input")
6624
+ self._record_ungated_call(cs, body)
6501
6625
  cs.forget_hooked_call(
6502
6626
  str(body.get("tool_use_id") or ""),
6503
6627
  str(body.get("tool_name", "")),
@@ -6531,6 +6655,7 @@ class TmuxSessionManager:
6531
6655
  turn_active=cs.turn is not None and not cs.turn.stop_event.is_set(),
6532
6656
  )
6533
6657
  cs.complete_turn()
6658
+ await self._forget_background_agents(cs)
6534
6659
 
6535
6660
  @staticmethod
6536
6661
  def _end_turn_on_api_error(cs: TmuxClaudeSession, body: dict[str, Any]) -> None:
@@ -7075,6 +7200,13 @@ class TmuxSessionManager:
7075
7200
  if obj_type == "assistant":
7076
7201
  if turn is not None:
7077
7202
  turn.mark_activity()
7203
+ if _is_placeholder_reply(obj):
7204
+ logger.info(
7205
+ "tmux_placeholder_reply_skipped",
7206
+ session_id=cs.session_id,
7207
+ chat_id=cs.chat_id,
7208
+ )
7209
+ return
7078
7210
  message = obj.get("message", {})
7079
7211
  model = message.get("model")
7080
7212
  if isinstance(model, str) and model and model != _SYNTHETIC_MODEL:
@@ -7093,6 +7225,10 @@ class TmuxSessionManager:
7093
7225
  for block in _content_blocks(obj):
7094
7226
  if block.get("type") == "tool_result":
7095
7227
  cs.forget_hooked_call(str(block.get("tool_use_id") or ""))
7228
+ launched = _launched_background_agent(obj)
7229
+ if launched is not None and launched[0] not in cs.background_agents:
7230
+ cs.background_agents[launched[0]] = launched[1]
7231
+ await self._announce_background_agents(cs)
7096
7232
  if live_turn is not None and _is_interrupt_record(obj):
7097
7233
  live_turn.interrupted = True
7098
7234
  if turn is not None:
@@ -7101,6 +7237,11 @@ class TmuxSessionManager:
7101
7237
 
7102
7238
  if obj_type == "queue-operation":
7103
7239
  self._handle_queue_operation(cs, turn, obj)
7240
+ if obj.get("operation") == "enqueue":
7241
+ finished = _notified_task_id(obj)
7242
+ if finished is not None and finished in cs.background_agents:
7243
+ del cs.background_agents[finished]
7244
+ await self._announce_background_agents(cs)
7104
7245
  return
7105
7246
 
7106
7247
  if obj_type == "ai-title":
@@ -7119,6 +7260,41 @@ class TmuxSessionManager:
7119
7260
  ):
7120
7261
  self._spawn_late_reply(cs, turn)
7121
7262
 
7263
+ async def _forget_background_agents(self, cs: TmuxClaudeSession) -> None:
7264
+ if not cs.background_agents:
7265
+ return
7266
+ cs.background_agents.clear()
7267
+ await self._announce_background_agents(cs)
7268
+
7269
+ async def _announce_background_agents(self, cs: TmuxClaudeSession) -> None:
7270
+ """Report which background subagents this pane is still waiting on.
7271
+
7272
+ Claude ends its turn while they work and starts one of its own when
7273
+ each reports back, so between the two the chat has nothing to say the
7274
+ conversation is still busy. Launches are read off the tool result
7275
+ claude records for an ``Agent`` call it backgrounded, and the end of
7276
+ each off the ``<task-notification>`` it queues for itself.
7277
+ """
7278
+ logger.info(
7279
+ "tmux_background_agents",
7280
+ session_id=cs.session_id,
7281
+ chat_id=cs.chat_id,
7282
+ running=len(cs.background_agents),
7283
+ )
7284
+ if self._event_bus is None:
7285
+ return
7286
+ await self._event_bus.emit(
7287
+ Event(
7288
+ name=BACKGROUND_AGENTS,
7289
+ data={
7290
+ "chat_id": cs.chat_id,
7291
+ "user_id": cs.user_id,
7292
+ "session_id": cs.session_id,
7293
+ "agents": list(cs.background_agents.values()),
7294
+ },
7295
+ )
7296
+ )
7297
+
7122
7298
  async def _announce_title(self, cs: TmuxClaudeSession, obj: dict[str, Any]) -> None:
7123
7299
  title = obj.get("aiTitle")
7124
7300
  if not isinstance(title, str) or not title.strip() or title == cs.title:
@@ -7367,14 +7543,28 @@ class TmuxSessionManager:
7367
7543
  """
7368
7544
  try:
7369
7545
  payload = json.loads(Path(manifest.settings_path).read_text())
7370
- block = payload["hooks"]["PreToolUse"][0]["hooks"][0]
7546
+ gate = payload["hooks"]["PreToolUse"][0]["hooks"][0]
7547
+ lifecycle = payload["hooks"]["PostToolUse"][0]["hooks"][0]
7371
7548
  except (OSError, json.JSONDecodeError, KeyError, IndexError, TypeError):
7372
7549
  return False
7550
+ if not isinstance(gate, dict) or not isinstance(lifecycle, dict):
7551
+ return False
7552
+ if gate.get("type") == "command":
7553
+ return self._reaches_us(
7554
+ lifecycle, "PostToolUse", manifest.pane_token
7555
+ ) and gate.get("command") == self._relay_command(
7556
+ "PreToolUse", manifest.pane_token
7557
+ )
7558
+ return self._reaches_us(gate, "PreToolUse", manifest.pane_token)
7559
+
7560
+ def _reaches_us(
7561
+ self, block: dict[str, Any], event: str, pane_token: str | None
7562
+ ) -> bool:
7373
7563
  headers = block.get("headers") or {}
7374
7564
  return (
7375
- block.get("url") == self._hook_url("PreToolUse")
7565
+ block.get("url") == self._hook_url(event)
7376
7566
  and headers.get("X-Leashd-Token") == self._secret
7377
- and headers.get(_PANE_TOKEN_HEADER) == manifest.pane_token
7567
+ and headers.get(_PANE_TOKEN_HEADER) == pane_token
7378
7568
  )
7379
7569
 
7380
7570
  async def _adopt_one(self, manifest: PaneManifest) -> TmuxClaudeSession | None: