leashd 2.3.0__tar.gz → 2.5.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 (127) hide show
  1. {leashd-2.3.0 → leashd-2.5.0}/CHANGELOG.md +10 -0
  2. {leashd-2.3.0 → leashd-2.5.0}/PKG-INFO +2 -2
  3. {leashd-2.3.0 → leashd-2.5.0}/README.md +1 -1
  4. {leashd-2.3.0 → leashd-2.5.0}/leashd/__init__.py +1 -1
  5. {leashd-2.3.0 → leashd-2.5.0}/leashd/agents/runtimes/_helpers.py +24 -0
  6. {leashd-2.3.0 → leashd-2.5.0}/leashd/agents/runtimes/tmux_session.py +38 -0
  7. leashd-2.5.0/leashd/browser_launcher.py +361 -0
  8. {leashd-2.3.0 → leashd-2.5.0}/leashd/connectors/base.py +11 -6
  9. {leashd-2.3.0 → leashd-2.5.0}/leashd/connectors/multi.py +2 -1
  10. {leashd-2.3.0 → leashd-2.5.0}/leashd/connectors/telegram.py +5 -1
  11. {leashd-2.3.0 → leashd-2.5.0}/leashd/connectors/web.py +2 -1
  12. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/engine.py +17 -6
  13. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/safety/analyzer.py +187 -4
  14. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/safety/approvals.py +39 -8
  15. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/safety/audit.py +60 -18
  16. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/safety/gatekeeper.py +74 -4
  17. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/safety/policy.py +33 -3
  18. {leashd-2.3.0 → leashd-2.5.0}/leashd/policies/autonomous.yaml +2 -2
  19. {leashd-2.3.0 → leashd-2.5.0}/leashd/policies/default.yaml +2 -2
  20. {leashd-2.3.0 → leashd-2.5.0}/leashd/policies/permissive.yaml +1 -1
  21. {leashd-2.3.0 → leashd-2.5.0}/leashd/web/ws_handler.py +6 -7
  22. {leashd-2.3.0 → leashd-2.5.0}/pyproject.toml +1 -1
  23. {leashd-2.3.0 → leashd-2.5.0}/.claude/settings.json +0 -0
  24. {leashd-2.3.0 → leashd-2.5.0}/.gitignore +0 -0
  25. {leashd-2.3.0 → leashd-2.5.0}/LICENSE +0 -0
  26. {leashd-2.3.0 → leashd-2.5.0}/leashd/__main__.py +0 -0
  27. {leashd-2.3.0 → leashd-2.5.0}/leashd/agents/base.py +0 -0
  28. {leashd-2.3.0 → leashd-2.5.0}/leashd/agents/capabilities.py +0 -0
  29. {leashd-2.3.0 → leashd-2.5.0}/leashd/agents/registry.py +0 -0
  30. {leashd-2.3.0 → leashd-2.5.0}/leashd/agents/runtimes/hook_relay.py +0 -0
  31. {leashd-2.3.0 → leashd-2.5.0}/leashd/agents/runtimes/tmux.py +0 -0
  32. {leashd-2.3.0 → leashd-2.5.0}/leashd/agents/runtimes/tmux_manifest.py +0 -0
  33. {leashd-2.3.0 → leashd-2.5.0}/leashd/agents/types.py +0 -0
  34. {leashd-2.3.0 → leashd-2.5.0}/leashd/app.py +0 -0
  35. {leashd-2.3.0 → leashd-2.5.0}/leashd/browser_profile.py +0 -0
  36. {leashd-2.3.0 → leashd-2.5.0}/leashd/cc_plugins.py +0 -0
  37. {leashd-2.3.0 → leashd-2.5.0}/leashd/cli.py +0 -0
  38. {leashd-2.3.0 → leashd-2.5.0}/leashd/cli_run.py +0 -0
  39. {leashd-2.3.0 → leashd-2.5.0}/leashd/config_store.py +0 -0
  40. {leashd-2.3.0 → leashd-2.5.0}/leashd/connectors/telegram_approval.py +0 -0
  41. {leashd-2.3.0 → leashd-2.5.0}/leashd/connectors/telegram_commands.py +0 -0
  42. {leashd-2.3.0 → leashd-2.5.0}/leashd/connectors/telegram_markdown.py +0 -0
  43. {leashd-2.3.0 → leashd-2.5.0}/leashd/connectors/telegram_sessions.py +0 -0
  44. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/chat_sessions.py +0 -0
  45. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/config.py +0 -0
  46. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/events.py +0 -0
  47. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/file_delivery.py +0 -0
  48. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/interactions.py +0 -0
  49. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/message_logger.py +0 -0
  50. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/plan_gate.py +0 -0
  51. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/queue.py +0 -0
  52. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/runtime_settings.py +0 -0
  53. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/safety/approval_card.py +0 -0
  54. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/safety/sandbox.py +0 -0
  55. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/session.py +0 -0
  56. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/session_title.py +0 -0
  57. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/task.py +0 -0
  58. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/task_events.py +0 -0
  59. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/task_memory.py +0 -0
  60. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/task_profile.py +0 -0
  61. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/test_output.py +0 -0
  62. {leashd-2.3.0 → leashd-2.5.0}/leashd/core/workspace.py +0 -0
  63. {leashd-2.3.0 → leashd-2.5.0}/leashd/daemon.py +0 -0
  64. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/SKILL.md +0 -0
  65. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/references/authentication.md +0 -0
  66. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/references/commands.md +0 -0
  67. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/references/profiling.md +0 -0
  68. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/references/proxy-support.md +0 -0
  69. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/references/session-management.md +0 -0
  70. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/references/snapshot-refs.md +0 -0
  71. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/references/trust-boundaries.md +0 -0
  72. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/references/video-recording.md +0 -0
  73. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/references/webgpu.md +0 -0
  74. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/templates/authenticated-session.sh +0 -0
  75. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/templates/capture-workflow.sh +0 -0
  76. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/agent-browser/templates/form-automation.sh +0 -0
  77. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/skills/search-batch.sh +0 -0
  78. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/webui/app.js +0 -0
  79. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/webui/icons/icon-192.png +0 -0
  80. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/webui/icons/icon-512.png +0 -0
  81. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/webui/index.html +0 -0
  82. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/webui/manifest.json +0 -0
  83. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/webui/service-worker.js +0 -0
  84. {leashd-2.3.0 → leashd-2.5.0}/leashd/data/webui/style.css +0 -0
  85. {leashd-2.3.0 → leashd-2.5.0}/leashd/exceptions.py +0 -0
  86. {leashd-2.3.0 → leashd-2.5.0}/leashd/git/formatter.py +0 -0
  87. {leashd-2.3.0 → leashd-2.5.0}/leashd/git/handler.py +0 -0
  88. {leashd-2.3.0 → leashd-2.5.0}/leashd/git/models.py +0 -0
  89. {leashd-2.3.0 → leashd-2.5.0}/leashd/git/service.py +0 -0
  90. {leashd-2.3.0 → leashd-2.5.0}/leashd/main.py +0 -0
  91. {leashd-2.3.0 → leashd-2.5.0}/leashd/middleware/auth.py +0 -0
  92. {leashd-2.3.0 → leashd-2.5.0}/leashd/middleware/base.py +0 -0
  93. {leashd-2.3.0 → leashd-2.5.0}/leashd/middleware/rate_limit.py +0 -0
  94. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/base.py +0 -0
  95. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/_task_prompts.py +0 -0
  96. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/audit_plugin.py +0 -0
  97. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/browser_tools.py +0 -0
  98. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/merge_resolver.py +0 -0
  99. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/playbooks/linkedin_comment.yaml +0 -0
  100. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/task_orchestrator.py +0 -0
  101. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/test_config_loader.py +0 -0
  102. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/web_agent.py +0 -0
  103. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/web_checkpoint.py +0 -0
  104. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/web_interaction_logger.py +0 -0
  105. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/builtin/workflow.py +0 -0
  106. {leashd-2.3.0 → leashd-2.5.0}/leashd/plugins/registry.py +0 -0
  107. {leashd-2.3.0 → leashd-2.5.0}/leashd/policies/.gitkeep +0 -0
  108. {leashd-2.3.0 → leashd-2.5.0}/leashd/policies/dev-tools.yaml +0 -0
  109. {leashd-2.3.0 → leashd-2.5.0}/leashd/policies/strict.yaml +0 -0
  110. {leashd-2.3.0 → leashd-2.5.0}/leashd/setup.py +0 -0
  111. {leashd-2.3.0 → leashd-2.5.0}/leashd/skills.py +0 -0
  112. {leashd-2.3.0 → leashd-2.5.0}/leashd/storage/base.py +0 -0
  113. {leashd-2.3.0 → leashd-2.5.0}/leashd/storage/memory.py +0 -0
  114. {leashd-2.3.0 → leashd-2.5.0}/leashd/storage/sqlite.py +0 -0
  115. {leashd-2.3.0 → leashd-2.5.0}/leashd/tunnel.py +0 -0
  116. {leashd-2.3.0 → leashd-2.5.0}/leashd/web/app.py +0 -0
  117. {leashd-2.3.0 → leashd-2.5.0}/leashd/web/auth.py +0 -0
  118. {leashd-2.3.0 → leashd-2.5.0}/leashd/web/models.py +0 -0
  119. {leashd-2.3.0 → leashd-2.5.0}/leashd/web/push.py +0 -0
  120. {leashd-2.3.0 → leashd-2.5.0}/leashd/web/routes.py +0 -0
  121. {leashd-2.3.0 → leashd-2.5.0}/leashd/web/tmux_hooks.py +0 -0
  122. {leashd-2.3.0 → leashd-2.5.0}/leashd/web/tmux_jsonl.py +0 -0
  123. {leashd-2.3.0 → leashd-2.5.0}/leashd/web/tmux_server.py +0 -0
  124. {leashd-2.3.0 → leashd-2.5.0}/scripts/_harness/drive.py +0 -0
  125. {leashd-2.3.0 → leashd-2.5.0}/scripts/_harness/multisession_suite.py +0 -0
  126. {leashd-2.3.0 → leashd-2.5.0}/scripts/_harness/soak_model.py +0 -0
  127. {leashd-2.3.0 → leashd-2.5.0}/scripts/_harness/tmux_harness.py +0 -0
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.5.0] - 2026-10-22
4
+ - **added**: every audit entry about one tool call shares a `call_id`, approvals record how they ended (`outcome`) and who answered, and a new `tool_finished` entry says whether the call succeeded.
5
+ - **fixed**: on macOS, force-quitting "Google Chrome for Testing" no longer shuts leashd down; agent-browser's Chrome now starts as its own launchd job.
6
+ - **fixed**: MCP tool calls show the server and tool (`⏳ Running: leadline · edit_reply`) instead of a bare record id, and `SendMessage`, `Monitor` and `ScheduleWakeup` show their summary, description or reason.
7
+
8
+ ## [2.4.0] - 2026-10-17
9
+ - **changed**: "Approve all" now survives `/clear` and `/stop`; a directory or mode change still drops it.
10
+ - **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.
11
+ - **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`.
12
+
3
13
  ## [2.3.0] - 2026-10-10
4
14
  - **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.
5
15
  - **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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: leashd
3
- Version: 2.3.0
3
+ Version: 2.5.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
@@ -150,7 +150,7 @@ Every tool call the agent makes passes through three layers before it can execut
150
150
  | **2. Policy** | YAML rules classify each call as `allow` / `deny` / `require_approval` by tool name, command pattern, and path pattern. First match wins. Compound bash is split on `&&`, `||`, `;` and evaluated per segment, deny-wins. |
151
151
  | **3. Approval** | `require_approval` sends an inline **Approve / Reject** to the Web UI or Telegram. No response within the timeout → denied. |
152
152
 
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`.
153
+ The pipeline is connector-agnostic: same sandbox, same rules, same buttons whether you're in the browser or on your phone. Every attempt, decision and result is appended to `.leashd/audit.jsonl`, and all entries about one tool call share a `call_id`: `grep toolu_… .leashd/audit.jsonl` shows what was asked, who approved it and whether it succeeded.
154
154
 
155
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
156
 
@@ -102,7 +102,7 @@ Every tool call the agent makes passes through three layers before it can execut
102
102
  | **2. Policy** | YAML rules classify each call as `allow` / `deny` / `require_approval` by tool name, command pattern, and path pattern. First match wins. Compound bash is split on `&&`, `||`, `;` and evaluated per segment, deny-wins. |
103
103
  | **3. Approval** | `require_approval` sends an inline **Approve / Reject** to the Web UI or Telegram. No response within the timeout → denied. |
104
104
 
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`.
105
+ The pipeline is connector-agnostic: same sandbox, same rules, same buttons whether you're in the browser or on your phone. Every attempt, decision and result is appended to `.leashd/audit.jsonl`, and all entries about one tool call share a `call_id`: `grep toolu_… .leashd/audit.jsonl` shows what was asked, who approved it and whether it succeeded.
106
106
 
107
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
108
 
@@ -1,3 +1,3 @@
1
1
  """leashd — Remote AI-assisted development with safety constraints."""
2
2
 
3
- __version__ = "2.3.0"
3
+ __version__ = "2.5.0"
@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING, Any, Literal
10
10
 
11
11
  import structlog
12
12
 
13
+ from leashd.browser_launcher import browser_isolation_env
13
14
  from leashd.browser_profile import merged_launch_args
14
15
 
15
16
  if TYPE_CHECKING:
@@ -378,6 +379,9 @@ def build_agent_browser_env(config: LeashdConfig, session: Session) -> dict[str,
378
379
  agent-browser otherwise drops a path-less ``screenshot`` in the system temp
379
380
  dir, so ``/task`` visual evidence is cleaned up out from under the
380
381
  ``Visual check:`` line that references it.
382
+
383
+ On macOS Chrome is started through :mod:`leashd.browser_launcher`, so a
384
+ Force Quit of Chrome cannot take the daemon down with it.
381
385
  """
382
386
  if config.browser_backend != "agent-browser":
383
387
  return {}
@@ -388,6 +392,7 @@ def build_agent_browser_env(config: LeashdConfig, session: Session) -> dict[str,
388
392
  Path(session.working_directory) / SCREENSHOT_SAVE_DIR
389
393
  ),
390
394
  "AGENT_BROWSER_ARGS": merged_launch_args(os.environ.get("AGENT_BROWSER_ARGS")),
395
+ **browser_isolation_env(),
391
396
  }
392
397
  if not config.browser_headless:
393
398
  env["AGENT_BROWSER_HEADED"] = "1"
@@ -411,6 +416,16 @@ async def safe_callback(
411
416
  logger.warning(log_event, exc_info=True)
412
417
 
413
418
 
419
+ def _mcp_tool_label(name: str) -> str:
420
+ parts = name.split("__", 2)
421
+ if len(parts) != 3 or parts[0] != "mcp" or not parts[1] or not parts[2]:
422
+ return ""
423
+ server, tool = parts[1], parts[2]
424
+ if server == "playwright":
425
+ return ""
426
+ return f"{server} · {tool}"
427
+
428
+
414
429
  def describe_tool(name: str, tool_input: dict[str, Any]) -> str:
415
430
  """Return a brief human-readable description of a tool call."""
416
431
  if name == "Bash":
@@ -452,6 +467,15 @@ def describe_tool(name: str, tool_input: dict[str, Any]) -> str:
452
467
  subagent_type = tool_input.get("subagent_type", "")
453
468
  desc = tool_input.get("description", "")
454
469
  return f"{subagent_type}: {desc}" if subagent_type else desc
470
+ if name == "SendMessage":
471
+ return truncate(str(tool_input.get("summary") or tool_input.get("to") or ""))
472
+ if name == "Monitor" and tool_input.get("description"):
473
+ return truncate(str(tool_input["description"]))
474
+ if name == "ScheduleWakeup" and tool_input.get("reason"):
475
+ return truncate(str(tool_input["reason"]))
476
+ mcp_label = _mcp_tool_label(name)
477
+ if mcp_label:
478
+ return mcp_label
455
479
  for v in tool_input.values():
456
480
  if isinstance(v, str) and v:
457
481
  return truncate(v)
@@ -84,6 +84,7 @@ _MIN_TMUX = (3, 3)
84
84
  _ASYNC_HOOK_EVENTS = (
85
85
  "UserPromptSubmit",
86
86
  "PostToolUse",
87
+ "PostToolUseFailure",
87
88
  "Stop",
88
89
  "StopFailure",
89
90
  "SubagentStop",
@@ -4419,6 +4420,13 @@ class TmuxClaudeSession:
4419
4420
  del self.hooked_calls[oldest]
4420
4421
  self._hooked_at.pop(oldest, None)
4421
4422
 
4423
+ def hooked_call_id(self, tool_name: str, tool_input: dict[str, Any]) -> str | None:
4424
+ identity = _tool_identity_key("", tool_name, tool_input)
4425
+ for key, call in reversed(self.hooked_calls.items()):
4426
+ if key != identity and call == (tool_name, tool_input):
4427
+ return key
4428
+ return None
4429
+
4422
4430
  def ran_without_the_gate(self, tool_use_id: str) -> bool:
4423
4431
  """Did a finished call never come through this session's ``PreToolUse``?
4424
4432
 
@@ -6015,6 +6023,7 @@ class TmuxSessionManager:
6015
6023
  ) -> dict[str, Any]:
6016
6024
  claude_uuid = str(body.get("session_id", ""))
6017
6025
  tool_name = str(body.get("tool_name", ""))
6026
+ tool_use_id = str(body.get("tool_use_id") or "")
6018
6027
  tool_input = body.get("tool_input") or {}
6019
6028
  if not isinstance(tool_input, dict):
6020
6029
  tool_input = {}
@@ -6085,6 +6094,7 @@ class TmuxSessionManager:
6085
6094
  session_mode=cs.mode,
6086
6095
  task_run_id=cs.task_run_id,
6087
6096
  native_ask_rules=cs.native_ask_rules,
6097
+ call_id=tool_use_id or None,
6088
6098
  )
6089
6099
  if gated is None:
6090
6100
  return _hook_passthrough()
@@ -6108,6 +6118,7 @@ class TmuxSessionManager:
6108
6118
  cs.chat_id,
6109
6119
  session_mode=cs.mode,
6110
6120
  task_run_id=cs.task_run_id,
6121
+ call_id=tool_use_id or None,
6111
6122
  )
6112
6123
  return _permission_to_hook(result)
6113
6124
 
@@ -6139,6 +6150,21 @@ class TmuxSessionManager:
6139
6150
  # model and the pane hung.)
6140
6151
  return _permission_to_hook(decision)
6141
6152
 
6153
+ def _record_tool_finished(
6154
+ self, cs: TmuxClaudeSession, body: dict[str, Any], *, succeeded: bool
6155
+ ) -> None:
6156
+ tool_use_id = str(body.get("tool_use_id") or "")
6157
+ if self._audit is None or not tool_use_id:
6158
+ return
6159
+ error = body.get("error")
6160
+ self._audit.log_tool_finished(
6161
+ cs.session_id,
6162
+ str(body.get("tool_name", "")),
6163
+ tool_use_id,
6164
+ succeeded=succeeded,
6165
+ error=error if isinstance(error, str) else None,
6166
+ )
6167
+
6142
6168
  def _record_ungated_call(self, cs: TmuxClaudeSession, body: dict[str, Any]) -> None:
6143
6169
  """Put a call that ran without leashd's verdict on the audit trail.
6144
6170
 
@@ -6354,6 +6380,7 @@ class TmuxSessionManager:
6354
6380
  cs.chat_id,
6355
6381
  session_mode=cs.mode,
6356
6382
  task_run_id=cs.task_run_id,
6383
+ call_id=cs.hooked_call_id(tool_name, tool_input),
6357
6384
  )
6358
6385
  hook_out = _permission_to_hook(result)
6359
6386
  self._note_tool_decision(cs, tool_name, tool_input, hook_out)
@@ -6529,6 +6556,8 @@ class TmuxSessionManager:
6529
6556
  cs.chat_id,
6530
6557
  session_mode=cs.mode,
6531
6558
  task_run_id=cs.task_run_id,
6559
+ call_id=str(body.get("tool_use_id") or "")
6560
+ or cs.hooked_call_id(tool_name, tool_input),
6532
6561
  )
6533
6562
  hook_out = _permission_to_hook(result)
6534
6563
  swapped = _deny_without_ending_the_turn(tool_name, tool_input, hook_out)
@@ -6622,12 +6651,21 @@ class TmuxSessionManager:
6622
6651
  if event == "PostToolUse":
6623
6652
  tool_input = body.get("tool_input")
6624
6653
  self._record_ungated_call(cs, body)
6654
+ self._record_tool_finished(cs, body, succeeded=True)
6625
6655
  cs.forget_hooked_call(
6626
6656
  str(body.get("tool_use_id") or ""),
6627
6657
  str(body.get("tool_name", "")),
6628
6658
  tool_input if isinstance(tool_input, dict) else None,
6629
6659
  )
6630
6660
  await self._expire_executed_gate(cs, body)
6661
+ elif event == "PostToolUseFailure":
6662
+ tool_input = body.get("tool_input")
6663
+ self._record_tool_finished(cs, body, succeeded=False)
6664
+ cs.forget_hooked_call(
6665
+ str(body.get("tool_use_id") or ""),
6666
+ str(body.get("tool_name", "")),
6667
+ tool_input if isinstance(tool_input, dict) else None,
6668
+ )
6631
6669
  elif event == "Stop":
6632
6670
  turn = cs.turn
6633
6671
  if turn is not None and turn.end_response(from_transcript=False):
@@ -0,0 +1,361 @@
1
+ """Launch agent-browser's Chrome in its own macOS coalition.
2
+
3
+ macOS groups every process spawned under an app into that app's coalition,
4
+ and a Force Quit (Dock menu or the Cmd+Opt+Esc panel) signals the whole
5
+ coalition. agent-browser runs inside a leashd tmux pane, so the Chrome it
6
+ spawns shares the daemon's coalition, and force-quitting "Google Chrome for
7
+ Testing" also killed the daemon, tmux and every claude pane.
8
+
9
+ agent-browser runs this module as its browser executable. ``launch`` starts the
10
+ real Chrome as a one-off launchd job, which gets a coalition of its own, and
11
+ stays in place of Chrome for agent-browser: Chrome's output is relayed back,
12
+ and the two lifetimes are tied over a Unix socket so Chrome exits when the
13
+ launcher is stopped, killed or loses its parent.
14
+
15
+ Stdlib only, since it runs on every browser launch.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import contextlib
21
+ import os
22
+ import plistlib
23
+ import re
24
+ import select
25
+ import shlex
26
+ import shutil
27
+ import signal
28
+ import socket
29
+ import subprocess
30
+ import sys
31
+ import tempfile
32
+ import threading
33
+ from pathlib import Path
34
+ from typing import TYPE_CHECKING
35
+
36
+ if TYPE_CHECKING:
37
+ from collections.abc import Mapping, Sequence
38
+
39
+ EXECUTABLE_PATH_ENV = "AGENT_BROWSER_EXECUTABLE_PATH"
40
+ REAL_EXECUTABLE_ENV = "LEASHD_BROWSER_EXECUTABLE"
41
+ LAUNCHER_DIR_ENV = "LEASHD_BROWSER_LAUNCHER_DIR"
42
+ LAUNCHER_NAME = "browser-launcher"
43
+ JOB_LABEL_PREFIX = "com.leashd.browser"
44
+
45
+ _CHROME_FOR_TESTING = Path(
46
+ "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
47
+ )
48
+ _CONNECT_TIMEOUT_SECONDS = 15.0
49
+ _STOP_GRACE_SECONDS = 5.0
50
+ _JOB_EXIT_TIMEOUT_SECONDS = 10
51
+ _RELAY_CHUNK = 65536
52
+ _LAUNCHCTL = "/bin/launchctl"
53
+
54
+
55
+ class _StopSignalError(Exception):
56
+ def __init__(self, signum: int) -> None:
57
+ super().__init__(signum)
58
+ self.signum = signum
59
+
60
+
61
+ def launcher_path(environ: Mapping[str, str] | None = None) -> Path:
62
+ environ = os.environ if environ is None else environ
63
+ override = environ.get(LAUNCHER_DIR_ENV)
64
+ base = Path(override) if override else Path.home() / ".leashd" / "bin"
65
+ return base / LAUNCHER_NAME
66
+
67
+
68
+ def launcher_script() -> str:
69
+ return (
70
+ "#!/bin/sh\n"
71
+ f'exec {shlex.quote(sys.executable)} -I -m leashd.browser_launcher launch "$@"\n'
72
+ )
73
+
74
+
75
+ def install_launcher(path: Path) -> Path:
76
+ content = launcher_script()
77
+ with contextlib.suppress(OSError):
78
+ if path.read_text(encoding="utf-8") == content and os.access(path, os.X_OK):
79
+ return path
80
+ path.parent.mkdir(parents=True, exist_ok=True)
81
+ staging = path.with_name(f".{path.name}.{os.getpid()}")
82
+ staging.write_text(content, encoding="utf-8")
83
+ staging.chmod(0o755)
84
+ staging.replace(path)
85
+ return path
86
+
87
+
88
+ def _version_key(browser_dir: Path) -> tuple[int, ...]:
89
+ return tuple(int(part) for part in re.findall(r"\d+", browser_dir.name))
90
+
91
+
92
+ def _is_executable(path: Path) -> bool:
93
+ return path.is_file() and os.access(path, os.X_OK)
94
+
95
+
96
+ def resolve_browser_executable(
97
+ environ: Mapping[str, str] | None = None, home: Path | None = None
98
+ ) -> Path | None:
99
+ """The Chrome agent-browser would launch: the user's pick, else its newest install."""
100
+ environ = os.environ if environ is None else environ
101
+ override = environ.get(REAL_EXECUTABLE_ENV)
102
+ if override:
103
+ candidate = Path(override).expanduser()
104
+ return candidate if _is_executable(candidate) else None
105
+ browsers = (home or Path.home()) / ".agent-browser" / "browsers"
106
+ if not browsers.is_dir():
107
+ return None
108
+ for browser_dir in sorted(
109
+ browsers.glob("chrome-*"), key=_version_key, reverse=True
110
+ ):
111
+ candidate = browser_dir / _CHROME_FOR_TESTING
112
+ if _is_executable(candidate):
113
+ return candidate
114
+ return None
115
+
116
+
117
+ def browser_isolation_env(
118
+ environ: Mapping[str, str] | None = None,
119
+ *,
120
+ platform: str | None = None,
121
+ home: Path | None = None,
122
+ ) -> dict[str, str]:
123
+ """Env that routes agent-browser's Chrome through the launcher.
124
+
125
+ Empty off macOS, where coalitions don't exist, and when no Chrome is found,
126
+ so agent-browser keeps its own discovery and install hint. A user-set
127
+ ``AGENT_BROWSER_EXECUTABLE_PATH`` becomes the browser the launcher starts.
128
+ """
129
+ if (platform or sys.platform) != "darwin":
130
+ return {}
131
+ environ = os.environ if environ is None else environ
132
+ launcher = launcher_path(environ)
133
+ env: dict[str, str] = {}
134
+ configured = environ.get(EXECUTABLE_PATH_ENV)
135
+ if configured and Path(configured).expanduser() != launcher:
136
+ env[REAL_EXECUTABLE_ENV] = configured
137
+ elif environ.get(REAL_EXECUTABLE_ENV):
138
+ env[REAL_EXECUTABLE_ENV] = environ[REAL_EXECUTABLE_ENV]
139
+ if resolve_browser_executable({**environ, **env}, home) is None:
140
+ return {}
141
+ install_launcher(launcher)
142
+ env[EXECUTABLE_PATH_ENV] = str(launcher)
143
+ return env
144
+
145
+
146
+ def job_plist(
147
+ label: str,
148
+ program_arguments: Sequence[str],
149
+ environment: Mapping[str, str],
150
+ working_directory: str,
151
+ ) -> bytes:
152
+ return plistlib.dumps(
153
+ {
154
+ "Label": label,
155
+ "ProgramArguments": list(program_arguments),
156
+ "EnvironmentVariables": dict(environment),
157
+ "WorkingDirectory": working_directory,
158
+ "RunAtLoad": True,
159
+ "KeepAlive": False,
160
+ "ProcessType": "Interactive",
161
+ "ExitTimeOut": _JOB_EXIT_TIMEOUT_SECONDS,
162
+ }
163
+ )
164
+
165
+
166
+ def _gui_domain() -> str:
167
+ return f"gui/{os.getuid()}"
168
+
169
+
170
+ def _launchctl(*args: str) -> bool:
171
+ try:
172
+ result = subprocess.run( # noqa: S603
173
+ [_LAUNCHCTL, *args],
174
+ stdin=subprocess.DEVNULL,
175
+ stdout=subprocess.DEVNULL,
176
+ stderr=subprocess.DEVNULL,
177
+ check=False,
178
+ )
179
+ except OSError:
180
+ return False
181
+ return result.returncode == 0
182
+
183
+
184
+ def bootstrap_job(plist_path: Path) -> bool:
185
+ return _launchctl("bootstrap", _gui_domain(), str(plist_path))
186
+
187
+
188
+ def bootout_job(label: str) -> bool:
189
+ return _launchctl("bootout", f"{_gui_domain()}/{label}")
190
+
191
+
192
+ def _exit_code(status_path: Path) -> int:
193
+ try:
194
+ code = int(status_path.read_text(encoding="utf-8").strip())
195
+ except (OSError, ValueError):
196
+ return 1
197
+ return 128 - code if code < 0 else code
198
+
199
+
200
+ def _raise_stopped(signum: int, _frame: object) -> None:
201
+ raise _StopSignalError(signum)
202
+
203
+
204
+ def relay(conn: socket.socket, parent_pid: int) -> bool:
205
+ """Copy Chrome's output to stderr until it exits; False if the parent died first."""
206
+ queue = select.kqueue()
207
+ try:
208
+ events = [select.kevent(conn.fileno(), select.KQ_FILTER_READ, select.KQ_EV_ADD)]
209
+ if parent_pid > 1:
210
+ events.append(
211
+ select.kevent(
212
+ parent_pid,
213
+ select.KQ_FILTER_PROC,
214
+ select.KQ_EV_ADD | select.KQ_EV_ONESHOT,
215
+ select.KQ_NOTE_EXIT,
216
+ )
217
+ )
218
+ try:
219
+ queue.control(events, 0)
220
+ except ProcessLookupError:
221
+ return False
222
+ while True:
223
+ for event in queue.control(None, 2):
224
+ if event.filter == select.KQ_FILTER_PROC:
225
+ return False
226
+ data = conn.recv(_RELAY_CHUNK)
227
+ if not data:
228
+ return True
229
+ with contextlib.suppress(OSError):
230
+ sys.stderr.buffer.write(data)
231
+ sys.stderr.buffer.flush()
232
+ finally:
233
+ queue.close()
234
+
235
+
236
+ def _exec_directly(browser: Path, args: Sequence[str]) -> int:
237
+ os.execv(browser, [str(browser), *args]) # noqa: S606
238
+ return 127
239
+
240
+
241
+ def launch(args: Sequence[str]) -> int:
242
+ browser = resolve_browser_executable()
243
+ if browser is None:
244
+ print("leashd browser-launcher: no Chrome executable found", file=sys.stderr)
245
+ return 127
246
+ if sys.platform != "darwin":
247
+ return _exec_directly(browser, args)
248
+
249
+ parent_pid = os.getppid()
250
+ label = f"{JOB_LABEL_PREFIX}.{os.getpid()}"
251
+ workdir = Path(tempfile.mkdtemp(prefix="leashd-browser-"))
252
+ sock_path = workdir / "s"
253
+ status_path = workdir / "status"
254
+ plist_path = workdir / "job.plist"
255
+ server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
256
+ started = False
257
+ try:
258
+ server.bind(str(sock_path))
259
+ server.listen(1)
260
+ server.settimeout(_CONNECT_TIMEOUT_SECONDS)
261
+ plist_path.write_bytes(
262
+ job_plist(
263
+ label,
264
+ [
265
+ sys.executable,
266
+ "-I",
267
+ "-m",
268
+ "leashd.browser_launcher",
269
+ "supervise",
270
+ str(sock_path),
271
+ str(status_path),
272
+ label,
273
+ str(browser),
274
+ *args,
275
+ ],
276
+ os.environ,
277
+ os.getcwd(),
278
+ )
279
+ )
280
+ started = bootstrap_job(plist_path)
281
+ if not started:
282
+ raise OSError("launchctl bootstrap failed")
283
+ conn, _ = server.accept()
284
+ except OSError:
285
+ server.close()
286
+ if started:
287
+ bootout_job(label)
288
+ shutil.rmtree(workdir, ignore_errors=True)
289
+ return _exec_directly(browser, args)
290
+
291
+ server.close()
292
+ for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
293
+ signal.signal(signum, _raise_stopped)
294
+ try:
295
+ if relay(conn, parent_pid):
296
+ return _exit_code(status_path)
297
+ return 1
298
+ except _StopSignalError as stop:
299
+ return 128 + stop.signum
300
+ finally:
301
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
302
+ conn.close()
303
+ bootout_job(label)
304
+ shutil.rmtree(workdir, ignore_errors=True)
305
+
306
+
307
+ def _stop_browser(proc: subprocess.Popen[bytes]) -> None:
308
+ if proc.poll() is not None:
309
+ return
310
+ with contextlib.suppress(ProcessLookupError):
311
+ proc.terminate()
312
+ killer = threading.Timer(_STOP_GRACE_SECONDS, proc.kill)
313
+ killer.daemon = True
314
+ killer.start()
315
+
316
+
317
+ def supervise(args: Sequence[str]) -> int:
318
+ sock_path, status_path, label, browser, *browser_args = args
319
+ conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
320
+ conn.connect(sock_path)
321
+ proc = subprocess.Popen( # noqa: S603
322
+ [browser, *browser_args],
323
+ stdin=subprocess.DEVNULL,
324
+ stdout=conn.fileno(),
325
+ stderr=conn.fileno(),
326
+ )
327
+ launcher_gone = threading.Event()
328
+
329
+ def watch_launcher() -> None:
330
+ with contextlib.suppress(OSError):
331
+ while conn.recv(_RELAY_CHUNK):
332
+ pass
333
+ launcher_gone.set()
334
+ _stop_browser(proc)
335
+
336
+ signal.signal(signal.SIGTERM, lambda *_: _stop_browser(proc))
337
+ threading.Thread(target=watch_launcher, daemon=True).start()
338
+ code = proc.wait()
339
+ with contextlib.suppress(OSError):
340
+ Path(status_path).write_text(str(code), encoding="utf-8")
341
+ conn.close()
342
+ if launcher_gone.is_set():
343
+ bootout_job(label)
344
+ return code
345
+
346
+
347
+ def main(argv: Sequence[str] | None = None) -> int:
348
+ argv = list(sys.argv[1:] if argv is None else argv)
349
+ if argv and argv[0] == "launch":
350
+ return launch(argv[1:])
351
+ if argv and argv[0] == "supervise" and len(argv) >= 5:
352
+ return supervise(argv[1:])
353
+ print(
354
+ "usage: python -m leashd.browser_launcher launch <chrome args...>",
355
+ file=sys.stderr,
356
+ )
357
+ return 2
358
+
359
+
360
+ if __name__ == "__main__":
361
+ sys.exit(main())
@@ -2,12 +2,19 @@
2
2
 
3
3
  from abc import ABC, abstractmethod
4
4
  from collections.abc import Callable, Coroutine
5
- from typing import Any
5
+ from typing import Any, Protocol
6
6
 
7
7
  from pydantic import BaseModel, ConfigDict, field_validator
8
8
 
9
9
  from leashd.core.chat_sessions import index_of, slot_label
10
10
 
11
+
12
+ class ApprovalResolver(Protocol):
13
+ def __call__(
14
+ self, approval_id: str, approved: bool, approver_id: str | None = None
15
+ ) -> Coroutine[Any, Any, bool]: ...
16
+
17
+
11
18
  ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024 # 10 MB per file
12
19
  ATTACHMENT_MAX_COUNT = 5
13
20
  ATTACHMENT_SUPPORTED_TYPES = frozenset(
@@ -91,9 +98,7 @@ CommandHandler = Callable[
91
98
  class BaseConnector(ABC):
92
99
  def __init__(self) -> None:
93
100
  self._message_handler: MessageHandler | None = None
94
- self._approval_resolver: (
95
- Callable[[str, bool], Coroutine[Any, Any, bool]] | None
96
- ) = None
101
+ self._approval_resolver: ApprovalResolver | None = None
97
102
  self._interaction_resolver: (
98
103
  Callable[[str, str], Coroutine[Any, Any, bool]] | None
99
104
  ) = None
@@ -227,9 +232,9 @@ class BaseConnector(ABC):
227
232
 
228
233
  def set_approval_resolver(
229
234
  self,
230
- resolver: Callable[[str, bool], Coroutine[Any, Any, bool]],
235
+ resolver: ApprovalResolver,
231
236
  ) -> None:
232
- """Register resolver(approval_id, approved) for approval callbacks."""
237
+ """Register resolver(approval_id, approved, approver_id) for approval callbacks."""
233
238
  self._approval_resolver = resolver
234
239
 
235
240
  def set_interaction_resolver(
@@ -10,6 +10,7 @@ import structlog
10
10
 
11
11
  from leashd.connectors.base import (
12
12
  ApprovalCard,
13
+ ApprovalResolver,
13
14
  BaseConnector,
14
15
  CommandHandler,
15
16
  InlineButton,
@@ -222,7 +223,7 @@ class MultiConnector(BaseConnector):
222
223
 
223
224
  def set_approval_resolver(
224
225
  self,
225
- resolver: Callable[[str, bool], Coroutine[Any, Any, bool]],
226
+ resolver: ApprovalResolver,
226
227
  ) -> None:
227
228
  super().set_approval_resolver(resolver)
228
229
  for c in self._connectors:
@@ -1814,7 +1814,11 @@ class TelegramConnector(BaseConnector):
1814
1814
  resolved = False
1815
1815
  if self._approval_resolver:
1816
1816
  try:
1817
- resolved = await self._approval_resolver(approval_id, approved)
1817
+ resolved = await self._approval_resolver(
1818
+ approval_id,
1819
+ approved,
1820
+ approver_id=str(query.from_user.id) if query.from_user else None,
1821
+ )
1818
1822
  except Exception:
1819
1823
  logger.exception(
1820
1824
  "telegram_approval_resolver_error",
@@ -13,6 +13,7 @@ from urllib.parse import quote
13
13
  import structlog
14
14
 
15
15
  from leashd.connectors.base import (
16
+ ApprovalResolver,
16
17
  BaseConnector,
17
18
  CommandHandler,
18
19
  InlineButton,
@@ -527,7 +528,7 @@ class WebConnector(BaseConnector):
527
528
 
528
529
  def set_approval_resolver(
529
530
  self,
530
- resolver: Callable[[str, bool], Coroutine[Any, Any, bool]],
531
+ resolver: ApprovalResolver,
531
532
  ) -> None:
532
533
  super().set_approval_resolver(resolver)
533
534
  self._ws_handler.set_approval_resolver(resolver)