SaylorTwift HF Staff commited on
Commit
2969d1e
·
verified ·
1 Parent(s): e9c4f85

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tools/AGENTS.md +108 -0
  2. tools/apply_layout_tool.py +60 -0
  3. tools/approval_detection.py +1456 -0
  4. tools/approval_human_wait.py +169 -0
  5. tools/async_delegation.py +1003 -0
  6. tools/bot_mode_dm.py +663 -0
  7. tools/browser_camofox.py +601 -0
  8. tools/browser_dialog_tool.py +132 -0
  9. tools/browser_extension_router.py +137 -0
  10. tools/browser_supervisor.py +562 -0
  11. tools/browser_supervisor_dialogs.py +307 -0
  12. tools/browser_tool_eval_policy.py +167 -0
  13. tools/browser_tool_lightpanda_fallback.py +195 -0
  14. tools/browser_tool_origin.py +87 -0
  15. tools/browser_tool_session.py +614 -0
  16. tools/browser_tool_snapshot.py +125 -0
  17. tools/browser_tool_vision.py +143 -0
  18. tools/browser_use_cli.py +793 -0
  19. tools/clarify_gateway.py +308 -0
  20. tools/clarify_tool.py +311 -0
  21. tools/close_preview_tool.py +64 -0
  22. tools/code_execution_rpc.py +183 -0
  23. tools/cronjob_job_args.py +420 -0
  24. tools/daemon_pool.py +56 -0
  25. tools/delegate_tool_progress.py +392 -0
  26. tools/delegate_tool_tasks.py +162 -0
  27. tools/delegation_live_log.py +315 -0
  28. tools/delegation_output_schema.py +116 -0
  29. tools/desktop_ui.py +70 -0
  30. tools/env_probe.py +255 -0
  31. tools/feishu_doc_tool.py +95 -0
  32. tools/file_operations_common.py +279 -0
  33. tools/file_operations_lint.py +295 -0
  34. tools/file_operations_search.py +938 -0
  35. tools/file_state.py +248 -0
  36. tools/file_tools_read_tracking.py +263 -0
  37. tools/focus_pane_tool.py +76 -0
  38. tools/homeassistant_tool.py +335 -0
  39. tools/hook_output_spill.py +117 -0
  40. tools/image_generation_tool.py +877 -0
  41. tools/image_source.py +314 -0
  42. tools/interpreter_shutdown.py +25 -0
  43. tools/interrupt.py +121 -0
  44. tools/kanban_tools_schemas.py +533 -0
  45. tools/kanban_toolset_context.py +28 -0
  46. tools/lazy_deps.py +752 -0
  47. tools/mcp_oauth.py +1194 -0
  48. tools/mcp_oauth_device.py +198 -0
  49. tools/mcp_oauth_provider.py +427 -0
  50. tools/mcp_schema_cache.py +126 -0
tools/AGENTS.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # tools/ + toolsets.py + model_tools.py — model tools
2
+
3
+ Applies on top of the root `AGENTS.md`: settle the **Footprint Ladder** before adding anything here.
4
+ Most capabilities should NOT be core tools. Long-form: `website/docs/developer-guide/adding-tools.md`,
5
+ `tools-runtime.md`.
6
+
7
+ ## Registry and discovery
8
+
9
+ `tools/registry.py` has no deps and is imported by every tool file; each `tools/*.py` calls
10
+ `registry.register()` at import time; `model_tools.py` imports the registry and triggers discovery
11
+ (`discover_builtin_tools()`), then `run_agent.py`, `cli.py`, `batch_runner.py`, `environments/`
12
+ consume it. Any `tools/*.py` with a top-level `registry.register()` is imported automatically — no
13
+ manual import list. A tool that is a whole package (`tools/connectors/`) registers from
14
+ `tools/<pkg>/tool.py`, the only file discovery scans inside a package; every sibling in the package
15
+ is a library by construction, and the package needs an `__init__.py` or discovery skips it with a
16
+ warning (setuptools would drop it from the wheel). The registry handles schema collection, dispatch (`handle_function_call()`),
17
+ availability (`check_fn`, TTL-cached process-wide), and error wrapping. **All handlers return a JSON
18
+ string.**
19
+
20
+ ## Adding a core tool (2 files) — only when the user is explicitly contributing a core tool
21
+
22
+ For custom/local-only tools do NOT edit core: create `~/.hermes/plugins/<name>/plugin.yaml` +
23
+ `__init__.py` and call `ctx.register_tool(...)`; plugin toolsets are discovered automatically and
24
+ toggled without touching `tools/` or `toolsets.py` (`plugins/AGENTS.md`).
25
+
26
+ 1. `tools/your_tool.py`:
27
+ ```python
28
+ from tools.registry import registry
29
+ def check_requirements() -> bool: return bool(os.getenv("EXAMPLE_API_KEY"))
30
+ def example_tool(param: str, task_id: str = None) -> str: return json.dumps({"success": True, ...})
31
+ registry.register(name="example_tool", toolset="example",
32
+ schema={"name": "example_tool", "description": "...", "parameters": {...}},
33
+ handler=lambda args, **kw: example_tool(param=args.get("param", ""), task_id=kw.get("task_id")),
34
+ check_fn=check_requirements, requires_env=["EXAMPLE_API_KEY"])
35
+ ```
36
+ 2. `toolsets.py`: add the name to `_HERMES_CORE_TOOLS` (all platforms) or a new toolset. **Required**
37
+ — discovery registers the schema, but a tool is only exposed if a toolset names it.
38
+ `_HERMES_CORE_TOOLS` is the default bundle every platform's base toolset inherits, not dead code.
39
+
40
+ Rules for tool code:
41
+ - **Schema descriptions must not name tools from other toolsets** (`browser_navigate` saying "prefer
42
+ web_search"). Those tools may be unavailable (missing key, disabled toolset) and the model
43
+ hallucinates calls to them. Cross-references are added dynamically in `get_tool_definitions()` in
44
+ `model_tools.py` — see the `browser_navigate` / `execute_code` post-processing blocks.
45
+ - **Paths in schema descriptions use `display_hermes_home()`** (schema is built at import, after
46
+ `_apply_profile_override()` set `HERMES_HOME`). **State files use `get_hermes_home()`**, never
47
+ `Path.home()/.hermes`, so each profile gets its own state.
48
+ - **No `offset`/`limit` on instructional tools** (skills, prompts, playbooks) — models read page 1
49
+ and skip the rest (root rubric).
50
+ - **`check_fn` answers reachability/opt-in, never surface.** It is TTL-cached process-wide, and one
51
+ process serves many sessions; GUI-only tools go in a named toolset (`desktop_ui`, `project`)
52
+ folded in by `_load_enabled_toolsets(platform)` (root: capability is a property of the SESSION).
53
+ - **Agent-level tools** (`todo`, `memory`) are intercepted before `handle_function_call()` via the
54
+ `INLINE_TOOL_EXECUTORS` table (`agent/inline_tool_executors.py`; `agent/AGENTS.md`).
55
+ - **`_last_resolved_tool_names`** is a process-global in `model_tools.py`; `_run_single_child()` in
56
+ `delegate_tool.py` saves/restores it around child runs — readers may see it stale mid-delegation.
57
+ - New tools integrate with existing setup UX (`hermes tools`, `hermes setup`, auto-install) rather
58
+ than a raw env var; secrets go in `OPTIONAL_ENV_VARS` (`hermes_cli/AGENTS.md`).
59
+
60
+ ## Toolsets (`toolsets.py`)
61
+
62
+ Single `TOOLSETS` dict. Keys today: `browser, clarify, code_execution, cronjob, debugging,
63
+ delegation, discord, discord_admin, feishu_doc, feishu_drive, file, homeassistant, image_gen,
64
+ kanban, memory, messaging, moa, rl, safe, search, session_search, skills, spotify, terminal, todo,
65
+ tts, video, vision, web, yuanbao` (don't assert the list in tests). Per-platform enable/disable via
66
+ `hermes tools` (curses) or `tools.<platform>.enabled/disabled` in config.yaml. `browser_exec`
67
+ replaces the other browser tools when `browser.backend` is `browser-use`.
68
+
69
+ ## Backends and providers inside tools/
70
+
71
+ Several tools front pluggable backends: terminal environments in `tools/environments/` (local,
72
+ docker, ssh, modal, daytona, singularity; `terminal_tool_backends.py`, `tool_backend_helpers.py`),
73
+ browser (`browser_tool_*.py`: cdp, cloud, install, lifecycle, session, real_profile, vision), MCP
74
+ client (`mcp_tool_*.py`: config, discovery, transport, registration, content, errors), TTS
75
+ (`tts_tool_providers.py`, `tts_command_provider.py`), skills hub sources (`skills_hub_official.py`
76
+ `OptionalSkillSource`). Adding a backend = a new sibling or provider entry in the existing table,
77
+ never an `elif` on a backend name (root shape rules). Remote-backend file visibility problems are
78
+ fixed at the mount, not by adding a tool.
79
+
80
+ ## Delegation (`tools/delegate_tool.py`)
81
+
82
+ Spawns a subagent with isolated context + terminal session; the parent waits for the summary unless
83
+ `background=true`, which returns a delegation id and re-enters the result via the async-delegation
84
+ completion queue. Shapes: single (`goal` + optional `context`, `toolsets`) or batch (`tasks: [...]`,
85
+ concurrency capped by `delegation.max_concurrent_children`, default 3). A background batch returns as ONE
86
+ completion by default; with `delegation.independent_completions` it is split into completion **units**
87
+ (`delegate_tool_dispatch._units_of`): tasks sharing a `group` join and report together; each ungrouped
88
+ task reports alone as it finishes. Units of one call share ONE pool slot (`slot_key` in
89
+ `async_delegation._dispatch`) — never count units against capacity; the executor is sized by live UNITS
90
+ and the stall clock arms when the runner starts, so a queued unit is never judged stalled. Roles: `leaf` (default;
91
+ no `delegate_task`, `clarify`, `memory`, `send_message`, `cronjob`; keeps `execute_code`) and
92
+ `orchestrator` (keeps `delegate_task`; gated by `delegation.orchestrator_enabled`, bounded by
93
+ `delegation.max_spawn_depth`, default 2). Config knobs under `delegation:`:
94
+ `max_concurrent_children, independent_completions, max_spawn_depth, child_timeout_seconds, orchestrator_enabled,
95
+ subagent_auto_approve, inherit_mcp_toolsets, max_iterations`. **Child processes:** a child's background
96
+ processes are killed at its teardown and their notices are suppressed in the parent; `process_manage(action="handoff")`
97
+ (children only) flips `ProcessSession.owner_task_id` to the parent under the registry lock
98
+ (`process_registry.transfer_ownership`) so the completion routes and reaps by the new owner; un-handed leftovers land on
99
+ the result as `orphaned_processes`, exited-but-never-read notify processes as `unread_completions` (`_ChildRun.account_background_processes`, before `cleanup` kills them). **Durability:** background
100
+ delegation is process-local; work that must survive restart uses `cronjob` or
101
+ `terminal(background=True, notify_on_complete=True)`. API: `website/docs/developer-guide/subagent-lifecycle-api.md`.
102
+
103
+ ## Tests
104
+
105
+ `tests/tools/`. Test the handler through the registry (real dispatch), not the bare function only;
106
+ assert contracts ("every registered tool has a toolset", "no schema description names a tool from
107
+ another toolset") rather than tool counts. Approval/security-boundary tools are E2E'd with real
108
+ imports against a temp `HERMES_HOME` (see `tests/tools/test_approval_config_readonly.py`).
tools/apply_layout_tool.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Apply a layout preset in the Hermes desktop GUI (``layout.apply`` via ``desktop_ui``).
2
+
3
+ The renderer resolves the id against its layouts registry (core, plugin and user
4
+ presets are one list); only the active window's session acts, so a background turn
5
+ never rearranges the desktop. Preset ids are free-form on purpose. The renderer
6
+ answers with the applied id/title, or the available ids when unknown, so the model
7
+ can self-correct without a registry-listing tool.
8
+ """
9
+
10
+ from tools import desktop_ui
11
+ from tools.registry import registry, tool_error
12
+
13
+
14
+ def apply_layout_tool(preset: str) -> str:
15
+ """Ask the desktop GUI to apply layout preset ``preset``."""
16
+ name = (preset or "").strip()
17
+ if not name:
18
+ return tool_error("preset is required — a layout preset id, e.g. 'default' or 'focus'.")
19
+ return desktop_ui.emit_or_error(
20
+ "layout.apply", {"preset": name}, f"Failed to apply layout '{name}': ",
21
+ "Layout apply is only available in the Hermes desktop app.", {"success": True, "preset": name},
22
+ )
23
+
24
+
25
+ APPLY_LAYOUT_SCHEMA = {
26
+ "name": "apply_layout",
27
+ "description": (
28
+ "Apply a saved layout preset to the Hermes desktop app when the user "
29
+ "asks to rearrange the workspace. Built-ins: default (chat + "
30
+ "sidebars), focus (chat only), terminal-deck, quad; plugin/user "
31
+ "presets by id. To reveal ONE pane, use focus_pane instead."
32
+ ),
33
+ "parameters": {
34
+ "type": "object",
35
+ "properties": {
36
+ "preset": {
37
+ "type": "string",
38
+ "description": "Layout preset id to apply (e.g. 'default', 'focus', 'terminal-deck', 'quad', or a user/plugin preset id).",
39
+ },
40
+ },
41
+ "required": ["preset"],
42
+ },
43
+ }
44
+
45
+
46
+ registry.register(
47
+ name="apply_layout",
48
+ toolset="desktop_ui",
49
+ schema=APPLY_LAYOUT_SCHEMA,
50
+ handler=lambda args, **kw: apply_layout_tool(preset=args.get("preset", "")),
51
+ emoji="🧱",
52
+ )
53
+
54
+
55
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
56
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
57
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
58
+ # The whole block is removed by reverting the commit that added it.
59
+ import json # noqa: F401,E402
60
+ # ---- END PLUGIN-COMPAT ----
tools/approval_detection.py ADDED
@@ -0,0 +1,1456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dangerous-command detection: normalization, tokenizing, and pattern tables.
2
+
3
+ Pure command classification for :mod:`tools.approval` — no approval state, config reads, or
4
+ prompting live here.
5
+ """
6
+
7
+ import functools
8
+ import logging
9
+ import os
10
+ import re
11
+ import shlex
12
+ import tempfile
13
+ import unicodedata
14
+
15
+ logger = logging.getLogger("tools.approval")
16
+
17
+ # Sensitive write targets, matched via ~ / $HOME / $HERMES_HOME spellings. The resolved absolute
18
+ # home is folded into these forms at detection time by _normalize_command_for_detection(), so no
19
+ # import-time path snapshot (stale once HERMES_HOME is set after import) lives in the patterns.
20
+ _SSH_SENSITIVE_PATH = r'(?:~|\$home|\$\{home\})/\.ssh(?:/|$)'
21
+ _HERMES_ENV_PATH = (
22
+ r'(?:~\/\.hermes/|(?:\$home|\$\{home\})/\.hermes/|(?:\$hermes_home|\$\{hermes_home\})/)' r'\.env\b'
23
+ )
24
+ # ~/.hermes/config.yaml IS the security policy (approvals.mode, yolo, allowlist) and the config cache is mtime-keyed,
25
+ # so a write takes effect mid-session. Terminal-side coverage (sed -i, tee, >, cp) pairs the file_tools deny.
26
+ _HERMES_CONFIG_PATH = (
27
+ r'(?:~\/\.hermes/|(?:\$home|\$\{home\})/\.hermes/|(?:\$hermes_home|\$\{hermes_home\})/)' r'config\.yaml\b'
28
+ )
29
+ _PROJECT_ENV_PATH = r'(?:(?:/|\.{1,2}/)?(?:[^\s/"\'`]+/)*\.env(?:\.[^/\s"\'`]+)*)'
30
+ _PROJECT_CONFIG_PATH = r'(?:(?:/|\.{1,2}/)?(?:[^\s/"\'`]+/)*config\.yaml)'
31
+ _SHELL_RC_FILES = r'(?:~|\$home|\$\{home\})/\.' r'(?:bashrc|zshrc|profile|bash_profile|zprofile)\b'
32
+ _CREDENTIAL_FILES = r'(?:~|\$home|\$\{home\})/\.' r'(?:netrc|pgpass|npmrc|pypirc)\b'
33
+ # macOS: /etc, /var, /tmp, /home are symlinks to /private/*, so /private/etc/sudoers would bypass a plain
34
+ # "/etc/" check. Match both forms.
35
+ _MACOS_PRIVATE_SYSTEM_PATH = r'/private/(?:etc|var|tmp|home)/'
36
+ _SYSTEM_CONFIG_PATH = rf'(?:/etc/|{_MACOS_PRIVATE_SYSTEM_PATH})'
37
+ _SENSITIVE_WRITE_TARGET = (
38
+ rf'(?:{_SYSTEM_CONFIG_PATH}|/dev/sd|{_SSH_SENSITIVE_PATH}|{_HERMES_ENV_PATH}|{_HERMES_CONFIG_PATH}|'
39
+ rf'{_SHELL_RC_FILES}|{_CREDENTIAL_FILES})'
40
+ )
41
+ _USER_SENSITIVE_WRITE_TARGET = rf'(?:{_SSH_SENSITIVE_PATH}|{_SHELL_RC_FILES}|{_CREDENTIAL_FILES})'
42
+ _PROJECT_SENSITIVE_WRITE_TARGET = rf'(?:{_PROJECT_ENV_PATH}|{_PROJECT_CONFIG_PATH})'
43
+ # cp/mv/install: the sensitive path is a write target only as the LAST argument (destination), so
44
+ # `cp config.yaml backup.yaml` (config.yaml as SOURCE) stays out.
45
+ _COMMAND_TAIL = r'(?:\s*(?:&&|\|\||;).*)?$'
46
+ # `>`/`>>`/tee: the path is ALWAYS a write target regardless of what follows, so only require a
47
+ # shell word boundary (_COMMAND_TAIL let `echo x > .env extra` / `echo x > .env # note` slip past).
48
+ # `#` is deliberately NOT a boundary: a glued `#` is part of the filename (`.env#backup`).
49
+ _WRITE_TARGET_BOUNDARY = r'(?=[\s;&|<>"\']|$)'
50
+
51
+ # ---- Hardline (unconditional) blocklist ---------------------------------------------------
52
+ # Commands that NEVER run via the agent, regardless of --yolo, approvals.mode=off, or cron approve
53
+ # mode — a floor below yolo. Applies only to environments that can damage the host (local, ssh,
54
+ # container-host cron); containerized backends already bypass the dangerous-command layer.
55
+ # Deliberately tiny: only things with no recovery path (root wipe, raw block device writes,
56
+ # shutdown, DoS). Recoverable operations (git reset --hard, chmod -R 777, curl|sh) stay in
57
+ # DANGEROUS_PATTERNS.
58
+
59
+ # Start-of-command position: start of string, newline, subshell opener ($( or backtick), optionally consuming
60
+ # sudo/env/exec/nohup/setsid/time wrappers. Keeps shutdown/reboot rules from firing on "echo reboot" / "grep
61
+ # 'shutdown' log". Real ;/&/| separators are converted to newlines by the quote-aware _mark_command_starts pass;
62
+ # keeping them here mistakes quoted data (grep '(safe|rm -rf /)') for commands.
63
+ _CMDPOS = (
64
+ r'(?:^|[\n`]|\$\()' r'\s*' # start position, optional whitespace
65
+ r'(?:sudo\s+(?:-[^\s]+\s+)*)?' r'(?:env\s+(?:\w+=\S*\s+)*)?' # optional sudo with flags, env VAR=VAL pairs
66
+ r'(?:(?:exec|nohup|setsid|time)\s+)*' r'\s*' # optional wrapper commands
67
+ )
68
+
69
+
70
+ # Destructive-path matcher for the rm hardline rules: accept the path fully wrapped in a matching
71
+ # quote pair (`rm -rf "/"`, `rm -rf "$HOME"`) OR bare with a terminator (whitespace, end, or
72
+ # `) ` ; | &` so `$(rm -rf /)` is caught). A bare-token-only anchor lets quoted spellings slip past the floor.
73
+ def _hardline_rm_path(path_alt: str, tail: str = r'(?:\s|$|[)`;|&])') -> str:
74
+ return rf'(?:["\'](?:{path_alt})["\']|(?:{path_alt}){tail})'
75
+
76
+
77
+ # Protected system roots whose recursive deletion has no recovery path.
78
+ _HARDLINE_SYSTEM_DIRS = (r'/home|/home/\*|/root|/root/\*|/etc|/etc/\*|/usr|/usr/\*|'
79
+ r'/var|/var/\*|/bin|/bin/\*|/sbin|/sbin/\*|/boot|/boot/\*|/lib|/lib/\*')
80
+
81
+ # `rm` plus flag group, shared by the rm hardline rules (plain concatenation, not f-string:
82
+ # backslashes in replacement fields are unsupported on the 3.11 floor). _CMDPOS-anchored so `rm`
83
+ # must be an actual command word — "rm -rf /" as DATA in `git commit -m "…rm -rf /…"` must not trip the floor.
84
+ _RM_FLAG_PREFIX = _CMDPOS + r'rm\s+(-[^\s]*\s+)*'
85
+ # Package-manager global options, each optionally taking ONE non-dash operand.
86
+ _PKG_OPTS = r'(?:-[^\s]+(?:\s+[^-\s][^\s]*)?\s+)*'
87
+
88
+ HARDLINE_PATTERNS = [
89
+ # Root path: any root-anchored path whose components collapse to "/" in the shell ("/", "//",
90
+ # "/.", "/./", "/../..", optional trailing glob). Each inter-slash segment must be exactly "."
91
+ # or "..", so "/tmp", "/.ssh", even "/..." are literal dirs that fall through to the softer
92
+ # DANGEROUS rules. The "/ \*" alt covers `rm -rf / *` (two args: "/" plus the glob).
93
+ (_RM_FLAG_PREFIX + _hardline_rm_path(r'/(?:(?:\.\.?)?/)*(?:\.\.?)?\**|/ \*'), "recursive delete of root filesystem"),
94
+ (_RM_FLAG_PREFIX + _hardline_rm_path(_HARDLINE_SYSTEM_DIRS), "recursive delete of system directory"),
95
+ (_RM_FLAG_PREFIX + _hardline_rm_path(r'(?:~|\$\{?HOME\}?)(?:/?|/\*)?'), "recursive delete of home directory"),
96
+ # Command-name rules (mkfs, dd, kill, shutdown...) are _CMDPOS-anchored so quoted prose
97
+ # (`echo "does this use mkfs?"`) cannot trip the floor.
98
+ # See #93392.
99
+ (_CMDPOS + r'mkfs(\.[a-z0-9]+)?\b', "format filesystem (mkfs)"),
100
+ # `dd` is a command-name token, so anchor it to command position like mkfs/rm/shutdown (#93392): quoted
101
+ # prose such as `git commit -m "never dd of=/dev/sda"` is an argument, not a command. The argument tail
102
+ # ([^\n]*of=/dev/...) is kept so flag order doesn't matter.
103
+ (_CMDPOS + r'dd\b[^\n]*\bof=/dev/(sd|nvme|hd|mmcblk|vd|xvd)[a-z0-9]*', "dd to raw block device"),
104
+ # Positionless rules (no command-name token: `>` sits mid-command, the fork bomb is a function
105
+ # definition) are matched against a QUOTE-MASKED variant (_QUOTE_MASKED_HARDLINE_DESCRIPTIONS /
106
+ # _mask_quoted_prose) so quoted prose cannot trip them; sh -c / bash -c / eval payloads still scan raw.
107
+ # The redirect rule has no command-name token to anchor (`>` appears mid-command: `cat f > /dev/sda`),
108
+ # so command-position anchoring is the wrong tool. It is instead matched against a QUOTE-MASKED variant
109
+ # of the command (see _QUOTE_MASKED_HARDLINE / _mask_quoted_strings) so quoted prose (`echo "cat f >
110
+ # /dev/sda"`) cannot trip it, while shell-carrying wrappers (sh -c / bash -c / eval) still surface their
111
+ # payload as a raw detection variant — quoting is not a bypass (#93392).
112
+ (r'>\s*/dev/(sd|nvme|hd|mmcblk|vd|xvd)[a-z0-9]*\b', "redirect to raw block device"),
113
+ (r':\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:', "fork bomb"),
114
+ # Kill every process on the system — anchor the command-name token so `echo "kill -1 sends SIGHUP to
115
+ # everything"` doesn't trip (#93392).
116
+ (_CMDPOS + r'kill\s+(-[^\s]+\s+)*-1\b', "kill all processes"),
117
+ (_CMDPOS + r'(shutdown|reboot|halt|poweroff)\b', "system shutdown/reboot"),
118
+ (_CMDPOS + r'init\s+[06]\b', "init 0/6 (shutdown/reboot)"),
119
+ (_CMDPOS + r'systemctl\s+(poweroff|reboot|halt|kexec)\b', "systemctl poweroff/reboot"),
120
+ (_CMDPOS + r'telinit\s+[06]\b', "telinit 0/6 (shutdown/reboot)"),
121
+ ]
122
+
123
+ # Pre-compiled at module load so the hot-path matcher never pays the cold re.compile fan-out
124
+ # (re._cache can be evicted by unrelated regex work).
125
+ _RE_FLAGS = re.IGNORECASE | re.DOTALL
126
+ # Positionless hardline rules matched against quote-masked variants (see above).
127
+ _QUOTE_MASKED_HARDLINE_DESCRIPTIONS = frozenset({"redirect to raw block device", "fork bomb"})
128
+ HARDLINE_PATTERNS_COMPILED = [
129
+ (re.compile(p, _RE_FLAGS), d, d in _QUOTE_MASKED_HARDLINE_DESCRIPTIONS) for p, d in HARDLINE_PATTERNS
130
+ ]
131
+ # Commands that hand a quoted argument to another shell to EXECUTE: quoted text is code, not
132
+ # prose, so quote-masked hardline rules scan the raw string.
133
+ _SHELL_CARRIER_NAMES = frozenset({"eval", "sh", "bash", "zsh", "ksh", "dash", "source", "."})
134
+
135
+
136
+ def _contains_shell_carrier(command: str) -> bool:
137
+ """Return whether any command-position word is a shell-carrying command."""
138
+ return any(
139
+ os.path.basename(_deobfuscate_shell_word_for_detection(word)).lower() in _SHELL_CARRIER_NAMES
140
+ for _, _, word in _iter_shell_command_word_spans(command)
141
+ )
142
+
143
+
144
+ def _mask_quoted_prose(command: str) -> str:
145
+ """Blank out quoted string CONTENT for positionless hardline matching (detection-only).
146
+ Quote characters stay; inside double quotes `$(...)` and backtick spans are kept RAW because
147
+ the shell really executes them. An unclosed quote masks to end-of-string, which cannot hide a
148
+ runnable command (the shell would not run it either).
149
+
150
+ Detection-only rewrite used by the quote-masked hardline rules (redirect-to-block-device, fork bomb):
151
+ text inside single or double quotes is data the shell passes as an argument, so `echo "cat f >
152
+ /dev/sda"` must not trip the unconditional floor (#93392). Unquoted text is untouched.
153
+ """
154
+ return "".join(
155
+ command[i:j] if quote is None or kind in ("quote", "subst") else " " * (j - i)
156
+ for kind, i, j, quote in _scan_shell(command, subst="q", naive_backtick=True)
157
+ )
158
+
159
+
160
+ # ---- Sudo stdin guard: without SUDO_PASSWORD configured, an explicit "sudo -S" is the LLM piping
161
+ # a guessed password via stdin (brute-force vector). Unconditional block.
162
+ _SUDO_STDIN_RE = re.compile(r'(?:^|[;&|`\n]|&&|\|\||\$\()\s*sudo\s+-S\b', re.IGNORECASE)
163
+
164
+
165
+ def _check_sudo_stdin_guard(command: str) -> tuple:
166
+ """Detect ``sudo -S`` without configured SUDO_PASSWORD -> (is_blocked, description). When
167
+ SUDO_PASSWORD is set, ``_transform_sudo_command`` injects ``-S`` itself, so this guard only
168
+ fires when the LLM wrote it explicitly."""
169
+ if "SUDO_PASSWORD" not in os.environ and _SUDO_STDIN_RE.search(_normalize_command_for_detection(command).lower()):
170
+ return (True, "sudo password guessing via stdin (sudo -S)")
171
+ return (False, None)
172
+
173
+
174
+ def detect_hardline_command(command: str) -> tuple:
175
+ """Check hardline patterns (NEVER bypassable, even in YOLO) -> (is_hardline, description)."""
176
+ if _command_parser_limit_exceeded(command):
177
+ return (True, _PARSER_LIMIT_DESCRIPTION)
178
+ # The malformed-quoting verdict needs the author's quote state. Normalization strips escapes
179
+ # (`\"` -> `"`), so a shell-valid pattern like `grep -o "[^\"]*"` lexed as unterminated and was
180
+ # reported as a hardline block (118 of 125 hardline blocks in one week of real use, every one a
181
+ # benign grep). Only quoted newlines are masked: they are data, and masking keeps quoting intact.
182
+ _, malformed_grep = _grep_safe_detection_variant(_mask_quoted_newlines(command))
183
+ if malformed_grep:
184
+ return (True, _MALFORMED_EXEC_DESCRIPTION)
185
+ for command_variant in _command_detection_variants(command):
186
+ variant_lower = command_variant.lower()
187
+ masked_lower: str | None = None
188
+ for pattern_re, description, quote_masked in HARDLINE_PATTERNS_COMPILED:
189
+ if quote_masked and masked_lower is None:
190
+ # Positionless rules see quoted prose as DATA, except under shell carriers
191
+ # (sh -c, eval, source) whose quoted argument is code — those scan raw. bash -c
192
+ # payloads also surface as their own raw variants via _execution_flag_findings.
193
+ masked_lower = (
194
+ variant_lower if _contains_shell_carrier(command_variant)
195
+ else _mask_quoted_prose(command_variant).lower()
196
+ )
197
+ if pattern_re.search(masked_lower if quote_masked else variant_lower):
198
+ return (True, description)
199
+ return (False, None)
200
+
201
+
202
+ # ---- Dangerous command patterns -----------------------------------------------------------
203
+ DANGEROUS_PATTERNS = [
204
+ (r'\brm\s+(-[^\s]*\s+)*/', "delete in root path"),
205
+ (r'\brm\s+-[^\s]*r', "recursive delete"),
206
+ (r'\brm\s+--recursive\b', "recursive delete (long flag)"),
207
+ # GNU rm permutes options, so flags may FOLLOW operands (`rm build/ -rf`). The operand run
208
+ # cannot cross a command separator (so `rm foo | grep -r` is not attributed to rm), a quote,
209
+ # or a bare ` -- ` end-of-options (after which `-rf` is a literal filename). The flag token
210
+ # must follow whitespace so the `r` in long options like `--registry` does not count.
211
+ (r'\brm\s+(?!--(?:\s|$))(?:(?!\s--(?:\s|$))[^\n"\';|&])*\s' r'(?:-[a-z]*r[a-z]*\b|--recursive\b)',
212
+ # GNU rm permutes options, so a recursive flag group may legally FOLLOW the operands: `rm build/ -rf`,
213
+ # `rm build/ -r -f`, and `rm build/ --recursive --force` are all equivalent to the flags-first
214
+ # spellings the two patterns above catch — without this rule they run with no approval prompt at all.
215
+ # Port of openai/codex#33464 ("recognize force options when they follow operands").
216
+ "recursive delete (flags after operands)"),
217
+ # Windows cmd/powershell destructive built-ins: gate only when executed through the shell so
218
+ # prose/filenames containing "del"/"rd" do not trip.
219
+ (r'\bcmd(?:\.exe)?\s+/(?:c|k)\s+.*\b(?:del|erase|rd|rmdir)\b', "Windows cmd destructive delete"),
220
+ # PowerShell runs the verb as default positional arg (no -Command needed); anchor the verb to command
221
+ # position (after leading -Flag switches and optional -Command/-c) so `-File c:\del-logs\run.ps1` is not caught.
222
+ (r'\b(?:powershell|pwsh)(?:\.exe)?\b(?:\s+-\S+)*\s+(?:-(?:command|c)\s+)?["\']?(?:remove-item|rmdir|erase|del|rd|ri|rm)\b', "Windows PowerShell destructive delete"),
223
+ (r'\b(?:powershell|pwsh)(?:\.exe)?\b.*\s-(?:encodedcommand|enc|e)\b', "PowerShell encoded command execution"),
224
+ # ── Windows destructive tier: native Windows EXEs/cmdlets reachable from ANY backend on a
225
+ # Windows host (incl. git-bash). Input is lowercased by the variant loop, so patterns are
226
+ # lowercase. Each requires the destructive flag/verb so benign usage (`taskkill /IM app.exe`,
227
+ # `reg query`, `icacls file`) does NOT prompt. Bare Remove-Item form (ACP clients, pwsh-default
228
+ # SSH hosts, or compound commands where `powershell` appeared earlier).
229
+ # See #69472.
230
+ (r'\bremove-item\b[^\n;|&]*\s-(?:recurse|force)\b', "PowerShell destructive delete (Remove-Item)"),
231
+ # Bare cmd builtins with /s (recurse) or /q (quiet); plain `del file.txt` is covered only by the prefixed rule.
232
+ (r'\b(?:del|erase|rd|rmdir)\s+(?:/[a-z]\s+)*/[sq]\b', "Windows destructive delete (recursive/quiet switch)"),
233
+ # Remote content piped to Invoke-Expression — PowerShell's `curl | sh`.
234
+ (r'\b(?:iwr|invoke-webrequest|invoke-restmethod|irm|curl|wget)\b[^\n]*\|\s*(?:iex|invoke-expression)\b', "pipe remote content to PowerShell (iwr | iex)"),
235
+ (r'\b(?:iex|invoke-expression)\s*\(\s*(?:iwr|invoke-webrequest|invoke-restmethod|irm)\b', "execute remote content via Invoke-Expression"),
236
+ # Force process kills — Windows analogue of pkill -9.
237
+ (r'\btaskkill\b[^\n]*\s/f\b', "force kill processes (taskkill /F)"),
238
+ (r'\bstop-process\b[^\n]*\s-force\b', "force kill processes (Stop-Process -Force)"),
239
+ # Volume/disk destruction — Windows analogue of mkfs / dd.
240
+ (r'\bformat-volume\b', "format filesystem (Format-Volume)"),
241
+ (r'\bclear-disk\b', "wipe disk (Clear-Disk)"),
242
+ (r'\bdiskpart\b', "disk partitioning (diskpart)"),
243
+ (r'\bformat(?:\.com)?\s+[a-z]:', "format drive (format.com)"),
244
+ (r'\bcipher\s+/w\b', "wipe free space (cipher /w)"),
245
+ # ACL destruction — Windows analogue of chmod 777.
246
+ (r'\bicacls\b[^\n]*\s/grant\b[^\n]*\b(?:everyone|todos|jeder|tout\s+le\s+monde|\*s-1-1-0)\b', "grant Everyone access (icacls)"),
247
+ (r'\bicacls\b[^\n]*\s/reset\b', "reset ACLs recursively (icacls /reset)"),
248
+ # Backup/recovery destruction — classic ransomware prep.
249
+ (r'\bvssadmin\b[^\n]*\bdelete\s+shadows\b', "delete volume shadow copies (vssadmin)"),
250
+ (r'\bwbadmin\b[^\n]*\bdelete\b', "delete backups (wbadmin)"),
251
+ (r'\bbcdedit\b[^\n]*\s/set\b', "modify boot configuration (bcdedit /set)"),
252
+ # Registry deletion with force flag.
253
+ (r'\breg(?:\.exe)?\s+delete\b', "registry delete (reg delete)"),
254
+ (r'\bremove-itemproperty\b[^\n]*\s-force\b', "registry value delete (Remove-ItemProperty -Force)"),
255
+ # Windows service/system stop — analogue of systemctl stop.
256
+ (r'\bstop-service\b[^\n]*\s-force\b', "force stop service (Stop-Service -Force)"),
257
+ (r'\bsc(?:\.exe)?\s+(?:stop|delete)\b', "stop/delete service (sc)"),
258
+ # Windows-form credential paths; the POSIX ~/.ssh patterns never match drive-letter or backslash spellings.
259
+ (r'\busers[\\/][^\\/\s]+[\\/]\.ssh\b', "access to SSH keys (Windows path)"),
260
+ (r'\bappdata[\\/](?:local|roaming)[\\/]hermes[^\n]*\.env\b', "access to Hermes secrets (Windows path)"),
261
+ # ── end of Windows tier
262
+ (r'\bchmod\s+(-[^\s]*\s+)*(777|666|o\+[rwx]*w|a\+[rwx]*w)\b', "world/other-writable permissions"),
263
+ (r'\bchmod\s+--recursive\b.*(777|666|o\+[rwx]*w|a\+[rwx]*w)', "recursive world/other-writable (long flag)"),
264
+ (r'\bchown\s+(-[^\s]*)?R\s+root', "recursive chown to root"),
265
+ (r'\bchown\s+--recur[a-z]*\b.*root', "recursive chown to root (long flag)"),
266
+ # _CMDPOS-anchored like the hardline twins: quoted prose mentioning mkfs/dd must not require approval to echo.
267
+ # See #93392.
268
+ (_CMDPOS + r'mkfs\b', "format filesystem"),
269
+ (_CMDPOS + r'dd\s+.*if=', "disk copy"),
270
+ (r'>\s*/dev/sd', "write to block device"),
271
+ (r'\bDROP\s+(TABLE|DATABASE)\b', "SQL DROP"),
272
+ # [^\n]* not .*: under DOTALL a WHERE on the *next* line would satisfy the lookahead and
273
+ # silently allow DELETE without WHERE.
274
+ (r'\bDELETE\s+FROM\b(?![^\n]*\bWHERE\b)', "SQL DELETE without WHERE"),
275
+ (r'\bTRUNCATE\s+(TABLE)?\s*\w', "SQL TRUNCATE"),
276
+ (rf'>\s*{_SYSTEM_CONFIG_PATH}', "overwrite system config"),
277
+ (r'\bsystemctl\s+(-[^\s]+\s+)*(stop|restart|disable|mask)\b', "stop/restart system service"),
278
+ (r'\bkill\s+-9\s+-1\b', "kill all processes"),
279
+ (r'\bpkill\s+-9\b', "force kill processes"),
280
+ # killall with SIGKILL (-9 / -KILL / -s KILL / -SIGKILL) and `killall -r <regex>` broad sweeps
281
+ # that can wipe unrelated processes.
282
+ (r'\bkillall\s+(-[^\s]*\s+)*-(9|KILL|SIGKILL)\b', "force kill processes (killall -KILL)"),
283
+ (r'\bkillall\s+(-[^\s]*\s+)*-s\s+(KILL|SIGKILL|9)\b', "force kill processes (killall -s KILL)"),
284
+ (r'\bkillall\s+(-[^\s]*\s+)*-r\b', "kill processes by regex (killall -r)"),
285
+ (r':\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:', "fork bomb"),
286
+ # Shell -c is parsed structurally by _execution_flag_findings(); a regex searching a dash-token
287
+ # for "c" also matched --norc/--rcfile/--restricted.
288
+ (r'\b(curl|wget)\b.*\|\s*(?:[/\w]*/)?(?:ba)?sh(?:\s|$|-c)', "pipe remote content to shell"),
289
+ (r'\b(bash|sh|zsh|ksh)\s+<\s*<?\s*\(\s*(curl|wget)\b', "execute remote script via process substitution"),
290
+ # eval/source/. $(curl ...) — equivalent to piping remote content to a shell.
291
+ (r'(?:\beval\b|\bsource\b|\.)\s*(?:\$\(\s*|`\s*)(?:curl|wget)\b', "execute remote content via command substitution"),
292
+ # Cloud instance-metadata (IMDS) credential endpoints — deterministic containment-escape
293
+ # detection. On a cloud VM these serve live IAM/service-account credentials to ANY local
294
+ # process with no auth, so a fetch is credential exfiltration unless the operator expects it.
295
+ # The host literals have no other use, so their appearance ANYWHERE in the command (any HTTP
296
+ # client, env assignment, or script argument) is the signal; lookarounds keep other 169.254.x.x
297
+ # link-local addresses and longer dotted strings out. This prompts for approval (legit uses
298
+ # exist on real cloud VMs) — it is NOT a hardline block. Covers the link-local IPv4 endpoint
299
+ # (AWS/Azure/GCP/OpenStack), its AWS IPv6 form fd00:ec2::254, the GCP hostname, and Alibaba
300
+ # Cloud's 100.100.100.200.
301
+ (r'(?<![\d.])(?:169\.254\.169\.254|100\.100\.100\.200)(?![\d.])'
302
+ r'|(?<![\w.-])metadata\.google\.internal(?![\w.-])'
303
+ r'|fd00:ec2::254',
304
+ "cloud metadata endpoint access (instance credentials)"),
305
+ # Decode-and-execute: `echo <base64> | base64 -d | bash` carries no dangerous keywords in the
306
+ # raw text yet runs arbitrary commands.
307
+ (r'\b(base64|base32|base16)\s+(?:-[dD]|--decode)\b.*\|\s*\b(bash|sh|zsh|ksh|dash)\b', "pipe decoded content to shell (possible command obfuscation)"),
308
+ # xxd uses -r for decode, not -d.
309
+ (r'\bxxd\s+-r\b.*\|\s*\b(bash|sh|zsh|ksh|dash)\b', "pipe xxd-decoded content to shell (possible command obfuscation)"),
310
+ # `echo 'eq -pe v/' | tr 'eqv' 'rmf' | bash` decodes to `rm -rf /`.
311
+ (r'\becho\b[^|]*\|\s*\btr\b[^|]*\|\s*\b(bash|sh|zsh|ksh|dash)\b', "pipe tr-transformed output to shell (possible command obfuscation)"),
312
+ (r'\bopenssl\b.*\b(?:base64|enc)\b[^|]*\s+-[dD]\b[^|]*\|\s*\b(bash|sh|zsh|ksh|dash)\b',
313
+ "pipe openssl-decoded content to shell (possible command obfuscation)"),
314
+ (rf'\btee\b.*["\']?{_SENSITIVE_WRITE_TARGET}', "overwrite system file via tee"),
315
+ (rf'>>?\s*["\']?{_SENSITIVE_WRITE_TARGET}', "overwrite system file via redirection"),
316
+ (rf'\btee\b.*["\']?{_PROJECT_SENSITIVE_WRITE_TARGET}["\']?{_WRITE_TARGET_BOUNDARY}', "overwrite project env/config via tee"),
317
+ (rf'>>?\s*["\']?{_PROJECT_SENSITIVE_WRITE_TARGET}["\']?{_WRITE_TARGET_BOUNDARY}', "overwrite project env/config via redirection"),
318
+ (r'\bxargs\s+.*\brm\b', "xargs with rm"),
319
+ # -execdir has the same semantics as -exec (runs in each match's directory).
320
+ (r'\bfind\b.*-exec(?:dir)?\s+(/\S*/)?rm\b', "find -exec/-execdir rm"),
321
+ (r'\bfind\b.*-delete\b', "find -delete"),
322
+ # Gateway lifecycle: stopping/restarting the gateway kills all running agents. Global flags
323
+ # between `hermes` and `gateway` (`hermes -p ade gateway restart`) are allowed so a profile flag can't slip past.
324
+ (r'\bhermes\s+(?:-{1,2}\S+(?:\s+\S+)?\s+)*gateway\s+(stop|restart)\b', "stop/restart hermes gateway (kills running agents)"),
325
+ (r'\bhermes\s+update\b', "hermes update (restarts gateway, kills running agents)"),
326
+ # Docker/Podman daemon redirect — global flags or env that point the CLI at a DIFFERENT (often remote) daemon:
327
+ # `docker -H ssh://prod stop app` looks local but operates on remote infra, so any redirect requires approval
328
+ # regardless of subcommand. The flag must be in global position (before the subcommand) and -H/--host/--context
329
+ # must carry a value, keeping `docker -h` and `docker run -h <hostname>` out. Listed BEFORE the lifecycle rules so
330
+ # a redirected lifecycle command surfaces the more specific reason.
331
+ (r'\bdocker\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(?:-h|--host)[=\s]+\S+', "docker with remote daemon redirect (-H/--host)"),
332
+ (r'\bdocker\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(?:-c|--context)[=\s]+\S+', "docker with daemon redirect (--context: alternate daemon)"),
333
+ (r'\bdocker\s+context\s+use\b', "docker context use (switches default daemon for future commands)"),
334
+ (r'\bpodman\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(?:--url|--connection|--identity)[=\s]+\S+', "podman with remote daemon redirect (--url/--connection/--identity)"),
335
+ (r'\bpodman\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(?:-r\b|--remote\b)', "podman remote mode (-r/--remote: remote daemon)"),
336
+ (r'\b(?:docker_host|docker_context|container_host|container_connection)=\S+', "docker/podman daemon redirect via environment (DOCKER_HOST/CONTAINER_HOST)"),
337
+ # Container lifecycle (docker.sock mounts let the agent stop/kill containers) always needs
338
+ # consent. Global flags between docker/compose and the verb and the legacy `docker-compose`
339
+ # binary are allowed so a flag can't slip past.
340
+ (r'\bdocker(?:-compose|\s+compose)\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(restart|stop|kill|down)\b', "docker compose restart/stop/kill/down (container lifecycle)"),
341
+ (r'\bdocker\s+(?:-{1,2}\S+(?:[=\s]\S+)?\s+)*(restart|stop|kill)\b', "docker restart/stop/kill (container lifecycle)"),
342
+ # Gateway protection: never start gateway outside systemd management
343
+ (r'gateway\s+run\b.*(&\s*$|&\s*;|\bdisown\b|\bsetsid\b)', "start gateway outside systemd (use 'systemctl --user restart hermes-gateway')"),
344
+ (r'\bnohup\b.*gateway\s+run\b', "start gateway outside systemd (use 'systemctl --user restart hermes-gateway')"),
345
+ # Self-termination protection: prevent agent from killing its own process
346
+ (r'\b(pkill|killall)\b.*\b(hermes|gateway|cli\.py)\b', "kill hermes/gateway process (self-termination)"),
347
+ # Self-termination via kill + $(pgrep/pidof): the substitution is opaque to the name-based
348
+ # pattern above, so catch the structural form.
349
+ (r'\bkill\b.*\$\(\s*(pgrep|pidof)\b', "kill process via pgrep/pidof expansion (self-termination)"),
350
+ (r'\bkill\b.*`\s*(pgrep|pidof)\b', "kill process via backtick pgrep/pidof expansion (self-termination)"),
351
+ # launchctl-driven gateway stop/restart on macOS (label `ai.hermes.gateway`). Two independent lookaheads, NOT a
352
+ # sequential match: a for-loop building the label from a list defined EARLIER (`for item in 'ai.hermes...'; do
353
+ # launchctl bootout "$label"`) never has "hermes" after the verb, and that slipped past and restarted 4 gateways
354
+ # with zero approval. Erring broad is correct for an approval gate: an extra prompt is cheap.
355
+ (r'(?=[\s\S]*\blaunchctl\s+(?:stop|kickstart|bootout|unload|kill|disable|remove)\b)(?=[\s\S]*\b(?:hermes|ai\.hermes)\b)', "stop/restart hermes launchd service (kills running agents)"),
356
+ (rf'\b(cp|mv|install)\b.*\s{_SYSTEM_CONFIG_PATH}', "copy/move file into system config path"),
357
+ (rf'\b(cp|mv|install)\b.*\s["\']?{_PROJECT_SENSITIVE_WRITE_TARGET}["\']?{_COMMAND_TAIL}', "overwrite project env/config file"),
358
+ # cp/mv/install OVERWRITING a credential/SSH/shell-rc/Hermes file (key implant, login-time
359
+ # injection) — pairs the tee/redirection coverage. Anchored to the command tail so only the
360
+ # DESTINATION fires; reading OUT of a sensitive path (`cp ~/.ssh/config /tmp/x`) stays safe.
361
+ # The trailing `[^\s"\']*` consumes the rest of the destination filename.
362
+ # The tee/redirection patterns above already gate _SENSITIVE_WRITE_TARGET (~/.ssh/*,
363
+ # ~/.netrc/.pgpass/.npmrc/.pypirc, shell rc files, ~/.hermes/config.yaml/.env), but cp/mv/install was
364
+ # only paired for /etc and project-relative env/config — so `cp evil ~/.ssh/authorized_keys` (key
365
+ # implant), `cp creds ~/.netrc`, and `cp evil ~/.bashrc` (login-time command injection) slipped through
366
+ # with auto-approve. Same unpaired-door rationale as #14639 / the sed-tee-redirect pairing on these
367
+ # targets. `authorized_keys` after the `~/.ssh/` fragment).
368
+ (rf'\b(cp|mv|install)\b.*\s["\']?{_SENSITIVE_WRITE_TARGET}[^\s"\']*["\']?{_COMMAND_TAIL}', "copy/move file into sensitive credential/SSH/shell-rc path"),
369
+ # In-place edits mutate the file directly, bypassing redirection/tee/cp coverage; gate the same
370
+ # startup/credential files.
371
+ (rf'\bsed\s+-[^\s]*i.*(?:{_USER_SENSITIVE_WRITE_TARGET})[^\s"\']*', "in-place edit of sensitive credential/SSH/shell-rc path"),
372
+ (rf'\bsed\s+--in-place\b.*(?:{_USER_SENSITIVE_WRITE_TARGET})[^\s"\']*', "in-place edit of sensitive credential/SSH/shell-rc path (long flag)"),
373
+ (rf'\b(?:perl|ruby)\b.*(?:^|\s)-[^\s]*i\b.*(?:{_USER_SENSITIVE_WRITE_TARGET})[^\s"\']*', "in-place edit of sensitive credential/SSH/shell-rc path (perl/ruby)"),
374
+ (rf'\bsed\s+-[^\s]*i.*\s{_SYSTEM_CONFIG_PATH}', "in-place edit of system config"),
375
+ (rf'\bsed\s+--in-place\b.*\s{_SYSTEM_CONFIG_PATH}', "in-place edit of system config (long flag)"),
376
+ # sed -i on Hermes config/.env bypasses the redirection/tee rules; pairs the file_tools
377
+ # write_file/patch deny so the terminal side is not an open door.
378
+ # In-place edit of a Hermes-managed security file (~/.hermes/config.yaml or .env). sed -i bypasses the
379
+ # redirection/tee patterns above because it mutates the file directly. See #14639.
380
+ (rf'\bsed\s+-[^\s]*i.*(?:{_HERMES_CONFIG_PATH}|{_HERMES_ENV_PATH})', "in-place edit of Hermes config/env"),
381
+ (rf'\bsed\s+--in-place\b.*(?:{_HERMES_CONFIG_PATH}|{_HERMES_ENV_PATH})', "in-place edit of Hermes config/env (long flag)"),
382
+ # perl/ruby -i: the flag may be its own token after other flags (`-p -i -e`), combined (`-pi`), or carry a backup
383
+ # suffix (`-i.bak`), so match any flag token containing `i` anywhere; `perl -e '...'` (no -i) does not trip.
384
+ # perl -i and ruby -i perform the same in-place mutation as sed -i but are not caught by the -e/-c
385
+ # script-execution pattern above (which targets code evaluation, not file mutation). Pairs the sed -i
386
+ # coverage from #14639.
387
+ (rf'\b(?:perl|ruby)\b.*(?:^|\s)-[^\s]*i\b.*(?:{_HERMES_CONFIG_PATH}|{_HERMES_ENV_PATH})', "in-place edit of Hermes config/env (perl/ruby)"),
388
+ # Interpreter heredocs are handled by _execution_flag_findings(); only shell heredocs stay
389
+ # regex-based. `bash <<'EOF'` runs arbitrary commands without triggering the `bash -c` path.
390
+ (r'\b(bash|sh|zsh|ksh)\s+<<', "shell execution via heredoc"),
391
+ # Git destructive operations. `git reset --hard` accepts any unambiguous long-flag prefix (--h,
392
+ # --ha, --har): --hard is the only reset mode starting with "h", and `--help` is special-cased
393
+ # by git before mode resolution.
394
+ (r'\bgit\s+reset\s+--h(?:a(?:r(?:d)?)?)?\b', "git reset --hard (destroys uncommitted changes)"),
395
+ (r'\bgit\s+push\b.*--forc[a-z]*\b', "git force push (rewrites remote history)"),
396
+ (r'\bgit\s+push\b.*-f\b', "git force push short flag (rewrites remote history)"),
397
+ (r'\bgit\s+clean\s+-[^\s]*f', "git clean with force (deletes untracked files)"),
398
+ (r'\bgit\s+branch\s+-D\b', "git branch force delete"),
399
+ # `-D` = `-d --force`; the long spellings are different tokens, so match delete+force in either order, bounded to
400
+ # one command segment (no `;`/`|`/`&`/newline) so an unrelated later command isn't contaminated.
401
+ (r'\bgit\s+branch\b[^;|&\n]*?(?:-d\b|--delete\b)[^;|&\n]*?(?:-f\b|--force\b)', "git branch force delete (long flags)"),
402
+ (r'\bgit\s+branch\b[^;|&\n]*?(?:-f\b|--force\b)[^;|&\n]*?(?:-d\b|--delete\b)', "git branch force delete (long flags, force-first)"),
403
+ # chmod +x then immediate run: the script content may hold dangerous commands individual patterns miss.
404
+ (r'\bchmod\s+\+x\b.*[;&|]+\s*\./', "chmod +x followed by immediate execution"),
405
+ # Sudo stdin/askpass/shell/list-privs flags. The agent has no TTY, so sudo invocations that succeed
406
+ # non-interactively read the password from stdin (-S) or askpass (-A); -s (shell) and -a (list) are gated as
407
+ # privilege chains (read SUDO_PASSWORD from .env -> sudo -S -s). Plain `sudo cmd` is TTY-bound and excluded. Input
408
+ # is lowercased, so S/s and A/a collapse. Lazy `[^;|&\n]*?` allows flag args without spanning separators. sudo
409
+ # resolves unambiguous long-flag prefixes: `--stdin` is the only long option starting with "st", `--askpass` the
410
+ # only one starting with "a".
411
+ (r'\bsudo\b[^;|&\n]*?\s+(?:-s\b|--st[a-z]*\b|-a\b|--a[a-z]*\b)', "sudo with privilege flag (stdin/askpass/shell/list)"),
412
+ # Combined short-flag form (-nS, -sa, -las).
413
+ (r'\bsudo\b[^;|&\n]*?\s+-[a-z]*[sa][a-z]*\b', "sudo with combined-flag privilege escalation"),
414
+ # Package-manager uninstall commands can remove installed software outside
415
+ # the current project (notably `npm uninstall -g`). Treat their destructive
416
+ # subcommands like other state-removing operations while leaving installs
417
+ # and updates alone.
418
+ # _CMDPOS-anchored (quoted prose like `git commit -m "npm uninstall docs"` is data); the
419
+ # option group also swallows one operand (`--prefix DIR`, `--proxy URL`, `--cwd DIR`).
420
+ (_CMDPOS + r'npm\s+' + _PKG_OPTS + r'(?:uninstall|unlink|remove|rm|r|un)\b', "package manager uninstall"),
421
+ (_CMDPOS + r'pnpm\s+' + _PKG_OPTS + r'(?:uninstall|remove|rm|un)\b', "package manager uninstall"),
422
+ (_CMDPOS + r'yarn\s+' + _PKG_OPTS + r'(?:global\s+)?(?:uninstall|remove)\b', "package manager uninstall"),
423
+ (_CMDPOS + r'pip(?:3)?\s+' + _PKG_OPTS + r'uninstall\b', "package manager uninstall"),
424
+ (_CMDPOS + r'brew\s+' + _PKG_OPTS + r'(?:uninstall|remove|rm)\b', "package manager uninstall"),
425
+ ]
426
+
427
+
428
+ DANGEROUS_PATTERNS_COMPILED = [(re.compile(p, _RE_FLAGS), d) for p, d in DANGEROUS_PATTERNS]
429
+
430
+ # Preserve approvals stored under the removed interpreter regex rules.
431
+ _REMOVED_PATTERN_KEY_ALIASES = {
432
+ "script execution via -e/-c flag": "(python[23]?|perl|ruby|node)\\s+-[ec]\\s+",
433
+ "script execution via heredoc": "(python[23]?|perl|ruby|node)\\s+<<",
434
+ }
435
+ # description <-> legacy regex-derived key (the old approval key, kept for backwards compatibility
436
+ # with stored allowlist/session entries), both ways.
437
+ _PATTERN_KEY_ALIASES: dict[str, set[str]] = {}
438
+ for _canonical_key, _legacy_key in [
439
+ (d, p.split(r'\b')[1] if r'\b' in p else p[:20]) for p, d in DANGEROUS_PATTERNS
440
+ ] + list(_REMOVED_PATTERN_KEY_ALIASES.items()):
441
+ _PATTERN_KEY_ALIASES.setdefault(_canonical_key, set()).update({_canonical_key, _legacy_key})
442
+ _PATTERN_KEY_ALIASES.setdefault(_legacy_key, set()).update({_legacy_key, _canonical_key})
443
+
444
+
445
+ def _approval_key_aliases(pattern_key: str) -> set[str]:
446
+ """All approval keys for this pattern: the description plus the historical regex-derived key
447
+ older allowlist/session entries may still use."""
448
+ return _PATTERN_KEY_ALIASES.get(pattern_key, {pattern_key})
449
+
450
+
451
+ # ---- Detection ----------------------------------------------------------------------------
452
+ def _normalize_command_for_detection(command: str) -> str:
453
+ """Normalize a command before pattern matching so ANSI escapes, null bytes, Unicode fullwidth
454
+ forms, and shell splicing tricks cannot bypass detection."""
455
+ from tools.ansi_strip import strip_ansi
456
+ command = unicodedata.normalize('NFKC', strip_ansi(command).replace('\x00', ''))
457
+ # Collapse backslash-newline continuations (`rm -rf \<newline>/` runs as `rm -rf /`). MUST
458
+ # precede the generic escape strip below, whose [^\n] class skips newlines and would leave the
459
+ # backslash wedged between tokens, defeating the structured rm/mkfs/dd patterns incl. the HARDLINE floor.
460
+ command = re.sub(r'\\\r?\n', '', command)
461
+ # Fold absolute user/Hermes home prefixes to ~/ and ~/.hermes/ so the static patterns catch /home/alice/.bashrc
462
+ # and C:\Users\alice\.bashrc. Resolved at detection time (not import time) so it tracks HOME/HERMES_HOME set
463
+ # later. MUST run before the backslash strip (which would dissolve C:\Users\alice to C:Usersalice). Hermes home
464
+ # first: on Windows it nests under the user home, and folding the user home first would eat the prefix it needs.
465
+ command = _rewrite_resolved_hermes_home(command)
466
+ command = _rewrite_resolved_user_home(command)
467
+ # Strip backslash-escapes (r\m -> rm) and empty-string literals (r''m -> rm).
468
+ command = re.sub(r'\\([^\n])', r'\1', command)
469
+ command = re.sub(r"''|\"\"", '', command)
470
+ # Collapse $IFS / ${IFS...} (incl. `${IFS:0:1}`) to a space: IFS defaults to whitespace, so `rm${IFS}-rf${IFS}/`
471
+ # runs as `rm -rf /`, and every pattern — incl. the hardline floor — anchors on literal \s between tokens.
472
+ return re.sub(r'\$\{IFS\b[^}]*\}|\$IFS\b', ' ', command)
473
+
474
+
475
+ # Shell metacharacters, quotes, and whitespace that terminate a path token.
476
+ _PATH_TOKEN_STOP = r"""\s'"`;|&<>()"""
477
+ _PATH_TAIL = r"(?P<tail>(?:[/\\][^/\\" + _PATH_TOKEN_STOP + r"]*)+)"
478
+
479
+
480
+ @functools.lru_cache(maxsize=64)
481
+ def _home_prefix_fold_regex(path: str):
482
+ """Compile a regex matching *path* as an absolute directory prefix.
483
+ Components match with either separator so native Windows, forward-slash, and mixed forms all
484
+ fold; the caller normalizes the tail's backslashes to ``/``. A non-empty tail is required, so a
485
+ bare home is never folded. Returns ``None`` for an unset/degenerate path (fewer than two
486
+ components: ``/``, ``C:\\``, ``""``) so a stray HOME cannot rewrite unrelated prefixes."""
487
+ components = [c for c in re.split(r"[/\\]+", path) if c] if path else []
488
+ if len(components) < 2:
489
+ return None
490
+ # Optional leading root separator; a Windows drive letter is a component.
491
+ return re.compile(r"[/\\]*" + r"[/\\]+".join(re.escape(c) for c in components) + _PATH_TAIL)
492
+
493
+
494
+ def _fold_home_prefixes(command: str, paths, replacement: str) -> str:
495
+ """Fold each resolved home prefix in *command* to *replacement* (no trailing separator; the tail
496
+ supplies it). Longest first so a deeper home folds before a shorter overlapping one that would clobber it."""
497
+ for path in dict.fromkeys(sorted((p for p in paths if p), key=len, reverse=True)):
498
+ pattern = _home_prefix_fold_regex(path)
499
+ if pattern is not None:
500
+ command = pattern.sub(lambda m: replacement + m.group("tail").replace("\\", "/"), command)
501
+ return command
502
+
503
+
504
+ def _rewrite_resolved_user_home(command: str) -> str:
505
+ """User home (expanduser / realpath / $HOME) -> ``~/``; no-op when unset, degenerate, or unresolvable."""
506
+ try:
507
+ # expanduser, realpath, and an explicit HOME — Windows expanduser uses USERPROFILE, not HOME.
508
+ home = os.path.expanduser("~")
509
+ paths = [home, os.path.realpath(home), os.environ.get("HOME", "")]
510
+ except Exception:
511
+ return command
512
+ return _fold_home_prefixes(command, paths, "~")
513
+
514
+
515
+ def _rewrite_resolved_hermes_home(command: str) -> str:
516
+ """Resolved HERMES_HOME (and its realpath) -> ``~/.hermes/`` so the _HERMES_CONFIG_PATH /
517
+ _HERMES_ENV_PATH rules match Docker/gateway deployments that spell the absolute path."""
518
+ try:
519
+ from hermes_constants import get_hermes_home
520
+ home = get_hermes_home().expanduser()
521
+ paths = [str(home), str(home.resolve(strict=False))]
522
+ except Exception:
523
+ return command
524
+ return _fold_home_prefixes(command, paths, "~/.hermes")
525
+
526
+
527
+ _PARAM_REPLACEMENT_RE = re.compile(r"\$\{[^}/\s]+/[^}/]*/(?P<replacement>[^}]*)\}")
528
+ _PARAM_DEFAULT_RE = re.compile(r"\$\{[^}:}\s]+:-(?P<default>[^}]*)\}")
529
+ _SIMPLE_SHELL_LITERAL_RE = re.compile(r"^[A-Za-z0-9_./:@%+=,-]+$")
530
+ _ENV_ASSIGNMENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=.*")
531
+ _COMMAND_WRAPPER_WORDS = {"sudo", "env", "exec", "nohup", "setsid", "time", "command", "builtin",
532
+ "nice", "timeout", "stdbuf", "ionice", "chrt", "taskset", "chroot"}
533
+ _SUDO_OPTIONS_WITH_ARG = {"-c", "--close-from", "-g", "--group", "-h", "--host", "-p", "--prompt", "-u", "--user"}
534
+ # Adapted from embwl0x's command-position work in #76063. Option operands are
535
+ # data, not executable positions; option spelling remains case-sensitive.
536
+ _COMMAND_WRAPPER_OPTIONS_WITH_ARG = {
537
+ "chroot": {"--groups", "--userspec"},
538
+ "sudo": _SUDO_OPTIONS_WITH_ARG,
539
+ "env": {"-a", "--argv0", "-C", "--chdir", "-S", "--split-string", "-u", "--unset"},
540
+ "exec": {"-a"}, "nice": {"-n", "--adjustment"},
541
+ "time": {"-f", "--format", "-o", "--output"},
542
+ "timeout": {"-k", "--kill-after", "-s", "--signal"},
543
+ "stdbuf": {"-e", "--error", "-i", "--input", "-o", "--output"},
544
+ "ionice": {"-c", "--class", "-n", "--classdata"},
545
+ }
546
+ _COMMAND_WRAPPER_NON_EXECUTING_OPTIONS = {
547
+ "command": {"-v", "-V"}, "chrt": {"-p", "--pid"},
548
+ "ionice": {"-p", "--pid", "--pgid", "--uid"}, "taskset": {"-p", "--pid"},
549
+ }
550
+ _COMMAND_WRAPPER_POSITIONAL_ARGS = {"chroot": 1, "chrt": 1, "taskset": 1, "timeout": 1}
551
+ _SHELL_COMMAND_TRANSITIONS = {"if", "then", "else", "elif", "do", "while", "until", "!"}
552
+ _SHELL_REDIRECTION_RE = re.compile(r"(?:[0-9]+)?(?:>>|<<|<>|>&|<&|>\||[<>])")
553
+
554
+ _INTERPRETER_NAME_RES = tuple((family, re.compile(pattern)) for family, pattern in (
555
+ ("python", r"py(?:\.exe)?|python[23]?(?:\.\d+)*(?:\.exe)?"), ("node", r"node(?:js)?(?:\.exe)?"),
556
+ ("perl", r"perl[0-9]*(?:\.\d+)*(?:\.exe)?"), ("ruby", r"ruby[0-9.]*(?:\.exe)?"), ("php", r"php(?:\.exe)?"),
557
+ ("powershell", r"powershell(?:\.exe)?|pwsh(?:\.exe)?"),
558
+ ))
559
+ _INTERPRETER_EXEC_FLAGS = {
560
+ "python": {"-c"}, "node": {"-e", "--eval", "-p", "--print"}, "perl": {"-e", "--eval"}, "ruby": {"-e"},
561
+ "php": {"-r"}, "powershell": {"-command", "-c", "-file", "-f"},
562
+ }
563
+ _INTERPRETER_WITH_ARG = {
564
+ "python": {"-W", "-X", "--check-hash-based-pycs"},
565
+ "node": {"-C", "--conditions", "--cpu-prof-dir", "--diagnostic-dir", "--icu-data-dir", "--import", "--loader",
566
+ "--openssl-config", "--require", "--title"},
567
+ "perl": {"-0", "-F", "-I", "-M", "-m", "-x"}, "ruby": {"-C", "-E", "-F", "-I", "-K", "-r"},
568
+ "php": {"-c", "-d", "-z"},
569
+ "powershell": {"-configurationname", "-custompipename", "-executionpolicy", "-inputformat", "-outputformat",
570
+ "-settingsfile", "-version", "-windowstyle", "-workingdirectory"},
571
+ }
572
+ _READ_TOOL_EXEC_FLAGS = {
573
+ "sort": {"--compress-program"}, "rg": {"--pre", "--hostname-bin"}, "ag": {"--pager"},
574
+ "man": {"--pager", "--html", "-P", "-H"},
575
+ }
576
+ # Required-argument options are ownership boundaries: an option-looking next token is data, not another option. These
577
+ # sets mirror the invocation grammar of the supported binaries (ripgrep 14, GNU sort, man-db, and ag 2.2).
578
+ _READ_TOOL_LONG_OPTIONS_WITH_ARG = {
579
+ "rg": {
580
+ "--after-context", "--before-context", "--color", "--colors", "--context", "--context-separator",
581
+ "--dfa-size-limit", "--encoding", "--engine", "--field-context-separator", "--field-match-separator",
582
+ "--file", "--generate", "--glob", "--hostname-bin", "--hyperlink-format", "--iglob", "--ignore-file",
583
+ "--max-columns", "--max-count", "--max-depth", "--max-filesize", "--path-separator", "--pre", "--pre-glob",
584
+ "--regex-size-limit", "--regexp", "--replace", "--sort", "--sortr", "--threads", "--type", "--type-add",
585
+ "--type-clear", "--type-not",
586
+ },
587
+ "sort": {
588
+ "--batch-size", "--buffer-size", "--compress-program", "--field-separator", "--files0-from", "--key",
589
+ "--output", "--parallel", "--random-source", "--sort", "--temporary-directory",
590
+ },
591
+ "man": {
592
+ "--config-file", "--encoding", "--extension", "--locale", "--manpath", "--pager", "--preprocessor",
593
+ "--prompt", "--recode", "--sections", "--systems",
594
+ },
595
+ "ag": {
596
+ "--ackmate-dir-filter", "--color-line-number", "--color-match", "--color-path", "--depth",
597
+ "--filename-pattern", "--file-search-regex", "--ignore", "--ignore-dir", "--max-count", "--pager",
598
+ "--path-to-ignore", "--width", "--workers",
599
+ },
600
+ }
601
+ _READ_TOOL_SHORT_OPTIONS_WITH_ARG = {
602
+ "rg": frozenset("efEmjgdtTABCMr"), "sort": frozenset("koStT"), "man": frozenset("CRLmMSserEPp"),
603
+ "ag": frozenset("gGmpW"),
604
+ }
605
+ _GREP_OPTIONS_WITH_ARG = {
606
+ "--after-context", "--before-context", "--binary-files", "--context", "--directories", "--devices", "--exclude",
607
+ "--exclude-dir", "--exclude-from", "--include", "--label", "--max-count", "--regexp", "--file",
608
+ }
609
+ _GREP_SHORT_OPTIONS_WITH_ARG = {"A", "B", "C", "D", "d", "e", "f", "m"}
610
+ _BASH_OPTIONS_WITH_ARG = {"-O", "+O", "-o", "+o", "--init-file", "--rcfile"}
611
+ _BASH_SHORT_OPTION_LETTERS = frozenset("ilrsDcabefhkmnptuvxBCEHPTOo")
612
+ _MAX_DETECTION_COMMAND_CHARS, _MAX_SEPARATOR_FREE_COMMAND_CHARS, _MAX_DETECTION_SEGMENTS = 128_000, 4_096, 25_000
613
+ _PARSER_LIMIT_DESCRIPTION = "command parser limit exceeded"
614
+ _MALFORMED_EXEC_DESCRIPTION = "command parser limit or malformed executable payload"
615
+ _GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION = "stop/restart hermes gateway via shell-spliced verb (kills running agents)"
616
+
617
+
618
+ def _command_parser_limit_exceeded(command: str) -> bool:
619
+ """Bound all parser work before normalization/tokenization. Separator counting is deliberately
620
+ conservative: quoted separators over-count, but crossing the ceiling fails closed rather than
621
+ letting an uninspected suffix execute."""
622
+ if len(command) > _MAX_DETECTION_COMMAND_CHARS:
623
+ return True
624
+ # Long separator-free input has no compound-command utility and makes every regex inspect one giant token.
625
+ if len(command) > _MAX_SEPARATOR_FREE_COMMAND_CHARS and not any(char in command for char in ";&|\n"):
626
+ return True
627
+ return sum(command.count(char) for char in ";&|\n") >= _MAX_DETECTION_SEGMENTS
628
+
629
+
630
+ def _backtick_end_from(segment: str, i: int) -> int | None:
631
+ """Index of the backtick closing the one opened at ``i``, or None when none follows."""
632
+ j = segment.find("`", i + 1)
633
+ while j != -1 and segment[j - 1] == "\\":
634
+ j = segment.find("`", j + 1)
635
+ return None if j == -1 else j
636
+
637
+
638
+ def _shell_tokens_with_spans(segment: str, start: int):
639
+ """Return shell words as ``(value, start, end, quoted)`` or ``None`` on malformed quoting.
640
+ Deliberately small lexer that never expands shell syntax; it exists to keep source spans (which
641
+ ``shlex`` does not expose) for deciding which quoted grep operand is data, not another command.
642
+
643
+ Lexing stops at the end of the simple command that begins at *start*: an unquoted ``;``, ``|``,
644
+ ``&`` or newline, or the ``)`` / backtick that closes the substitution the command sits inside.
645
+ Without that, a grep nested as ``"$(grep … | cut …)"`` was lexed together with the enclosing
646
+ command's closing quote, read as unbalanced quoting, and reported as a hardline block (546
647
+ blocked turns in one run, every one a false positive; ``sed -n "$(grep -n X f | cut -d: -f1),+3p" f``
648
+ is the canonical shape)."""
649
+ tokens, value, token_start, quote = [], [], None, None
650
+ depth = 0 # $(...) nesting opened AFTER start; a closer at depth 0 ends the enclosing substitution
651
+ # A backtick opened AFTER start is an operand substitution (``grep -e `cmd` f``); the matching
652
+ # closer belongs to it, not to an enclosing backtick the command might sit inside.
653
+ in_backtick = False
654
+
655
+ def flush(end: int) -> None:
656
+ raw = segment[token_start:end]
657
+ # Only a wholly single-quoted operand is inert shell data. Double quotes still execute $()
658
+ # and backticks; unquoted substitutions do too.
659
+ inert = (raw.startswith("'") and raw.endswith("'")) or ("='" in raw and raw.endswith("'"))
660
+ tokens.append(("".join(value), token_start, end, inert))
661
+
662
+ end_at = len(segment)
663
+ for kind, i, _, _ in _scan_shell(segment, start):
664
+ ch = segment[i]
665
+ if kind == "char" and not quote:
666
+ if ch.isspace() and ch != "\n":
667
+ if token_start is not None:
668
+ flush(i)
669
+ value, token_start = [], None
670
+ continue
671
+ if segment.startswith("$(", i):
672
+ depth += 1
673
+ elif ch == "`":
674
+ if in_backtick:
675
+ in_backtick = False
676
+ elif depth == 0 and _backtick_end_from(segment, i) is None:
677
+ end_at = i # unmatched: it closes the substitution this command sits inside
678
+ break
679
+ else:
680
+ in_backtick = True
681
+ elif ch == ")":
682
+ if depth == 0:
683
+ end_at = i
684
+ break
685
+ depth -= 1
686
+ elif ch in ";|&\n":
687
+ end_at = i
688
+ break
689
+ if token_start is None:
690
+ token_start = i
691
+ if kind == "quote":
692
+ quote = None if quote else ch
693
+ elif kind == "esc":
694
+ value.append(segment[i + 1])
695
+ elif ch == "\\" and not quote:
696
+ return None # dangling backslash
697
+ else:
698
+ value.append(ch)
699
+ if quote:
700
+ return None
701
+ if token_start is not None:
702
+ flush(end_at)
703
+ return tokens
704
+
705
+
706
+ def _quoted_grep_pattern_spans(command: str) -> tuple[list[tuple[int, int]], bool]:
707
+ """Structurally locate quoted grep PCRE operands -> (spans, malformed). On an ambiguous or
708
+ malformed grep parse callers fail closed and use the original command: no text is hidden on
709
+ an uncertain parse."""
710
+ spans: list[tuple[int, int]] = []
711
+ offset = 0
712
+ for segment in _iter_top_level_shell_segments(command):
713
+ segment_at = command.find(segment, offset)
714
+ offset = segment_at + len(segment)
715
+ for start, _, word in _iter_shell_command_word_spans(segment):
716
+ if os.path.basename(_deobfuscate_shell_word_for_detection(word)).lower() not in {"grep", "egrep"}:
717
+ continue
718
+ tokens = _shell_tokens_with_spans(segment, start)
719
+ if tokens is None:
720
+ return [], True
721
+ args, pattern_indexes = tokens[1:], []
722
+ pcre = explicit_patterns = False
723
+ operand_index, i, options = None, 0, True
724
+ while i < len(args):
725
+ token = args[i][0]
726
+ if options and token == "--":
727
+ options = False
728
+ elif options and token.startswith("--"):
729
+ option, equals, _ = token.partition("=")
730
+ pcre = pcre or option == "--perl-regexp"
731
+ explicit_patterns = explicit_patterns or option in {"--regexp", "--file"}
732
+ takes_next = option in _GREP_OPTIONS_WITH_ARG and not equals
733
+ if takes_next and i + 1 >= len(args):
734
+ return [], True
735
+ if option == "--regexp":
736
+ pattern_indexes.append(i + 1 if takes_next else i)
737
+ i += 1 if takes_next else 0
738
+ elif options and token.startswith("-") and token != "-":
739
+ chars = token[1:]
740
+ for j, char in enumerate(chars):
741
+ pcre = pcre or char == "P"
742
+ explicit_patterns = explicit_patterns or char in {"e", "f"}
743
+ if char in _GREP_SHORT_OPTIONS_WITH_ARG:
744
+ # The first argument-taking short option owns the rest of the bundle,
745
+ # or the next token when it comes last.
746
+ attached = j + 1 < len(chars)
747
+ if not attached and i + 1 >= len(args):
748
+ return [], True
749
+ if char == "e":
750
+ pattern_indexes.append(i if attached else i + 1)
751
+ i += 0 if attached else 1
752
+ break
753
+ elif operand_index is None:
754
+ operand_index = i
755
+ i += 1
756
+ if not explicit_patterns:
757
+ if operand_index is None:
758
+ return [], pcre
759
+ pattern_indexes.append(operand_index)
760
+ if pcre:
761
+ spans.extend(
762
+ (segment_at + token_start, segment_at + token_end)
763
+ for _, token_start, token_end, quoted in map(args.__getitem__, pattern_indexes) if quoted
764
+ )
765
+ return spans, False
766
+
767
+
768
+ def _splice(command: str, edits) -> str:
769
+ """Apply sorted, non-overlapping ``(start, end, text)`` edits to *command* in one pass
770
+ (re-slicing per edit is quadratic on 10k+ segments)."""
771
+ parts, previous = [], 0
772
+ for start, end, text in edits:
773
+ parts.extend((command[previous:start], text))
774
+ previous = end
775
+ return "".join(parts) + command[previous:]
776
+
777
+
778
+ def _grep_safe_detection_variant(command: str) -> tuple[str, bool]:
779
+ spans, malformed = _quoted_grep_pattern_spans(command)
780
+ if malformed or not spans:
781
+ return command, malformed
782
+ return _splice(command, [(start, end, " " * (end - start)) for start, end in spans]), False
783
+
784
+
785
+ def _interpreter_family(executable: str) -> str | None:
786
+ name = os.path.basename(executable).lower()
787
+ return next((family for family, name_re in _INTERPRETER_NAME_RES if name_re.fullmatch(name)), None)
788
+
789
+
790
+ def _shell_segment_tokens(segment: str, start: int) -> list[str] | None:
791
+ """Tokenize an already-bounded command segment. ``None`` distinguishes malformed quoting from
792
+ an empty segment so callers can fail closed for a program-bearing option rather than silently
793
+ skip it."""
794
+ try:
795
+ lexer = shlex.shlex(segment[start:], posix=True, punctuation_chars="<>")
796
+ lexer.whitespace_split, lexer.commenters = True, ""
797
+ return list(lexer)
798
+ except ValueError:
799
+ return None
800
+
801
+
802
+ def _iter_top_level_shell_segments(command: str):
803
+ """Yield top-level command segments in one left-to-right pass."""
804
+ start = 0
805
+ for kind, i, j, quote in _scan_shell(command, comments=True):
806
+ if kind == "comment" or (kind == "char" and quote is None and command[i] in ";&|\n"):
807
+ if start < i:
808
+ yield command[start:i]
809
+ start = j
810
+ if start < len(command):
811
+ yield command[start:]
812
+
813
+
814
+ def _interpreter_exec_flag(family: str, args: list[str]) -> str | None:
815
+ """Return an execution-bearing interpreter option, if present."""
816
+ flags, with_arg = _INTERPRETER_EXEC_FLAGS[family], _INTERPRETER_WITH_ARG[family]
817
+ powershell = family == "powershell"
818
+ skip_value = False
819
+ for token in args:
820
+ if skip_value:
821
+ skip_value = False
822
+ continue
823
+ if token == "--" or (not powershell and not token.startswith("-")):
824
+ break
825
+ option, equals, _ = token.partition("=")
826
+ comparable = option.lower() if powershell else option
827
+ if comparable in flags:
828
+ return comparable
829
+ # `-Wonce` and `ruby -rjson` attach an option value; they are not short-option bundles containing an execution
830
+ # flag. PowerShell's normal long options also use one dash, so bundle parsing never applies to that family.
831
+ has_attached_option_value = any(
832
+ option.startswith(short) and len(option) > len(short)
833
+ for short in with_arg if short.startswith("-") and not short.startswith("--")
834
+ )
835
+ if not powershell and not option.startswith("--") and len(option) > 2 and not has_attached_option_value:
836
+ bundled = next((f"-{char}" for char in option[1:] if f"-{char}" in flags), None)
837
+ if bundled:
838
+ return bundled
839
+ skip_value = comparable in with_arg and not equals
840
+ return None
841
+
842
+
843
+ def _bash_exec_payload(args: list[str]) -> tuple[bool, str | None]:
844
+ """Return whether Bash ``-c`` occurs and the command string it owns.
845
+ Bash's O/o options consume the following argument even when they precede a later ``-c`` or
846
+ share its short-option bundle; the two startup-file long options own their next token.
847
+ Parsing those first prevents both missed payloads and false ``-c`` hits."""
848
+ index = 0
849
+ while index < len(args):
850
+ token = args[index]
851
+ if token == "--" or not token.startswith(("-", "+")):
852
+ break
853
+ if token in _BASH_OPTIONS_WITH_ARG:
854
+ index += 2
855
+ continue
856
+ chars = token[1:]
857
+ # Bash option letters are case-sensitive; restricting to the documented alphabet
858
+ # preserves invalid controls such as `-Wc`.
859
+ if token.startswith("--") or not set(chars) <= _BASH_SHORT_OPTION_LETTERS:
860
+ index += 1
861
+ continue
862
+ consumed_option_arg = int("O" in chars or "o" in chars)
863
+ if "c" in chars:
864
+ payload_index = index + 1 + consumed_option_arg
865
+ return True, (args[payload_index] if payload_index < len(args) else None)
866
+ index += 1 + consumed_option_arg
867
+ return False, None
868
+
869
+
870
+ def _read_tool_exec_flag(tool: str, args: list[str]) -> tuple[str, str] | None:
871
+ """Return (option, program) for a read-only tool's program-running flag."""
872
+ flags = _READ_TOOL_EXEC_FLAGS[tool]
873
+ index = 0
874
+ while index < len(args):
875
+ token = args[index]
876
+ if token == "--":
877
+ break
878
+ option, equals, payload = token.partition("=")
879
+ payload = payload if equals else None
880
+ matched = option if option in flags else None
881
+ if tool == "man" and token.startswith(("-P", "-H")) and len(token) > 2:
882
+ matched, payload = token[:2], token[2:]
883
+ if matched:
884
+ if payload is None and index + 1 < len(args):
885
+ payload = args[index + 1]
886
+ # The option owns its program argument regardless of spelling; the real binaries
887
+ # execute a '-'-prefixed payload rather than reparsing it.
888
+ if payload:
889
+ return matched, payload
890
+ index += 2 if payload is not None and "=" not in token else 1
891
+ elif option in _READ_TOOL_LONG_OPTIONS_WITH_ARG[tool] and payload is None:
892
+ index += 2
893
+ elif token.startswith("-") and not token.startswith("--") and len(token) > 1:
894
+ # In a short bundle, the first argument-taking option owns the rest of the token, or
895
+ # the following token when it occurs last.
896
+ shorts = _READ_TOOL_SHORT_OPTIONS_WITH_ARG[tool]
897
+ owner = next((k for k, char in enumerate(token[1:], start=1) if char in shorts), None)
898
+ index += 2 if owner == len(token) - 1 else 1
899
+ else:
900
+ index += 1
901
+ return None
902
+
903
+
904
+ def _execution_flag_findings(command: str):
905
+ """Yield scoped execution mechanisms and any executable payloads."""
906
+ for segment in _iter_top_level_shell_segments(command):
907
+ for start, _, word in _iter_shell_command_word_spans(segment):
908
+ executable = _deobfuscate_shell_word_for_detection(word)
909
+ tokens = _shell_segment_tokens(segment, start)
910
+ executable_name = os.path.basename(executable).lower()
911
+ family = _interpreter_family(executable)
912
+ if tokens is None:
913
+ if family is not None or executable_name in _READ_TOOL_EXEC_FLAGS:
914
+ yield (_MALFORMED_EXEC_DESCRIPTION, None)
915
+ continue
916
+ if not tokens:
917
+ continue
918
+ args = tokens[1:]
919
+ if family and _interpreter_exec_flag(family, args):
920
+ yield ("script execution via -e/-c flag", None)
921
+ elif family and any(token.startswith("<<") for token in args):
922
+ yield ("script execution via heredoc", None)
923
+ else:
924
+ if executable_name in {"bash", "sh", "zsh", "ksh"}:
925
+ found, payload = _bash_exec_payload(args)
926
+ if found:
927
+ yield ("shell command via -c/-lc flag", payload)
928
+ if executable_name in _READ_TOOL_EXEC_FLAGS:
929
+ finding = _read_tool_exec_flag(executable_name, args)
930
+ if finding:
931
+ yield (f"arbitrary program execution via {executable_name} {finding[0]}", finding[1])
932
+
933
+
934
+ def _skip_shell_whitespace(command: str, pos: int) -> int:
935
+ while pos < len(command) and command[pos].isspace():
936
+ pos += 1
937
+ return pos
938
+
939
+
940
+ def _scan_shell(text: str, start: int = 0, end: int | None = None, *, subst: str = "",
941
+ brace: bool = False, stop_unterminated: bool = False, naive_backtick: bool = False,
942
+ comments: bool = False):
943
+ """Yield ``(kind, i, j, quote)`` lexical steps over ``text[start:end]`` without expanding.
944
+
945
+ The single quote/escape state machine behind every detection scanner. ``kind`` is ``"char"``
946
+ (one char), ``"esc"`` (backslash + the char it escapes; never inside single quotes), ``"quote"``
947
+ (an opening/closing quote char) or ``"subst"`` (a ``$(...)`` / backtick / ``${...}`` span);
948
+ With *comments*, ``"comment"`` spans are skipped without interpreting their quote syntax.
949
+ ``quote`` is the state the step was read in (``None``, ``'`` or ``"``). Substitutions are
950
+ recognized unquoted when ``"u"`` is in *subst*, inside double quotes when ``"q"`` is; *brace*
951
+ adds unquoted ``${...}``. An unterminated substitution falls through as plain chars unless
952
+ *stop_unterminated*, which yields ``("subst", i, None, quote)`` and ends the scan (the caller
953
+ descends to *end* itself). *naive_backtick* closes a backtick at the next backtick even if
954
+ escaped (the quoted-prose masker's historical behavior)."""
955
+ n = len(text) if end is None else end
956
+ quote: str | None = None
957
+ i = start
958
+ while i < n:
959
+ ch = text[i]
960
+ kind, j = "char", i + 1
961
+ if comments and quote is None and _is_shell_comment_start(text, i):
962
+ kind, j = "comment", text.find("\n", i, n)
963
+ if j < 0:
964
+ j = n
965
+ elif quote != "'" and ch == "\\" and i + 1 < n:
966
+ kind, j = "esc", i + 2
967
+ elif ch == quote or (quote is None and ch in "'\""):
968
+ kind = "quote"
969
+ elif quote != "'" and ("q" if quote else "u") in subst and (
970
+ ch == "`" or text.startswith("$(", i) or (brace and not quote and text.startswith("${", i))
971
+ ):
972
+ if ch == "`":
973
+ close = text.find("`", i + 1) + 1 or None if naive_backtick else _scan_backtick_end(text, i)
974
+ elif text[i + 1] == "(":
975
+ close = _scan_dollar_paren_end(text, i)
976
+ else:
977
+ close = text.find("}", i + 2) + 1 or None
978
+ if close is not None:
979
+ kind, j = "subst", close
980
+ elif stop_unterminated:
981
+ yield ("subst", i, None, quote)
982
+ return
983
+ yield (kind, i, j, quote)
984
+ if kind == "quote":
985
+ quote = None if quote else ch
986
+ i = j
987
+
988
+
989
+ def _scan_dollar_paren_end(command: str, start: int) -> int | None:
990
+ """Return the offset after a balanced ``$(...)`` command substitution."""
991
+ depth = 1
992
+ for kind, i, _, quote in _scan_shell(command, start + 2):
993
+ if kind == "char" and not quote:
994
+ depth += command.startswith("$(", i) - (command[i] == ")")
995
+ if depth == 0:
996
+ return i + 1
997
+ return None
998
+
999
+
1000
+ def _scan_backtick_end(command: str, start: int) -> int | None:
1001
+ # Backticks have no quote awareness: only a backslash escapes the next char.
1002
+ match = re.compile(r"(?:\\.|[^`\\])*`", re.DOTALL).match(command, start + 1)
1003
+ return match.end() if match else None
1004
+
1005
+
1006
+ def _read_shell_word(command: str, pos: int) -> tuple[int, int, str]:
1007
+ """Read one shell word without executing expansions."""
1008
+ start = end = _skip_shell_whitespace(command, pos)
1009
+ for kind, i, j, quote in _scan_shell(command, start, subst="u", brace=True):
1010
+ if kind == "char" and quote is None and (command[i].isspace() or command[i] in ";&|<>()"):
1011
+ break
1012
+ end = j
1013
+ return (start, end, command[start:end])
1014
+
1015
+
1016
+ def _literal_command_substitution_output(script: str) -> str | None:
1017
+ """Resolve tiny literal command substitutions without executing a shell."""
1018
+ try:
1019
+ tokens = shlex.split(script, posix=True)
1020
+ except ValueError:
1021
+ tokens = []
1022
+ if not tokens:
1023
+ return None
1024
+ command, args = tokens[0].lower(), tokens[1:]
1025
+ if command == "echo":
1026
+ while args and re.fullmatch(r"-[nEe]+", args[0]):
1027
+ args = args[1:]
1028
+ elif command != "printf":
1029
+ return None
1030
+ if len(args) == 1 and _SIMPLE_SHELL_LITERAL_RE.fullmatch(args[0]):
1031
+ return args[0]
1032
+ if command == "printf" and len(args) == 2 and args[0] == "%s" and _SIMPLE_SHELL_LITERAL_RE.fullmatch(args[1]):
1033
+ return args[1]
1034
+ return None
1035
+
1036
+
1037
+ def _replace_simple_command_substitutions(word: str) -> str:
1038
+ chars: list[str] = []
1039
+ i = 0
1040
+ while i < len(word):
1041
+ opener = 2 if word.startswith("$(", i) else 1 if word[i] == "`" else 0
1042
+ end = (_scan_dollar_paren_end if opener == 2 else _scan_backtick_end)(word, i) if opener else None
1043
+ replacement = _literal_command_substitution_output(word[i + opener:end - 1]) if end is not None else None
1044
+ if replacement is None:
1045
+ replacement, end = word[i], i + 1
1046
+ chars.append(replacement)
1047
+ i = end
1048
+ return "".join(chars)
1049
+
1050
+
1051
+ def _replace_simple_shell_expansions(word: str) -> str:
1052
+ word = _replace_simple_command_substitutions(word)
1053
+ word = _PARAM_REPLACEMENT_RE.sub(lambda match: match.group("replacement"), word)
1054
+ return _PARAM_DEFAULT_RE.sub(lambda match: match.group("default"), word)
1055
+
1056
+
1057
+ def _strip_shell_word_syntax(word: str) -> str:
1058
+ return "".join(
1059
+ word[i + 1] if kind == "esc" else word[i]
1060
+ for kind, i, _, _ in _scan_shell(word) if kind != "quote"
1061
+ )
1062
+
1063
+
1064
+ def _deobfuscate_shell_word_for_detection(word: str) -> str:
1065
+ """Approximate how shell syntax can spell a command word: collapses quoting/escaping plus
1066
+ simple literal command substitutions in the word itself. Intentionally narrow and non-executing."""
1067
+ for _ in range(2):
1068
+ previous = word
1069
+ word = _strip_shell_word_syntax(_replace_simple_shell_expansions(word))
1070
+ if word == previous:
1071
+ break
1072
+ return word
1073
+
1074
+
1075
+ def _is_shell_comment_start(command: str, index: int) -> bool:
1076
+ return command[index] == "#" and (index == 0 or command[index - 1].isspace()
1077
+ or command[index - 1] in ";&|()<>")
1078
+
1079
+
1080
+ def _iter_shell_command_starts(command: str):
1081
+ starts = [0]
1082
+
1083
+ def scan(start: int, end: int) -> None:
1084
+ skip = -1
1085
+ for kind, i, j, quote in _scan_shell(command, start, end, subst="uq", stop_unterminated=True,
1086
+ comments=True):
1087
+ if kind == "subst":
1088
+ # Record a nested $(...)/backtick command start and scan its body.
1089
+ inner = i + (1 if command[i] == "`" else 2)
1090
+ starts.append(inner)
1091
+ scan(inner, end if j is None else j - 1)
1092
+ elif kind == "char" and quote is None and i != skip:
1093
+ # `${` opens a parameter expansion, not a brace group: a start marked inside it would
1094
+ # split `${IFS}` and defeat the IFS collapse in normalization.
1095
+ if command[i] in "({;\n" and not (command[i] == "{" and i > 0 and command[i - 1] == "$"):
1096
+ starts.append(i + 1)
1097
+ elif command[i] in "&|":
1098
+ repeated = i + 1 < end and command[i + 1] == command[i]
1099
+ skip = i + 1 if repeated else skip
1100
+ starts.append(i + 1 + repeated)
1101
+
1102
+ scan(0, len(command))
1103
+ seen = set()
1104
+ for start in starts:
1105
+ start = _skip_shell_whitespace(command, start)
1106
+ if start >= len(command) or start in seen or _is_shell_comment_start(command, start):
1107
+ continue
1108
+ seen.add(start)
1109
+ yield start
1110
+ _, end, word = _read_shell_word(command, start)
1111
+ if word in _SHELL_COMMAND_TRANSITIONS:
1112
+ starts.append(end)
1113
+
1114
+
1115
+ def _mark_command_starts(command: str, marker: str = "\n") -> str:
1116
+ """Insert *marker* (a newline) before each real (quote-aware) command start.
1117
+ ``\\n`` is already a ``_CMDPOS`` separator, so this exposes subshell ``(cmd)`` and brace-group
1118
+ ``{ cmd; }`` openers — which the flat pattern class omits — to the anchored patterns WITHOUT the
1119
+ quoted-prose false positives that adding ``(`` / ``{`` to ``_CMDPOS`` would cause: starts inside
1120
+ quotes are never produced, so ``--title "block (reboot)"`` is left as-is."""
1121
+ offsets = sorted(o for o in _iter_shell_command_starts(command) if o > 0)
1122
+ return _splice(command, [(o, o, marker) for o in offsets]) if offsets else command
1123
+
1124
+
1125
+ def _mask_quoted_newlines(command: str) -> str:
1126
+ """Replace raw newlines inside single/double quotes with a space (detection-only).
1127
+ A quoted newline is DATA to the shell, yet the flat ``_CMDPOS`` class treats every raw ``\\n``
1128
+ as a command start, so multi-line quoted arguments (commit messages, heredoc text) tripped the
1129
+ hardline blocklist when a data line began with e.g. ``sudo reboot``. Quote tracking mirrors
1130
+ ``_iter_shell_command_starts``. Unquoted newlines pass through and ``_mark_command_starts``
1131
+ still re-inserts newlines at genuine starts; an unclosed quote absorbs following newlines
1132
+ exactly as the shell would, so masking them cannot hide a runnable command."""
1133
+ if "\n" not in command:
1134
+ return command
1135
+ return _mask_quoted_newlines_span(command, 0, len(command))
1136
+
1137
+
1138
+ def _mask_quoted_newlines_span(command: str, start: int, end: int) -> str:
1139
+ """``_mask_quoted_newlines`` over ``command[start:end]``. A ``$(...)`` / backtick substitution
1140
+ inside double quotes is EXECUTABLE, not data: its body is re-scanned with a fresh quote state so a
1141
+ newline that separates commands inside it survives as a command boundary. Masking it as quoted
1142
+ data turned ``"$(grep x f\nreboot)"`` into ``... f reboot)``, which no later stage can tell from an
1143
+ operand; the pre-fix scanner only caught it by refusing the whole command as malformed."""
1144
+ out: list[str] = []
1145
+ for kind, i, j, quote in _scan_shell(command, start, end, subst="q"):
1146
+ if kind == "subst":
1147
+ # j is the index just past the closer; keep the opener and closer, recurse into the body.
1148
+ body_start = i + (2 if command.startswith("$(", i) else 1)
1149
+ body_end = j - 1
1150
+ out.append(command[i:body_start])
1151
+ out.append(_mask_quoted_newlines_span(command, body_start, body_end))
1152
+ out.append(command[body_end:j])
1153
+ elif quote and kind == "char" and command[i] == "\n":
1154
+ out.append(" ")
1155
+ else:
1156
+ out.append(command[i:j])
1157
+ return "".join(out)
1158
+
1159
+
1160
+ def _iter_shell_command_word_spans(command: str):
1161
+ """Yield command-position words that may be executable names."""
1162
+ for pos in _iter_shell_command_starts(command):
1163
+ wrapper, positionals = None, 0
1164
+ options, skip_arg = True, False
1165
+ while pos < len(command):
1166
+ redirect = _SHELL_REDIRECTION_RE.match(command, _skip_shell_whitespace(command, pos))
1167
+ if redirect:
1168
+ _, pos, _ = _read_shell_word(command, redirect.end())
1169
+ continue
1170
+ word_start, word_end, word = _read_shell_word(command, pos)
1171
+ if word_start == word_end:
1172
+ break
1173
+ pos = word_end
1174
+ deobfuscated = _deobfuscate_shell_word_for_detection(word)
1175
+ name = os.path.basename(deobfuscated).lower()
1176
+ if skip_arg:
1177
+ skip_arg = False
1178
+ continue
1179
+ if wrapper and options and deobfuscated == "--":
1180
+ options = False
1181
+ continue
1182
+ if wrapper and options and deobfuscated.startswith("-"):
1183
+ option = deobfuscated.split("=", 1)[0]
1184
+ if wrapper == "env" and (option == "--split-string" or deobfuscated.startswith("-S")):
1185
+ # The split string and remaining argv form ONE command, handled
1186
+ # by _env_split_payload; the suffix is not a new executable.
1187
+ break
1188
+ queries = _COMMAND_WRAPPER_NON_EXECUTING_OPTIONS.get(wrapper, set())
1189
+ if option in queries or (wrapper == "command" and not option.startswith("--")
1190
+ and set(option[1:]) & {"v", "V"}):
1191
+ break
1192
+ skip_arg = "=" not in deobfuscated and option in _COMMAND_WRAPPER_OPTIONS_WITH_ARG.get(wrapper, set())
1193
+ continue
1194
+ if positionals:
1195
+ positionals -= 1
1196
+ continue
1197
+ if _ENV_ASSIGNMENT_RE.fullmatch(word):
1198
+ continue
1199
+ yield (word_start, word_end, word)
1200
+ if name not in _COMMAND_WRAPPER_WORDS:
1201
+ break
1202
+ wrapper, options = name, True
1203
+ positionals = _COMMAND_WRAPPER_POSITIONAL_ARGS.get(name, 0)
1204
+
1205
+
1206
+ def _shell_command_segment(command: str, start: int) -> str:
1207
+ """Bound a candidate to its command, preserving quoted argument bytes."""
1208
+ end = len(command)
1209
+ for kind, i, _, quote in _scan_shell(command, start, subst="uq", brace=True, comments=True):
1210
+ if kind == "comment" or (kind == "char" and quote is None and command[i] in ";&|\n)`"):
1211
+ end = i
1212
+ break
1213
+ return command[start:end].strip()
1214
+
1215
+
1216
+ def _split_env_string(payload: str) -> list[str] | None:
1217
+ r"""Project GNU env -S literal argv, not POSIX shell words.
1218
+
1219
+ Dynamic ${NAME} expansion is deliberately not evaluated: the execution
1220
+ backend's environment need not be this process's environment.
1221
+ """
1222
+ escapes = {"f": "\f", "n": "\n", "r": "\r", "t": "\t", "v": "\v",
1223
+ "#": "#", "$": "$", "\"": "\"", "'": "'", "\\": "\\"}
1224
+ args, word = [], []
1225
+ quote, started, index = None, False, 0
1226
+ while index < len(payload):
1227
+ char = payload[index]
1228
+ index += 1
1229
+ if char == "\\":
1230
+ if index == len(payload):
1231
+ return None
1232
+ escaped = payload[index]
1233
+ if quote == "'" and escaped not in ("'", "\\"):
1234
+ word.append(char)
1235
+ started = True
1236
+ continue
1237
+ index += 1
1238
+ if escaped == "c":
1239
+ if quote:
1240
+ return None
1241
+ break
1242
+ if escaped == "_" and quote is None:
1243
+ if started:
1244
+ args.append("".join(word))
1245
+ word, started = [], False
1246
+ continue
1247
+ if escaped not in escapes and escaped != "_":
1248
+ return None
1249
+ word.append(" " if escaped == "_" else escapes[escaped])
1250
+ started = True
1251
+ continue
1252
+ if char in ("'", '"') and (quote is None or char == quote):
1253
+ quote = char if quote is None else None
1254
+ started = True
1255
+ continue
1256
+ if quote is None and char in " \t\n\r\v\f":
1257
+ if started:
1258
+ args.append("".join(word))
1259
+ word, started = [], False
1260
+ continue
1261
+ if quote is None and char == "#" and not started:
1262
+ break
1263
+ if char == "$" and quote != "'":
1264
+ return None
1265
+ word.append(char)
1266
+ started = True
1267
+ if quote:
1268
+ return None
1269
+ if started:
1270
+ args.append("".join(word))
1271
+ return args
1272
+
1273
+
1274
+ def _env_split_payload(tokens: list[str]) -> str | None:
1275
+ index = 1
1276
+ while index < len(tokens):
1277
+ token = tokens[index]
1278
+ if token == "--" or not token.startswith("-"):
1279
+ return None
1280
+ option, equals, value = token.partition("=")
1281
+ if option == "--split-string" or token.startswith("-S"):
1282
+ attached = equals if option == "--split-string" else len(token) > 2
1283
+ if not attached:
1284
+ index += 1
1285
+ payload = (value if option == "--split-string" else token[2:]) if attached else (
1286
+ tokens[index] if index < len(tokens) else "")
1287
+ args = _split_env_string(payload)
1288
+ # Protect literal separators when reusing command-position detection;
1289
+ # only a real shell -c carrier may turn these argv bytes into code.
1290
+ return shlex.join(args + tokens[index + 1:]) if args is not None else None
1291
+ index += 2 if not equals and option in _COMMAND_WRAPPER_OPTIONS_WITH_ARG["env"] else 1
1292
+ return None
1293
+
1294
+
1295
+ def _deny_command_variants(command: str):
1296
+ """Add executable projections without reparsing normalized argument data.
1297
+
1298
+ Whole-input matching is retained for existing globs. New projections parse
1299
+ the original quote state, preserve path-specific rules, and fold only the
1300
+ executable basename (never arbitrary argument paths).
1301
+ """
1302
+ yield from _command_detection_variants(command)
1303
+ pending, seen = [command], set()
1304
+ while pending:
1305
+ source = pending.pop()
1306
+ if source in seen:
1307
+ continue
1308
+ seen.add(source)
1309
+ for start, end, word in _iter_shell_command_word_spans(source):
1310
+ segment = _shell_command_segment(source, start)
1311
+ executable = _deobfuscate_shell_word_for_detection(word)
1312
+ tail = segment[end - start:]
1313
+ # Collapse only unquoted inter-word whitespace; quoted prose is data.
1314
+ parts = []
1315
+ for kind, i, j, quote in _scan_shell(tail):
1316
+ if kind == "char" and quote is None and tail[i].isspace():
1317
+ if not parts or parts[-1] != " ":
1318
+ parts.append(" ")
1319
+ else:
1320
+ parts.append(tail[i:j])
1321
+ tail = "".join(parts)
1322
+ for name in dict.fromkeys((executable, os.path.basename(executable))):
1323
+ candidate = name + tail
1324
+ yield candidate
1325
+ # Apply the existing text matching semantics only AFTER locating
1326
+ # executable positions; never parse its rewritten quotes again.
1327
+ yield _normalize_command_for_detection(candidate)
1328
+ if os.path.basename(executable) == "env":
1329
+ tokens = _shell_segment_tokens(segment, 0)
1330
+ if tokens:
1331
+ payload = _env_split_payload(tokens)
1332
+ if payload:
1333
+ pending.append(payload)
1334
+ for _, payload in _execution_flag_findings(source):
1335
+ if payload:
1336
+ pending.append(payload)
1337
+
1338
+
1339
+ def _command_detection_variants(command: str):
1340
+ # Mask quoted newlines BEFORE normalization: normalization strips escapes (\" -> ") and ""
1341
+ # pairs, corrupting quote tracking (`echo "a\""` becomes an unterminated quote) so masking
1342
+ # afterwards could swallow a REAL unquoted newline separator. The raw command carries faithful quote state.
1343
+ normalized = _normalize_command_for_detection(_mask_quoted_newlines(command))
1344
+ # Quote-aware grep parsing hides only structurally identified pattern operands; malformed or
1345
+ # ambiguous input stays byte-for-byte intact.
1346
+ grep_safe, _ = _grep_safe_detection_variant(normalized)
1347
+ seen = {grep_safe}
1348
+ yield grep_safe
1349
+
1350
+ def fresh(variant: str) -> bool:
1351
+ if not variant or variant in seen:
1352
+ return False
1353
+ seen.add(variant)
1354
+ return True
1355
+
1356
+ # Windows-path variant: normalization strips backslashes as shell escapes, so `del C:\Users\me\.ssh\id_rsa`
1357
+ # reaches the patterns as `del C:Usersme.sshid_rsa`. When the RAW command has a drive-letter or UNC backslash
1358
+ # path, also yield a variant with backslashes flattened to `/` BEFORE normalization. Gated on a real path shape so
1359
+ # POSIX escape semantics (`echo a\"b`) are untouched elsewhere.
1360
+ # See #69472.
1361
+ if re.search(r"(?:[A-Za-z]:|\\\\)[\\\\]", command) or re.search(r"[A-Za-z]:\\", command):
1362
+ win_variant = _normalize_command_for_detection(_mask_quoted_newlines(command.replace("\\", "/")))
1363
+ if fresh(win_variant):
1364
+ yield win_variant
1365
+ # Program-bearing options are parsed in their owning command's context; surfacing only the payload lets the
1366
+ # hardline floor inspect what will actually run without promoting similar flags or quoted prose.
1367
+ pending = [normalized]
1368
+ while pending:
1369
+ for _, payload in _execution_flag_findings(pending.pop()):
1370
+ if fresh(payload):
1371
+ yield payload
1372
+ # A payload may start with an option-looking program and then invoke a hardline command
1373
+ # after a separator; mark its starts.
1374
+ marked_payload = _mark_command_starts(payload)
1375
+ if marked_payload != payload and fresh(marked_payload):
1376
+ yield marked_payload
1377
+ pending.append(payload)
1378
+ # Subshell `(cmd)` / brace-group `{ cmd; }` openers put `cmd` at a real command position the flat `_CMDPOS`
1379
+ # patterns can't see (adding `(`/`{` there would match quoted prose like `--title "(reboot)"`). Insert a newline
1380
+ # at each start the QUOTE-AWARE tokenizer found instead; this covers every `_CMDPOS` rule in one place.
1381
+ marked = _mark_command_starts(grep_safe)
1382
+ if marked != grep_safe and fresh(marked):
1383
+ yield marked
1384
+ # Every variant above tracks quotes on NORMALIZED text, where `\"` has already become `"`. That
1385
+ # flips quote parity, so in `cat "f\"n.txt"; rm -rf /` the `; rm` start sat "inside" a phantom
1386
+ # quote, no start was marked, and the hardline floor let it through. Mark starts on the RAW
1387
+ # command (only quoted newlines masked), then normalize; the leading space keeps the marker
1388
+ # from being eaten as a `\<newline>` continuation when the preceding text ends in a backslash.
1389
+ faithful = _normalize_command_for_detection(_mark_command_starts(_mask_quoted_newlines(command), marker=" \n"))
1390
+ if fresh(faithful):
1391
+ yield faithful
1392
+ # Quoting/escaping can spell an executable in pieces (r\m, r''m). Keep that deobfuscation scoped
1393
+ # to command words so arguments don't false-positive.
1394
+ for word_start, word_end, word in _iter_shell_command_word_spans(normalized):
1395
+ deobfuscated = _deobfuscate_shell_word_for_detection(word)
1396
+ if deobfuscated and deobfuscated != word:
1397
+ variant = normalized[:word_start] + deobfuscated + normalized[word_end:]
1398
+ if fresh(variant):
1399
+ yield variant
1400
+
1401
+
1402
+ def _is_verification_artifact_cleanup(command: str) -> bool:
1403
+ """Return whether *command* only removes one Hermes ad-hoc temp script."""
1404
+ try:
1405
+ argv = shlex.split(command, posix=True)
1406
+ except ValueError:
1407
+ return False
1408
+ if len(argv) != 3 or argv[0] != "rm" or argv[1] != "-f":
1409
+ return False
1410
+ operand = argv[2]
1411
+ temp_dir = os.path.realpath(tempfile.gettempdir())
1412
+ basename = os.path.basename(operand)
1413
+ return (
1414
+ operand == os.path.join(temp_dir, basename)
1415
+ and os.path.dirname(os.path.realpath(operand)) == temp_dir
1416
+ and re.fullmatch(r"hermes-(?:verify|ad-hoc)-[A-Za-z0-9_.-]+", basename) is not None
1417
+ )
1418
+
1419
+
1420
+ def _is_shell_token_spliced_gateway_lifecycle(command: str) -> bool:
1421
+ """Catch gateway-lifecycle verbs spelled with quote splicing.
1422
+ Backslash splicing (``kick\\start``) is undone by normalization, but quote splicing is not:
1423
+ ``_deobfuscate_shell_word_for_detection`` is deliberately scoped to command-position words
1424
+ (widening it would let quoted prose like ``git commit -m "rm -rf /"`` match), and the spliced
1425
+ verb is an ARGUMENT, so ``launchctl kick"start" -k gui/501/ai.hermes.gateway`` auto-approved.
1426
+ Delegates to ``cron.lifecycle_guard`` (shlex-tokenized, anchored on a hermes-gateway
1427
+ identifier). Runs last so an ordinary pattern match keeps its more specific reason; this layer
1428
+ only prompts — the non-bypassable block still lives in ``cron.lifecycle_guard``.
1429
+
1430
+ ``_normalize_command_for_detection`` strips backslash escapes, so ``kick\\start`` already reaches the
1431
+ launchctl pattern above. See #80269.
1432
+ """
1433
+ try:
1434
+ from cron.lifecycle_guard import contains_gateway_lifecycle_command
1435
+ except Exception:
1436
+ return False
1437
+ return contains_gateway_lifecycle_command(command)
1438
+
1439
+
1440
+ def detect_dangerous_command(command: str) -> tuple:
1441
+ """Check dangerous patterns -> (is_dangerous, pattern_key, description)."""
1442
+ if _command_parser_limit_exceeded(command):
1443
+ return (True, _PARSER_LIMIT_DESCRIPTION, _PARSER_LIMIT_DESCRIPTION)
1444
+ if _is_verification_artifact_cleanup(command):
1445
+ return (False, None, None)
1446
+ for command_variant in _command_detection_variants(command):
1447
+ command_lower = command_variant.lower()
1448
+ for pattern_re, description in DANGEROUS_PATTERNS_COMPILED:
1449
+ if pattern_re.search(command_lower):
1450
+ return (True, description, description)
1451
+ normalized = _normalize_command_for_detection(command)
1452
+ for description, _ in _execution_flag_findings(normalized):
1453
+ return (True, description, description)
1454
+ if _is_shell_token_spliced_gateway_lifecycle(command):
1455
+ return (True, _GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION, _GATEWAY_LIFECYCLE_SPLICE_DESCRIPTION)
1456
+ return (False, None, None)
tools/approval_human_wait.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Human-wait accounting for :mod:`tools.approval` (per session).
2
+
3
+ Tracks wall-clock time the agent spends verifiably blocked on a HUMAN prompt
4
+ (CLI approval prompt, gateway approval round-trip). The concurrent tool batch
5
+ deadline in agent/tool_executor.py excludes this time so a slow human answer
6
+ never times a batch out — but ONLY this time. Measuring at the source (rather
7
+ than residency in the authorization gate, which is arbitrary code) is what keeps
8
+ a wedged pre_tool_call plugin or a dead approval client from growing the
9
+ exclusion 1:1 with wall clock and defeating the deadline entirely. Keyed by
10
+ session so one gateway session's pending approval cannot extend a different
11
+ session's batch deadline; state is process-global like the rest of the approval
12
+ state, bounded by _HUMAN_WAIT_MAX_SESSIONS.
13
+ """
14
+
15
+ import contextlib
16
+ import threading
17
+ import time
18
+
19
+
20
+ # ========================================================================= Human-wait accounting (per
21
+ # session) ========================================================================= Tracks the wall-clock
22
+ # time the agent spends verifiably blocked on a HUMAN prompt (CLI approval prompt, gateway approval
23
+ # round-trip). The concurrent tool batch deadline in agent/tool_executor.py excludes this time so a slow
24
+ # human answer never times a batch out — but ONLY this time. Measuring human waits at the source (rather
25
+ # than residency in the authorization gate, which is arbitrary code) is what keeps a wedged pre_tool_call
26
+ # plugin or a dead approval client from growing the exclusion 1:1 with wall clock and defeating the deadline
27
+ # entirely (#79719). Keyed by session so one gateway session's pending approval cannot extend a different
28
+ # session's batch deadline. State is process-global like the rest of this module's approval state; entries
29
+ # are bounded by _HUMAN_WAIT_MAX_SESSIONS.
30
+ class _HumanWaitState:
31
+ __slots__ = ("pending", "window_started", "completed_seconds")
32
+
33
+ def __init__(self) -> None:
34
+ self.pending = 0
35
+ self.window_started: float | None = None
36
+ self.completed_seconds = 0.0
37
+
38
+
39
+ _human_wait_lock = threading.Lock()
40
+ _human_wait_states: dict[str, _HumanWaitState] = {}
41
+ _HUMAN_WAIT_MAX_SESSIONS = 256
42
+ # Margin added on top of approvals.timeout when clamping a window's contribution (read-side AND close-side) and when
43
+ # bounding the authorization gate's serialization-lock acquire in agent/tool_executor.py. One constant so the clamps
44
+ # can't drift apart.
45
+ HUMAN_WAIT_MARGIN_S = 60.0
46
+
47
+
48
+ def human_wait_ceiling() -> float:
49
+ """Max seconds a single window may contribute: approvals.timeout + margin.
50
+ Every legitimate human wait self-terminates at ``approvals.timeout`` (the CLI
51
+ prompt join and the gateway poll loop both enforce it), so a window that
52
+ overstays this ceiling is itself wedged and must not keep extending a batch
53
+ deadline. Also the bound on the authorization gate's serialization-lock
54
+ acquire in agent/tool_executor.py, so the two cannot drift. Never call while
55
+ holding ``_human_wait_lock`` — it reads the config cache.
56
+ ``_get_approval_timeout`` caps at ``agent.deadline.MAX_SAFE_TIMEOUT_S`` so the
57
+ value is always safe for ``Lock.acquire(timeout=...)`` / ``Thread.join(timeout=...)``."""
58
+ from tools import approval_context
59
+ return float(approval_context._get_approval_timeout()) + HUMAN_WAIT_MARGIN_S
60
+
61
+
62
+ def _clamped_window_seconds(started: float, now: float, ceiling: float) -> float:
63
+ """Seconds an open window contributes: elapsed, floored at 0, capped. Shared
64
+ by the close-time accrual and the open-window read so the two clamps stay
65
+ identical by construction."""
66
+ return min(max(0.0, now - started), ceiling)
67
+
68
+
69
+ def _human_wait_state(session_key: str) -> _HumanWaitState:
70
+ """Return (creating if needed) the wait state for *session_key*. Caller must
71
+ hold ``_human_wait_lock``. Evicts idle entries (no pending waiter)
72
+ insertion-order-first until the table is under the cap so an army of
73
+ short-lived session keys cannot grow it without bound. Entries with an open
74
+ window are never evicted (that would corrupt live accounting), so the cap is
75
+ best-effort under 256+ concurrently-pending sessions."""
76
+ state = _human_wait_states.get(session_key)
77
+ if state is None:
78
+ for key in list(_human_wait_states):
79
+ if len(_human_wait_states) < _HUMAN_WAIT_MAX_SESSIONS:
80
+ break
81
+ if _human_wait_states[key].pending == 0:
82
+ del _human_wait_states[key]
83
+ state = _human_wait_states[session_key] = _HumanWaitState()
84
+ return state
85
+
86
+
87
+ def _resolve_key(session_key: str | None) -> str:
88
+ if session_key is not None:
89
+ return session_key
90
+ from tools import approval_context
91
+ return approval_context.get_current_session_key()
92
+
93
+
94
+ def activity_heartbeat(label: str):
95
+ """Callable that pings the agent's inactivity tracker (at most every ~10s)
96
+ while a human wait is parked, so the gateway watchdog does not kill the agent
97
+ while the user is still answering. No-op in minimal tool-only environments."""
98
+ try:
99
+ from tools.environments.base import touch_activity_if_due
100
+ except Exception: # pragma: no cover - minimal tool-only environments
101
+ return lambda: None
102
+ now = time.monotonic()
103
+ state = {"last_touch": now, "start": now}
104
+ return lambda: touch_activity_if_due(state, label)
105
+
106
+
107
+ @contextlib.contextmanager
108
+ def human_wait_window(session_key: str | None = None):
109
+ """Mark the enclosed block as time spent blocked on a human prompt. Wrap ONLY
110
+ code that is genuinely parked waiting for a user's answer (the CLI approval
111
+ prompt, the gateway approval poll loop). The concurrent tool batch deadline
112
+ excludes this time; wrapping anything else re-creates the hang where
113
+ arbitrary wedged code pushes the deadline out forever. Overlapping windows
114
+ for the same session coalesce (pending counter), so two serialized approval
115
+ prompts don't double-count the same wall clock.
116
+
117
+ See #79719.
118
+ """
119
+ key = _resolve_key(session_key)
120
+ now = time.monotonic()
121
+ with _human_wait_lock:
122
+ state = _human_wait_state(key)
123
+ if state.pending == 0:
124
+ state.window_started = now
125
+ state.pending += 1
126
+ try:
127
+ yield
128
+ finally:
129
+ now = time.monotonic()
130
+ # Clamp the accrual too: a window that overstayed the ceiling was wedged —
131
+ # record at most the ceiling, not the whole overstay.
132
+ ceiling = human_wait_ceiling()
133
+ with _human_wait_lock:
134
+ state = _human_wait_states.get(key)
135
+ if state is not None:
136
+ state.pending -= 1
137
+ if state.pending == 0:
138
+ if state.window_started is not None:
139
+ state.completed_seconds += _clamped_window_seconds(state.window_started, now, ceiling)
140
+ state.window_started = None
141
+
142
+
143
+ def human_wait_seconds(session_key: str | None = None) -> float:
144
+ """Return total human-wait seconds recorded for the session: completed windows
145
+ plus the currently open one (if any). Monotonically non-decreasing for the
146
+ life of the process — except when an idle session's entry is evicted under
147
+ cap pressure, which can only shrink a consumer's baseline delta to zero (the
148
+ safe direction: the deadline fires sooner). Deadline consumers snapshot a
149
+ baseline at batch start and use the delta. Each window's contribution is
150
+ clamped to :func:`human_wait_ceiling` (belt-and-braces against the
151
+ wedged-window hang).
152
+
153
+ Each window's contribution is clamped to :func:`human_wait_ceiling`: every legitimate human wait
154
+ self-terminates at ``approvals.timeout`` (both the CLI prompt join and the gateway poll loop enforce
155
+ it), so a window that overstays that bound is itself wedged and must not keep extending a batch deadline
156
+ (belt-and-braces for #79719).
157
+ """
158
+ key = _resolve_key(session_key)
159
+ now = time.monotonic()
160
+ # Resolve the clamp outside the lock: it reads the config cache, which must never nest under _human_wait_lock.
161
+ ceiling = human_wait_ceiling()
162
+ with _human_wait_lock:
163
+ state = _human_wait_states.get(key)
164
+ if state is None:
165
+ return 0.0
166
+ total = state.completed_seconds
167
+ if state.window_started is not None:
168
+ total += _clamped_window_seconds(state.window_started, now, ceiling)
169
+ return total
tools/async_delegation.py ADDED
@@ -0,0 +1,1003 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Async (background) delegation registry behind ``delegate_task(background=true)``.
3
+
4
+ The parent dispatches a subagent on a module-level daemon executor and returns a handle
5
+ immediately. On completion a ``type="async_delegation"`` event (self-contained task-source
6
+ block) is pushed onto the SHARED ``process_registry.completion_queue`` the CLI/gateway drain
7
+ while idle, so results surface as a NEW turn (never mid-turn) and inherit its de-dup and
8
+ crash-recovery wiring. Only the async lifecycle lives here; the child run is an injected ``runner``."""
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import logging
14
+ import os
15
+ import sqlite3
16
+ import threading
17
+ import time
18
+ import uuid
19
+ from concurrent.futures import ThreadPoolExecutor
20
+ from typing import Any, Callable, Dict, List, Optional
21
+
22
+ from hermes_constants import get_hermes_home
23
+ from tools.daemon_pool import DaemonThreadPoolExecutor
24
+ from tools.thread_context import propagate_context_to_thread
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ # ── Module-level state ──────────────────────────────────────────────────────
29
+ # Persistent daemon executor (never a `with ThreadPoolExecutor()` block, which
30
+ # would join on exit and defeat async); daemon workers can't hang a hard exit.
31
+ _executor: Optional[ThreadPoolExecutor] = None
32
+ _executor_lock = threading.Lock()
33
+ _executor_max_workers: int = 0
34
+
35
+ _records_lock = threading.Lock()
36
+ # delegation_id -> record dict; kept for the run plus a short completed tail.
37
+ _records: Dict[str, Dict[str, Any]] = {}
38
+
39
+ _DEFAULT_MAX_ASYNC_CHILDREN = 3
40
+ # Completed records retained (in memory and in the ledger) for status queries.
41
+ _MAX_RETAINED_COMPLETED = 50
42
+ _DURABLE_RETENTION_SECONDS = 7 * 24 * 60 * 60
43
+ _MAX_DURABLE_PENDING = 1000
44
+ # Cap retried deliveries so an unroutable row converges to terminal 'dropped'.
45
+ _MAX_DELIVERY_ATTEMPTS = 8
46
+ # Pending completions older than this are dropped on restart replay instead of
47
+ # re-run as a full-context turn; 48h keeps weekend results deliverable.
48
+ _MAX_COMPLETION_REPLAY_AGE_S = 48 * 3600.0
49
+ _DB_LOCK = threading.Lock()
50
+
51
+ # ── Stale-delegation detection (progress-based, on by default) ──────────────
52
+ # A runner wedged before returning never reaches its finalizer, so it would show
53
+ # "dispatched" forever. No wall-clock timeout (heavy work must never be killed for
54
+ # taking long): one monitor thread samples per-dispatch PROGRESS via an injected
55
+ # ``progress_fn``; a frozen child is interrupted, given a grace window to unwind via
56
+ # the normal finalize path, and only force-finalized (terminal ``stalled`` event) if
57
+ # it never returns. Thresholds mirror delegate_tool's sync heartbeat monitor.
58
+ _STALE_CHECK_INTERVAL = 30.0
59
+ _STALE_IDLE_SECONDS = 450.0
60
+ _STALE_IN_TOOL_SECONDS = 1200.0
61
+ _STALL_GRACE_SECONDS = 120.0
62
+
63
+ _monitor_lock = threading.Lock()
64
+ _monitor_thread: Optional[threading.Thread] = None
65
+ _monitor_stop = threading.Event()
66
+
67
+ _LIVE_STATES = {"running", "stalling", "finalizing"}
68
+ _ACTIVE_STATES = ("running", "stalling")
69
+ # Routing origin persisted at dispatch so a restart-recovered completion can
70
+ # reconstruct a full SessionSource (scope_id drives relay tenant egress).
71
+ _ROUTING_KEYS = ("scope_id", "user_id", "user_name")
72
+ # Structured stall metadata — additive, present only on stall finalizations.
73
+ _STALL_META_KEYS = ("stalled_after_quiet_seconds", "stall_threshold_seconds", "stall_phase", "stall_grace_seconds")
74
+ # Private stall bookkeeping on the record -> public field in list_async_delegations().
75
+ _STALL_FIELD_MAP = (("_stall_quiet_seconds", "stalled_after_quiet_seconds"),
76
+ ("_stall_threshold_seconds", "stall_threshold_seconds"), ("_stall_in_tool", "stall_in_tool"))
77
+
78
+
79
+ # ── Durable ledger (state.db / async_delegations) ───────────────────────────
80
+ def _db_path():
81
+ return get_hermes_home() / "state.db"
82
+
83
+
84
+ def _connect() -> sqlite3.Connection:
85
+ from hermes_cli.sqlite_util import open_db
86
+ # Same state.db as hermes_state.SessionDB -- reuse its owner-only (0600)
87
+ # hardening so this writer doesn't create/leave the file (and its WAL
88
+ # sidecars) at the process umask. See hermes_state._secure_state_db_files.
89
+ from hermes_state import _secure_state_db_files
90
+
91
+ path = _db_path()
92
+ path.parent.mkdir(parents=True, exist_ok=True)
93
+ _secure_state_db_files(path, create_main=True)
94
+ # wal=False: SessionDB owns state.db's journal mode (_initialize_schema applies the barriers).
95
+ conn = open_db(path, db_label="state.db (async_delegation)", busy_timeout_ms=10_000,
96
+ wal=False, row_factory=None, initialize=_initialize_schema)
97
+ _secure_state_db_files(path)
98
+ return conn
99
+
100
+
101
+ def _initialize_schema(conn: sqlite3.Connection) -> None:
102
+ from hermes_state_repair import apply_durability_barriers
103
+ from hermes_state_schema import reconcile_state_schema
104
+ # Preserve the journal mode SessionDB configured on state.db: forcing WAL from
105
+ # every short-lived connection collides with live transcript/FTS writers.
106
+ apply_durability_barriers(conn)
107
+ # Single durable-shape authority: the canonical SCHEMA_SQL drives both
108
+ # table creation and column backfill (reconcile_state_schema replays the
109
+ # canonical DDL and reuses SessionDB's declarative reconciliation). This
110
+ # module previously carried its own CREATE TABLE + ALTER column list,
111
+ # which drifted from SCHEMA_SQL — same-name columns with different
112
+ # nullability/defaults depending on which authority touched the database
113
+ # first (#94691).
114
+ reconcile_state_schema(conn)
115
+
116
+
117
+ def _transaction():
118
+ from hermes_cli.sqlite_util import transaction
119
+
120
+ return transaction(_connect())
121
+
122
+
123
+ def _capture_routing_origin() -> Dict[str, Any]:
124
+ """Snapshot scope_id/user_id/user_name on the PARENT thread (the daemon worker
125
+ has no contextvars) so a restart-replayed completion can rebuild a SessionSource.
126
+ Best-effort: empty values are omitted."""
127
+ try:
128
+ from gateway.session_context import get_session_env
129
+ return {k: v for k in _ROUTING_KEYS if (v := get_session_env(f"HERMES_SESSION_{k.upper()}", ""))}
130
+ except Exception: # noqa: BLE001 - routing origin is additive, never fatal
131
+ return {}
132
+
133
+
134
+ def _persist_dispatch(record: Dict[str, Any]) -> None:
135
+ now = time.time()
136
+ try:
137
+ from gateway.status import get_process_start_time
138
+ owner_started_at = get_process_start_time(os.getpid())
139
+ except Exception:
140
+ owner_started_at = None
141
+ task_payload = {
142
+ key: record.get(key)
143
+ for key in ("goal", "goals", "context", "toolsets", "role", "model", "is_batch", "task_indexes", *_ROUTING_KEYS)
144
+ if key in record}
145
+ with _DB_LOCK, _transaction() as conn:
146
+ conn.execute("""INSERT OR REPLACE INTO async_delegations
147
+ (delegation_id, origin_session, origin_ui_session_id,
148
+ parent_session_id, state, dispatched_at, updated_at,
149
+ delivery_state, delivery_attempts, owner_pid,
150
+ owner_started_at, task_json, origin_session_id)
151
+ VALUES (?, ?, ?, ?, 'running', ?, ?, 'pending', 0, ?, ?, ?, ?)""",
152
+ (record["delegation_id"], record.get("session_key", ""), record.get("origin_ui_session_id", ""),
153
+ record.get("parent_session_id"), record["dispatched_at"], now, os.getpid(), owner_started_at,
154
+ json.dumps(task_payload), record.get("origin_session_id", "")))
155
+ _prune_durable_records()
156
+
157
+
158
+ def _prune_durable_records() -> None:
159
+ """Bound terminal history, preferring delivered records for deletion."""
160
+ cutoff = time.time() - _DURABLE_RETENTION_SECONDS
161
+ with _DB_LOCK, _transaction() as conn:
162
+ conn.execute(
163
+ "DELETE FROM async_delegations WHERE delivery_state='delivered' AND updated_at < ?", (cutoff,))
164
+ terminal_count = conn.execute(
165
+ "SELECT COUNT(*) FROM async_delegations WHERE state NOT IN ('running','finalizing')").fetchone()[0]
166
+ if terminal_count > _MAX_RETAINED_COMPLETED:
167
+ conn.execute("""DELETE FROM async_delegations WHERE delegation_id IN (
168
+ SELECT delegation_id FROM async_delegations
169
+ WHERE state NOT IN ('running','finalizing')
170
+ ORDER BY CASE delivery_state WHEN 'delivered' THEN 0 ELSE 1 END,
171
+ updated_at ASC LIMIT ?
172
+ )""", (terminal_count - _MAX_RETAINED_COMPLETED,))
173
+ pending_count = conn.execute("""SELECT COUNT(*) FROM async_delegations
174
+ WHERE state NOT IN ('running','finalizing') AND delivery_state='pending'""").fetchone()[0]
175
+ if pending_count > _MAX_DURABLE_PENDING:
176
+ conn.execute("""DELETE FROM async_delegations WHERE delegation_id IN (
177
+ SELECT delegation_id FROM async_delegations
178
+ WHERE state NOT IN ('running','finalizing') AND delivery_state='pending'
179
+ ORDER BY updated_at ASC LIMIT ?
180
+ )""", (pending_count - _MAX_DURABLE_PENDING,))
181
+
182
+
183
+ def _persist_completion(event: Dict[str, Any], result: Dict[str, Any]) -> None:
184
+ now = time.time()
185
+ with _DB_LOCK, _transaction() as conn:
186
+ conn.execute("""UPDATE async_delegations SET state=?, completed_at=?, updated_at=?,
187
+ event_json=?, result_json=?, delivery_state='pending'
188
+ WHERE delegation_id=?""",
189
+ (event.get("status", "completed"), event.get("completed_at", now), now,
190
+ json.dumps(event), json.dumps(result), event["delegation_id"]))
191
+
192
+
193
+ def record_unit_child(delegation_id: str, entry: Dict[str, Any]) -> None:
194
+ """Durably record ONE finished child of a still-running multi-child unit on the unit's own row, so a crash before
195
+ the unit joins loses only the children that had not finished. Stored in ``result_json`` (overwritten by the real
196
+ result at finalize); ``recover_abandoned_delegations`` replays it. Best-effort: a failed write costs recovery
197
+ fidelity, never the live result."""
198
+ try:
199
+ with _DB_LOCK, _transaction() as conn:
200
+ row = conn.execute("SELECT result_json FROM async_delegations WHERE delegation_id=? AND state='running'",
201
+ (delegation_id,)).fetchone()
202
+ if row is None:
203
+ return
204
+ partial = json.loads(row[0] or "{}") or {}
205
+ results = [r for r in partial.get("results") or [] if r.get("task_index") != entry.get("task_index")]
206
+ results.append(entry)
207
+ conn.execute("UPDATE async_delegations SET result_json=?, updated_at=? WHERE delegation_id=? AND state='running'",
208
+ (json.dumps({"results": results, "partial": True}), time.time(), delegation_id))
209
+ except Exception: # noqa: BLE001 — recovery bookkeeping must never fail a live child
210
+ logger.warning("Async delegation %s: could not record finished child %s", delegation_id, entry.get("task_index"), exc_info=True)
211
+
212
+
213
+ def _recovered_results(task: Dict[str, Any], result_json: Optional[str], error: str) -> Optional[List[Dict[str, Any]]]:
214
+ """Per-task results for an abandoned unit: recorded children as they finished, the rest ``unknown``."""
215
+ partial = json.loads(result_json or "{}") or {}
216
+ if not (task.get("is_batch") and partial.get("partial") and partial.get("results")):
217
+ return None
218
+ recorded = {r["task_index"]: r for r in partial["results"] if isinstance(r.get("task_index"), int)}
219
+ indexes = task.get("task_indexes") or list(range(len(task.get("goals") or [])))
220
+ return [recorded.get(i) or {"task_index": i, "status": "unknown", "summary": None, "error": error} for i in indexes]
221
+
222
+
223
+ def recover_abandoned_delegations() -> int:
224
+ """Classify records whose owning process disappeared as outcome unknown; children a multi-child unit had already
225
+ recorded (``record_unit_child``) are replayed with their real results."""
226
+ try:
227
+ from gateway.status import _pid_exists, get_process_start_time
228
+ except Exception:
229
+ return 0
230
+ now, recovered = time.time(), 0
231
+ with _DB_LOCK, _transaction() as conn:
232
+ rows = conn.execute("""SELECT delegation_id, origin_session, origin_ui_session_id,
233
+ parent_session_id, dispatched_at, owner_pid,
234
+ owner_started_at, task_json, origin_session_id, result_json
235
+ FROM async_delegations WHERE state IN ('running','finalizing')""").fetchall()
236
+ for row in rows:
237
+ delegation_id, session_key, origin_ui, parent_id, dispatched_at, pid, started, task_json, origin_sid, result_json = row
238
+ if pid and _pid_exists(int(pid)) and (started is None or get_process_start_time(int(pid)) == int(started)):
239
+ continue
240
+ task = json.loads(task_json or "{}")
241
+ error = "Delegation owner exited before recording a terminal result; outcome unknown."
242
+ recovered_results = _recovered_results(task, result_json, error)
243
+ if recovered_results:
244
+ done = sum(1 for r in recovered_results if r.get("status") != "unknown")
245
+ error = (f"Delegation owner exited before the unit finished; {done}/{len(recovered_results)} child "
246
+ "results were recorded and are included below, the rest are unknown.")
247
+ event = {
248
+ "type": "async_delegation", "delegation_id": delegation_id, "session_key": session_key,
249
+ "origin_ui_session_id": origin_ui, "origin_session_id": origin_sid or "",
250
+ "parent_session_id": parent_id, "goal": task.get("goal", ""), "goals": task.get("goals"),
251
+ "context": task.get("context"), "toolsets": task.get("toolsets"), "role": task.get("role"),
252
+ "model": task.get("model"), "is_batch": bool(task.get("is_batch")),
253
+ "status": "unknown", "summary": None, "error": error,
254
+ **({"results": recovered_results} if recovered_results else {}),
255
+ "dispatched_at": dispatched_at, "completed_at": now,
256
+ **{k: task[k] for k in _ROUTING_KEYS if task.get(k)}}
257
+ result = {"status": "unknown", "summary": None, "error": event["error"],
258
+ **({"results": recovered_results} if recovered_results else {})}
259
+ conn.execute("""UPDATE async_delegations SET state='unknown', completed_at=?,
260
+ updated_at=?, event_json=?, result_json=?, delivery_state='pending'
261
+ WHERE delegation_id=?""", (now, now, json.dumps(event), json.dumps(result), delegation_id))
262
+ recovered += 1
263
+ return recovered
264
+
265
+
266
+ def restore_undelivered_completions(target_queue) -> int:
267
+ """Enqueue durable pending completions as fresh turns after process start.
268
+ Restored events are stamped ``restored=True`` in memory only: they came from a PREVIOUS
269
+ process, so drains without an ownership filter must leave them for a consumer that can
270
+ prove ownership. Rows older than ``_MAX_COMPLETION_REPLAY_AGE_S`` are terminally dropped
271
+ instead of replaying a turn nobody is waiting on.
272
+
273
+ Every restored event is stamped ``restored=True`` (in-memory only — the stamp is added after the durable
274
+ payload is deserialized and is never persisted). Restored events originate from a *previous* process, so
275
+ no consumer in THIS process implicitly owns them: drain paths that run without an ownership filter (the
276
+ legacy single-session behavior) must leave them queued for a consumer that can positively prove
277
+ ownership, otherwise a brand-new session adopts a dead session's delegation results seconds after boot
278
+ (#64484).
279
+ """
280
+ recover_abandoned_delegations()
281
+ now, restored = time.time(), 0
282
+ with _DB_LOCK, _transaction() as conn:
283
+ rows = conn.execute("""SELECT delegation_id, event_json, completed_at, dispatched_at
284
+ FROM async_delegations
285
+ WHERE state != 'running' AND delivery_state='pending' AND event_json IS NOT NULL
286
+ ORDER BY completed_at, delegation_id""").fetchall()
287
+ for delegation_id, payload, completed_at, dispatched_at in rows:
288
+ age_basis = completed_at or dispatched_at
289
+ if age_basis and (now - age_basis) > _MAX_COMPLETION_REPLAY_AGE_S:
290
+ conn.execute("""UPDATE async_delegations SET delivery_state='dropped',
291
+ delivery_claim=NULL, delivery_claimed_at=NULL,
292
+ updated_at=?
293
+ WHERE delegation_id=? AND delivery_state='pending'""", (now, delegation_id))
294
+ logger.warning("Async delegation %s: pending completion is %.1fh old "
295
+ "(cap %.1fh); terminally dropping the replay (result remains queryable).",
296
+ delegation_id, (now - age_basis) / 3600.0, _MAX_COMPLETION_REPLAY_AGE_S / 3600.0)
297
+ continue
298
+ evt = json.loads(payload)
299
+ if isinstance(evt, dict):
300
+ evt["restored"] = True
301
+ target_queue.put(evt)
302
+ restored += 1
303
+ return restored
304
+
305
+
306
+ def _update_delivery(sql: str, params: tuple) -> bool:
307
+ """Run one UPDATE on the ledger; True iff exactly one row changed."""
308
+ with _DB_LOCK, _transaction() as conn:
309
+ return conn.execute(sql, params).rowcount == 1
310
+
311
+
312
+ def mark_completion_delivered(delegation_id: str) -> bool:
313
+ """Atomically acknowledge successful injection of a durable completion."""
314
+ now = time.time()
315
+ return _update_delivery(
316
+ """UPDATE async_delegations SET delivery_state='delivered', delivered_at=?, updated_at=?
317
+ WHERE delegation_id=? AND delivery_state!='delivered'""", (now, now, delegation_id))
318
+
319
+
320
+ def claim_completion_delivery(delegation_id: str, claim_id: str) -> bool:
321
+ """Claim one pending completion across competing consumers/processes."""
322
+ now = time.time()
323
+ with _DB_LOCK, _transaction() as conn:
324
+ row = conn.execute(
325
+ "SELECT delivery_state FROM async_delegations WHERE delegation_id=?", (delegation_id,)).fetchone()
326
+ if row is None:
327
+ return True # legacy event created before durable dispatch
328
+ cur = conn.execute("""UPDATE async_delegations SET delivery_claim=?, delivery_claimed_at=?,
329
+ delivery_attempts=delivery_attempts+1, updated_at=?
330
+ WHERE delegation_id=? AND delivery_state='pending'
331
+ AND (delivery_claim IS NULL OR delivery_claimed_at < ?)""",
332
+ (claim_id, now, now, delegation_id, now - 300))
333
+ return cur.rowcount == 1
334
+
335
+
336
+ def is_interim_delegation_event(evt: Dict[str, Any]) -> bool:
337
+ """An early per-task notice for a batch that is still running. It shares the batch's
338
+ ``delegation_id`` but is NOT the durable completion: it must never claim, acknowledge or
339
+ dedup against the final result's row (independent review reproduced exactly that loss)."""
340
+ return evt.get("type") == "async_delegation" and bool(evt.get("task_failure_notice"))
341
+
342
+
343
+ def claim_event_delivery(evt: Dict[str, Any], consumer: str) -> Optional[str]:
344
+ """Claim a durable delegation event; non-durable events (and interim notices) need no token."""
345
+ if is_interim_delegation_event(evt):
346
+ return ""
347
+ delegation_id = str(evt.get("delegation_id") or "") if evt.get("type") == "async_delegation" else ""
348
+ if not delegation_id:
349
+ return ""
350
+ claim_id = f"{consumer}:{os.getpid()}:{uuid.uuid4().hex}"
351
+ return claim_id if claim_completion_delivery(delegation_id, claim_id) else None
352
+
353
+
354
+ def release_completion_delivery(delegation_id: str, claim_id: str) -> bool:
355
+ """Release a failed delivery claim so another consumer may retry. Attempts are
356
+ counted at claim time; once the budget is exhausted the row converges to
357
+ terminal ``dropped`` (only pending rows replay on restart)."""
358
+ now = time.time()
359
+ with _DB_LOCK, _transaction() as conn:
360
+ capped = conn.execute("""UPDATE async_delegations SET delivery_state='dropped',
361
+ delivery_claim=NULL, delivery_claimed_at=NULL, updated_at=?
362
+ WHERE delegation_id=? AND delivery_state='pending'
363
+ AND delivery_claim=? AND delivery_attempts>=?""",
364
+ (now, delegation_id, claim_id, _MAX_DELIVERY_ATTEMPTS))
365
+ if capped.rowcount == 1:
366
+ logger.warning("Async delegation %s exhausted its %d delivery attempts; "
367
+ "marking terminally dropped (result remains queryable).",
368
+ delegation_id, _MAX_DELIVERY_ATTEMPTS)
369
+ return True
370
+ cur = conn.execute("""UPDATE async_delegations SET delivery_claim=NULL,
371
+ delivery_claimed_at=NULL, updated_at=?
372
+ WHERE delegation_id=? AND delivery_state='pending'
373
+ AND delivery_claim=?""", (now, delegation_id, claim_id))
374
+ return cur.rowcount == 1
375
+
376
+
377
+ def defer_completion_delivery(delegation_id: str, claim_id: str) -> bool:
378
+ """Return an unadmitted completion to pending without spending a delivery attempt."""
379
+ return _update_delivery("""UPDATE async_delegations SET delivery_claim=NULL,
380
+ delivery_claimed_at=NULL, delivery_attempts=MAX(0, delivery_attempts-1),
381
+ updated_at=?
382
+ WHERE delegation_id=? AND delivery_state='pending' AND delivery_claim=?""",
383
+ (time.time(), delegation_id, claim_id))
384
+
385
+
386
+ def drop_completion_delivery(delegation_id: str, claim_id: str) -> bool:
387
+ """Terminally drop a claimed completion whose target is permanently gone (the
388
+ spawning session ended at an explicit user boundary such as /new or reset).
389
+ ``dropped`` — not ``delivered`` — keeps the ack honest; not ``pending`` keeps
390
+ restart recovery from replaying it into a fail-closed drop forever."""
391
+ return _update_delivery("""UPDATE async_delegations SET delivery_state='dropped',
392
+ updated_at=?, delivery_claim=NULL,
393
+ delivery_claimed_at=NULL
394
+ WHERE delegation_id=? AND delivery_state='pending'
395
+ AND delivery_claim=?""", (time.time(), delegation_id, claim_id))
396
+
397
+
398
+ def complete_completion_delivery(delegation_id: str, claim_id: str) -> bool:
399
+ """Acknowledge acceptance for the consumer holding this claim."""
400
+ now = time.time()
401
+ return _update_delivery("""UPDATE async_delegations SET delivery_state='delivered',
402
+ delivered_at=?, updated_at=?, delivery_claim=NULL,
403
+ delivery_claimed_at=NULL
404
+ WHERE delegation_id=? AND delivery_state='pending'
405
+ AND delivery_claim=?""", (now, now, delegation_id, claim_id))
406
+
407
+
408
+ def complete_event_delivery(evt: Dict[str, Any], claim_id: str) -> None:
409
+ _event_delivery(complete_completion_delivery, evt, claim_id)
410
+
411
+
412
+ def release_event_delivery(evt: Dict[str, Any], claim_id: str) -> None:
413
+ _event_delivery(release_completion_delivery, evt, claim_id)
414
+
415
+
416
+ def _event_delivery(fn, evt: Dict[str, Any], claim_id: str) -> None:
417
+ if claim_id and evt.get("type") == "async_delegation":
418
+ fn(str(evt.get("delegation_id") or ""), claim_id)
419
+
420
+
421
+ def get_durable_delegation(delegation_id: str) -> Optional[Dict[str, Any]]:
422
+ with _DB_LOCK, _transaction() as conn:
423
+ row = conn.execute("""SELECT origin_session, state, dispatched_at, completed_at,
424
+ result_json, delivery_state, delivery_attempts,
425
+ origin_session_id
426
+ FROM async_delegations WHERE delegation_id=?""", (delegation_id,)).fetchone()
427
+ return None if row is None else {
428
+ "delegation_id": delegation_id, "origin_session": row[0], "state": row[1], "dispatched_at": row[2],
429
+ "completed_at": row[3], "result": json.loads(row[4]) if row[4] else None, "delivery_state": row[5],
430
+ "delivery_attempts": row[6], "origin_session_id": row[7] or ""}
431
+
432
+
433
+ # ── In-memory registry queries ──────────────────────────────────────────────
434
+ def _get_executor(max_workers: int) -> ThreadPoolExecutor:
435
+ """Lazily create (or grow in place, never shrink) the shared daemon executor. Raising
436
+ ``_max_workers`` is enough: the next ``submit`` spawns threads up to the new cap."""
437
+ global _executor, _executor_max_workers
438
+ with _executor_lock:
439
+ if _executor is None:
440
+ _executor = DaemonThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="async-delegate")
441
+ _executor_max_workers = max_workers
442
+ elif max_workers > _executor_max_workers:
443
+ _executor._max_workers = max_workers
444
+ _executor_max_workers = max_workers
445
+ return _executor
446
+
447
+
448
+ def active_count() -> int:
449
+ """Number of live async delegation UNITS (one per completion message: a task group or an ungrouped task)."""
450
+ with _records_lock:
451
+ return sum(1 for r in _records.values() if r.get("status") in _LIVE_STATES)
452
+
453
+
454
+ def active_task_count() -> int:
455
+ """Number of running child subagents (a batch of N contributes N; a batch with
456
+ no goal list counts 1) — the truthful observability figure, unlike slots."""
457
+ with _records_lock:
458
+ return sum(
459
+ len(r.get("task_indexes") or r["goals"])
460
+ if r.get("is_batch") and isinstance(r.get("goals"), (list, tuple)) and r["goals"] else 1
461
+ for r in _records.values() if r.get("status") in {"running", "finalizing"})
462
+
463
+
464
+ def _session_records(statuses, session_key: str, origin_ui_session_id: str, parent_session_id: str) -> list:
465
+ """Records in ``statuses`` owned by a session: any non-empty selector claims the
466
+ record — ``origin_ui_session_id`` (TUI tab), ``session_key`` (routing key at
467
+ dispatch), or ``parent_session_id`` (spawner's durable id — the right one for
468
+ gateway chats, whose session_key survives ``/new`` while the session id rotates)."""
469
+ selectors = [(field, wanted) for field, wanted in (
470
+ ("origin_ui_session_id", origin_ui_session_id), ("session_key", session_key),
471
+ ("parent_session_id", parent_session_id)) if wanted]
472
+ if not selectors:
473
+ return []
474
+ with _records_lock:
475
+ return [r for r in _records.values() if r.get("status") in statuses
476
+ and any(str(r.get(field) or "") == wanted for field, wanted in selectors)]
477
+
478
+
479
+ def has_live_for_session(session_key: str = "", origin_ui_session_id: str = "", parent_session_id: str = "") -> bool:
480
+ """Whether a session still owns any live (running/stalling/finalizing) delegation."""
481
+ return bool(_session_records(_LIVE_STATES, session_key, origin_ui_session_id, parent_session_id))
482
+
483
+
484
+ def _new_delegation_id() -> str:
485
+ return f"deleg_{uuid.uuid4().hex[:8]}"
486
+
487
+
488
+ def _prune_completed_locked() -> None:
489
+ """Drop the oldest completed records beyond the cap. Caller holds ``_records_lock``."""
490
+ completed = [(rid, r) for rid, r in _records.items() if r.get("status") != "running"]
491
+ completed.sort(key=lambda kv: kv[1].get("completed_at") or kv[1].get("dispatched_at") or 0)
492
+ for rid, _ in completed[: max(0, len(completed) - _MAX_RETAINED_COMPLETED)]:
493
+ _records.pop(rid, None)
494
+
495
+
496
+ def _current_origin_session_id() -> str:
497
+ """Raw session id of the ORIGINATING api_server request, or ``""``. ``HERMES_SESSION_ID``
498
+ is unsafe here: building the child agent calls ``set_current_session_id(child.session_id)``
499
+ just before dispatch, so the wake would self-post into the subagent's own session. The
500
+ request-scoped ``HERMES_SESSION_CHAT_ID`` (raw X-Hermes-Session-Id on api_server) survives
501
+ child construction; on push platforms chat_id is a chat, not a session => ``""``."""
502
+ try:
503
+ from gateway.session_context import get_session_env
504
+ is_api = get_session_env("HERMES_SESSION_PLATFORM", "") == "api_server"
505
+ return (get_session_env("HERMES_SESSION_CHAT_ID", "") or "") if is_api else ""
506
+ except Exception:
507
+ return ""
508
+
509
+
510
+ # ── Dispatch ────────────────────────────────────────────────────────────────
511
+ def _single_crash(error: str, duration: float) -> Dict[str, Any]:
512
+ return {"status": "error", "summary": None, "error": error, "api_calls": 0, "duration_seconds": duration}
513
+
514
+
515
+ def _batch_crash(error: str, duration: float) -> Dict[str, Any]:
516
+ return {"results": [], "error": error, "total_duration_seconds": duration}
517
+
518
+
519
+ def _batch_status(combined: Dict[str, Any]) -> str:
520
+ """Batch status: completed unless every child errored/was interrupted."""
521
+ child_results = combined.get("results") or []
522
+ ok = ("completed", "success")
523
+ return "error" if child_results and all(r.get("status") not in ok for r in child_results) else "completed"
524
+
525
+
526
+ def _dispatch(
527
+ *, delegation_id: str, goal: str, goals: Optional[List[str]], context: Optional[str],
528
+ toolsets: Optional[List[str]], role: str, model: Optional[str], session_key: str,
529
+ parent_session_id: Optional[str], runner: Callable[[], Dict[str, Any]], origin_ui_session_id: str,
530
+ origin_session_id: str, interrupt_fn: Optional[Callable[[], None]], max_async_children: int,
531
+ progress_fn: Optional[Callable[[], tuple]], capacity_error: str, slot_key: Optional[str] = None,
532
+ task_indexes: Optional[List[int]] = None,
533
+ ) -> Dict[str, Any]:
534
+ """Shared dispatch core for single (``goals is None``) and batch units. Capacity check +
535
+ record insert happen under ONE lock hold so concurrent dispatches can't both pass the check
536
+ and exceed the cap. At capacity the dispatch is REJECTED (never queued) so a runaway model
537
+ can't pile up unbounded background work. ``slot_key`` names the pool slot the unit occupies
538
+ (default: its own id); the units of one delegate_task call share the first unit's id so
539
+ splitting a call into per-group completions never consumes more capacity than the call did."""
540
+ is_batch = goals is not None
541
+ label = " batch" if is_batch else ""
542
+ classify = _batch_status if is_batch else (lambda r: r.get("status") or "completed")
543
+ crash_result = _batch_crash if is_batch else _single_crash
544
+ dispatched_at = time.time()
545
+ record: Dict[str, Any] = {
546
+ "delegation_id": delegation_id, "goal": goal, **({"goals": list(goals)} if is_batch else {}),
547
+ "context": context, "toolsets": list(toolsets) if toolsets else None, "role": role, "model": model,
548
+ "session_key": session_key, "origin_ui_session_id": origin_ui_session_id,
549
+ "origin_session_id": origin_session_id, "parent_session_id": parent_session_id,
550
+ **_capture_routing_origin(),
551
+ "status": "running", "dispatched_at": dispatched_at, "completed_at": None,
552
+ "interrupt_fn": interrupt_fn, **({"is_batch": True} if is_batch else {}), "progress_fn": progress_fn,
553
+ "slot_key": slot_key or delegation_id,
554
+ # Which of the call's ``goals`` this unit runs (None = all of them).
555
+ **({"task_indexes": list(task_indexes)} if task_indexes is not None else {}),
556
+ # Stale-monitor bookkeeping (see _stale_monitor_loop).
557
+ "_progress_token": None, "_progress_ts": dispatched_at, "_interrupted_at": None}
558
+ with _records_lock:
559
+ active_slots = {r.get("slot_key") or r["delegation_id"] for r in _records.values() if r.get("status") in _ACTIVE_STATES}
560
+ if record["slot_key"] not in active_slots and len(active_slots) >= max_async_children:
561
+ return {"status": "rejected", "error": capacity_error}
562
+ _records[delegation_id] = record
563
+ live_units = sum(1 for r in _records.values() if r.get("status") in _LIVE_STATES)
564
+ _persist_dispatch(record)
565
+ # Units of one call share a slot, so live units can exceed slots: size the pool by units or a
566
+ # unit queues behind a full pool and the stale monitor kills it before its child ever starts.
567
+ executor = _get_executor(max(max_async_children, live_units))
568
+
569
+ def _worker() -> None:
570
+ result: Dict[str, Any] = {}
571
+ status = "error"
572
+ with _records_lock:
573
+ rec = _records.get(delegation_id)
574
+ if rec is not None:
575
+ # The stall clock starts when the runner starts; a unit queued behind a full pool is not stalled.
576
+ rec.update(_started=True, _progress_ts=time.time())
577
+ try:
578
+ result = runner() or {}
579
+ status = classify(result)
580
+ except Exception as exc: # noqa: BLE001 — must never crash the worker
581
+ logger.exception(f"Async delegation{label} %s crashed", delegation_id)
582
+ result = crash_result(f"{type(exc).__name__}: {exc}", round(time.time() - dispatched_at, 2))
583
+ finally:
584
+ _finalize(delegation_id, result, status)
585
+
586
+ try:
587
+ # Propagate the dispatching profile so the detached child resolves get_hermes_home() correctly.
588
+ executor.submit(propagate_context_to_thread(_worker))
589
+ except Exception as exc: # pragma: no cover — pool submit failure is rare
590
+ with _records_lock:
591
+ _records.pop(delegation_id, None)
592
+ with _DB_LOCK, _transaction() as conn:
593
+ conn.execute("DELETE FROM async_delegations WHERE delegation_id=?", (delegation_id,))
594
+ return {"status": "rejected", "error": f"Failed to schedule async delegation{label}: {exc}"}
595
+ if progress_fn is not None:
596
+ _ensure_stale_monitor()
597
+ return {"status": "dispatched", "delegation_id": delegation_id}
598
+
599
+
600
+ def dispatch_async_delegation(
601
+ *, goal: str, context: Optional[str], toolsets: Optional[List[str]], role: str, model: Optional[str],
602
+ session_key: str, parent_session_id: Optional[str] = None, runner: Callable[[], Dict[str, Any]],
603
+ origin_ui_session_id: str = "", origin_session_id: str = "", interrupt_fn: Optional[Callable[[], None]] = None,
604
+ max_async_children: int = _DEFAULT_MAX_ASYNC_CHILDREN, progress_fn: Optional[Callable[[], tuple]] = None,
605
+ ) -> Dict[str, Any]:
606
+ """Spawn ``runner`` on the daemon executor and return a handle immediately.
607
+ ``session_key``/``parent_session_id`` are captured on the parent thread (the worker carries
608
+ no contextvars) and route the completion back to the spawning session.
609
+ ``progress_fn() -> (token, in_tool)`` enables stale monitoring; omitted = unmonitored.
610
+ Returns ``{"status": "dispatched", "delegation_id"}`` or ``{"status": "rejected", "error"}``."""
611
+ delegation_id = _new_delegation_id()
612
+ handle = _dispatch(
613
+ delegation_id=delegation_id, goal=goal, goals=None, context=context,
614
+ toolsets=toolsets, role=role, model=model, session_key=session_key,
615
+ parent_session_id=parent_session_id, runner=runner,
616
+ origin_ui_session_id=origin_ui_session_id, origin_session_id=origin_session_id,
617
+ interrupt_fn=interrupt_fn, max_async_children=max_async_children, progress_fn=progress_fn,
618
+ capacity_error=(
619
+ f"Async delegation capacity reached ({max_async_children} running). Wait for one to finish "
620
+ "(its result will re-enter the chat), or run this task synchronously (background=false). "
621
+ "Raise delegation.max_concurrent_children in config.yaml to allow more concurrent background subagents."))
622
+ if handle["status"] == "dispatched":
623
+ logger.info("Dispatched async delegation %s (session_key=%s): %s",
624
+ delegation_id, session_key or "<cli>", (goal or "")[:80])
625
+ return handle
626
+
627
+
628
+ def dispatch_async_delegation_batch(
629
+ *, goals: List[str], context: Optional[str], toolsets: Optional[List[str]], role: str, model: Optional[str],
630
+ session_key: str, parent_session_id: Optional[str] = None, runner: Callable[[], Dict[str, Any]],
631
+ origin_ui_session_id: str = "", origin_session_id: str = "", interrupt_fn: Optional[Callable[[], None]] = None,
632
+ max_async_children: int = _DEFAULT_MAX_ASYNC_CHILDREN, delegation_id: Optional[str] = None,
633
+ progress_fn: Optional[Callable[[], tuple]] = None, slot_key: Optional[str] = None,
634
+ task_indexes: Optional[List[int]] = None,
635
+ ) -> Dict[str, Any]:
636
+ """Dispatch a fan-out unit (a whole batch, or one ``group`` of a delegate_task call) as ONE
637
+ background unit: ``runner`` runs its tasks and returns the combined ``{"results": [...],
638
+ "total_duration_seconds": N}`` dict. The unit occupies ONE async slot — or joins the slot named
639
+ by ``slot_key`` (in-unit parallelism is bounded separately) — and produces a SINGLE completion
640
+ event carrying per-task ``results``."""
641
+ delegation_id = delegation_id or _new_delegation_id()
642
+ # ``goals`` is the whole call (result task_index indexes it); the unit's own goals label the record.
643
+ unit_goals = [goals[i] for i in task_indexes] if task_indexes is not None else list(goals)
644
+ n = len(unit_goals)
645
+ combined_goal = unit_goals[0] if n == 1 else f"{n} parallel subagents: " + "; ".join(g[:40] for g in unit_goals)
646
+ handle = _dispatch(
647
+ delegation_id=delegation_id, goal=combined_goal, goals=goals, context=context,
648
+ toolsets=toolsets, role=role, model=model, session_key=session_key,
649
+ parent_session_id=parent_session_id, runner=runner,
650
+ origin_ui_session_id=origin_ui_session_id, origin_session_id=origin_session_id,
651
+ interrupt_fn=interrupt_fn, max_async_children=max_async_children, progress_fn=progress_fn, slot_key=slot_key,
652
+ task_indexes=task_indexes,
653
+ capacity_error=(
654
+ f"Async delegation capacity reached ({max_async_children} running). Wait for one to finish "
655
+ "(its result will re-enter the chat), or raise delegation.max_concurrent_children in "
656
+ "config.yaml to allow more concurrent background units."))
657
+ if handle["status"] == "dispatched":
658
+ logger.info("Dispatched async delegation batch %s (%d task(s), session_key=%s)",
659
+ delegation_id, n, session_key or "<cli>")
660
+ return handle
661
+
662
+
663
+ # ── Finalization + completion events ────────────────────────────────────────
664
+ def _finalize(delegation_id: str, result: Any, status: str) -> None:
665
+ """Atomically claim terminal delivery, push the completion event, then mark ``status``.
666
+ ``result`` is a dict or a callable receiving the record snapshot (stall path). The record
667
+ stays active ("finalizing") until durable persistence and queue publication finish; otherwise
668
+ process shutdown can kill this daemon worker after status flips but before SQLite commits.
669
+ A second call for the same id (late runner return after a forced stall) is a no-op."""
670
+ with _records_lock:
671
+ record = _records.get(delegation_id)
672
+ if record is None or record.get("status") not in _ACTIVE_STATES:
673
+ return
674
+ record["status"] = "finalizing"
675
+ record["completed_at"] = time.time()
676
+ record["interrupt_fn"] = None # drop the closure; child is done
677
+ record["progress_fn"] = None # stop stale-monitor sampling
678
+ snapshot = dict(record)
679
+ _push_completion_event(snapshot, result(snapshot) if callable(result) else result, status)
680
+ with _records_lock:
681
+ if delegation_id in _records:
682
+ _records[delegation_id]["status"] = status
683
+ _prune_completed_locked()
684
+
685
+
686
+ def _push_completion_event(record: Dict[str, Any], result: Dict[str, Any], status: str) -> None:
687
+ """Push a type='async_delegation' event onto the shared completion queue. Batch records
688
+ (``is_batch``) carry the per-task ``results`` list (plus live transcript paths, the
689
+ full-fidelity record of each child's run) instead of a single summary. Best-effort: failure
690
+ must not crash the worker, but it WOULD mean a silently-lost result, so we log loudly."""
691
+ is_batch = bool(record.get("is_batch"))
692
+ label = " batch" if is_batch else ""
693
+ try:
694
+ from tools.process_registry import process_registry
695
+ except Exception as exc: # pragma: no cover
696
+ logger.error(f"Async delegation{label} %s finished but process_registry import failed; "
697
+ "result lost: %s", record.get("delegation_id"), exc)
698
+ return
699
+ dispatched_at = record.get("dispatched_at") or time.time()
700
+ completed_at = record.get("completed_at") or time.time()
701
+ if is_batch:
702
+ payload = {
703
+ "is_batch": True, "results": result.get("results") or [],
704
+ "live_transcripts": result.get("live_transcripts"), "error": result.get("error"),
705
+ "total_duration_seconds": result.get("total_duration_seconds"),
706
+ **({"group": result["group"]} if result.get("group") is not None else {})}
707
+ else:
708
+ payload = {
709
+ "summary": result.get("summary"), "error": result.get("error"), "api_calls": result.get("api_calls", 0),
710
+ "duration_seconds": result.get("duration_seconds", round(completed_at - dispatched_at, 2))}
711
+ evt = {
712
+ "type": "async_delegation", "delegation_id": record.get("delegation_id"),
713
+ # session_key routes back to the originating gateway session; "" => CLI.
714
+ "session_key": record.get("session_key", ""),
715
+ "origin_ui_session_id": record.get("origin_ui_session_id", ""),
716
+ "origin_session_id": record.get("origin_session_id", ""),
717
+ "parent_session_id": record.get("parent_session_id"),
718
+ "goal": record.get("goal", ""), **({"goals": record.get("goals")} if is_batch else {}),
719
+ "context": record.get("context"), "toolsets": record.get("toolsets"), "role": record.get("role"),
720
+ "model": record.get("model") if is_batch else (result.get("model") or record.get("model")),
721
+ "status": status, **payload, "dispatched_at": dispatched_at, "completed_at": completed_at,
722
+ **({} if is_batch else {"exit_reason": result.get("exit_reason")}),
723
+ **{k: record[k] for k in _ROUTING_KEYS if record.get(k)},
724
+ **{k: result[k] for k in _STALL_META_KEYS if k in result}}
725
+ _persist_completion(evt, result)
726
+ try:
727
+ process_registry.completion_queue.put(evt)
728
+ except Exception as exc: # pragma: no cover
729
+ logger.error(f"Async delegation{label} %s: failed to enqueue completion event; "
730
+ "result lost: %s", record.get("delegation_id"), exc)
731
+
732
+
733
+ def push_task_failure_notice(delegation_id: str, entry: Dict[str, Any], *, n_tasks: int) -> None:
734
+ """Surface ONE failed child of a still-running detached batch to the parent now, instead of
735
+ when the slowest sibling finishes. In a 1,393-agent run every wave-1 child died in a 401 storm
736
+ at 08:29 and the parent learned of it at 09:36, when the batch's "unknown outcome" block finally
737
+ arrived: 66 minutes of a dead wave with nothing running. The notice rides the same
738
+ ``type="async_delegation"`` event shape as the batch result (so every drain/route/format path
739
+ treats it identically) with ``task_failure_notice=True`` and a single-entry ``results`` list; the
740
+ batch record is NOT finalized and its consolidated result still arrives as before."""
741
+ with _records_lock:
742
+ record = _records.get(delegation_id)
743
+ if record is None or record.get("status") not in _ACTIVE_STATES:
744
+ return
745
+ snapshot = dict(record)
746
+ try:
747
+ from tools.process_registry import process_registry
748
+ except Exception as exc: # pragma: no cover
749
+ logger.error("Async delegation batch %s: task failure notice dropped (process_registry import): %s", delegation_id, exc)
750
+ return
751
+ evt = {
752
+ "type": "async_delegation", "task_failure_notice": True, "is_batch": True, "n_tasks": n_tasks,
753
+ "delegation_id": delegation_id, "results": [entry],
754
+ "session_key": snapshot.get("session_key", ""),
755
+ "origin_ui_session_id": snapshot.get("origin_ui_session_id", ""),
756
+ "origin_session_id": snapshot.get("origin_session_id", ""),
757
+ "parent_session_id": snapshot.get("parent_session_id"),
758
+ "goal": snapshot.get("goal", ""), "goals": snapshot.get("goals"), "context": snapshot.get("context"),
759
+ "toolsets": snapshot.get("toolsets"), "role": snapshot.get("role"), "model": snapshot.get("model"),
760
+ "status": "running", "dispatched_at": snapshot.get("dispatched_at") or time.time(), "completed_at": time.time(),
761
+ **{k: snapshot[k] for k in _ROUTING_KEYS if snapshot.get(k)}}
762
+ try:
763
+ process_registry.completion_queue.put(evt)
764
+ except Exception as exc: # pragma: no cover
765
+ logger.error("Async delegation batch %s: failed to enqueue task failure notice: %s", delegation_id, exc)
766
+
767
+
768
+ # ── Stale monitor ───────────────────────────────────────────────────────────
769
+ def _ensure_stale_monitor() -> None:
770
+ """Start (once) the stale-delegation monitor thread. One daemon thread serves
771
+ every dispatch; it exits when no monitorable records remain and is restarted
772
+ by the next dispatch with a ``progress_fn``."""
773
+ global _monitor_thread
774
+ with _monitor_lock:
775
+ if _monitor_thread is not None and _monitor_thread.is_alive():
776
+ return
777
+ _monitor_stop.clear()
778
+ _monitor_thread = threading.Thread(
779
+ target=_stale_monitor_loop, name="async-delegate-stale-monitor", daemon=True)
780
+ _monitor_thread.start()
781
+
782
+
783
+ def _sweep_stale_locked(now: float):
784
+ """One monitor pass over ``_records``; caller holds ``_records_lock``. Returns
785
+ ``(stalled, expired, any_monitorable)``: newly-stalling ``(delegation_id, quiet_for, in_tool)``
786
+ tuples, stalling ids past the grace window, and whether anything is left to monitor."""
787
+ stalled, expired, any_monitorable = [], [], False # (delegation_id, quiet_for, in_tool) / ids past grace
788
+ for record in _records.values():
789
+ status = record.get("status")
790
+ if status == "stalling":
791
+ any_monitorable = True
792
+ if now - (record.get("_interrupted_at") or now) >= _STALL_GRACE_SECONDS:
793
+ expired.append(record["delegation_id"])
794
+ continue
795
+ progress_fn = record.get("progress_fn")
796
+ if status != "running" or progress_fn is None:
797
+ continue
798
+ any_monitorable = True
799
+ if not record.get("_started"):
800
+ continue # queued behind a full pool: not stalled, but keep the monitor alive for when it starts
801
+ try:
802
+ token, in_tool = progress_fn()
803
+ except Exception:
804
+ # An unreadable child must not look permanently healthy —
805
+ # keep the last timestamp running instead of refreshing it.
806
+ token, in_tool = record.get("_progress_token"), False
807
+ if token != record.get("_progress_token"):
808
+ record.update(_progress_token=token, _progress_ts=now)
809
+ continue
810
+ quiet_for = now - (record.get("_progress_ts") or now)
811
+ limit = _STALE_IN_TOOL_SECONDS if in_tool else _STALE_IDLE_SECONDS
812
+ if quiet_for >= limit:
813
+ # Stall context feeds the terminal event and status listings.
814
+ record.update(
815
+ status="stalling", _interrupted_at=now, _stall_quiet_seconds=round(quiet_for, 2),
816
+ _stall_threshold_seconds=limit, _stall_in_tool=bool(in_tool))
817
+ stalled.append((record["delegation_id"], quiet_for, in_tool))
818
+ return stalled, expired, any_monitorable
819
+
820
+
821
+ def _call_interrupt(fn, msg: str, *args) -> bool:
822
+ """Invoke an ``interrupt_fn``; True on success, else debug-log ``msg`` (+ exc)."""
823
+ if not callable(fn):
824
+ return False
825
+ try:
826
+ fn()
827
+ return True
828
+ except Exception as exc:
829
+ logger.debug(msg, *args, exc)
830
+ return False
831
+
832
+
833
+ def _stale_monitor_loop() -> None:
834
+ """Sweep running delegations for stalled progress. A changed progress token refreshes the
835
+ record's timestamp; a frozen token past the idle/in-tool threshold marks the record
836
+ ``stalling`` and calls ``interrupt_fn``; a ``stalling`` record still unreturned after the
837
+ grace window is force-finalized with a terminal ``stalled`` event."""
838
+ while not _monitor_stop.wait(_STALE_CHECK_INTERVAL):
839
+ now = time.time()
840
+ with _records_lock:
841
+ stalled, expired, any_monitorable = _sweep_stale_locked(now)
842
+ for delegation_id, quiet_for, in_tool in stalled:
843
+ logger.warning("Async delegation %s made no progress for %.0fs "
844
+ "(in_tool=%s) — interrupting; grace window %.0fs",
845
+ delegation_id, quiet_for, in_tool, _STALL_GRACE_SECONDS)
846
+ with _records_lock:
847
+ fn = (_records.get(delegation_id) or {}).get("interrupt_fn")
848
+ _call_interrupt(fn, "Async delegation %s stall interrupt failed: %s", delegation_id)
849
+ for delegation_id in expired:
850
+ _finalize(delegation_id, lambda rec, d=delegation_id: _stalled_result(d, rec), "stalled")
851
+ if not any_monitorable:
852
+ return
853
+
854
+
855
+ def _stalled_result(delegation_id: str, event_record: Dict[str, Any]) -> Dict[str, Any]:
856
+ """Synthetic terminal result for a stalling delegation whose runner never returned."""
857
+ completed_at = event_record.get("completed_at") or time.time()
858
+ duration = round(completed_at - (event_record.get("dispatched_at") or completed_at), 2)
859
+ error = (
860
+ f"Async delegation {delegation_id} stalled: the detached subagent stopped making progress "
861
+ "(no new API calls, tool activity, or streamed tokens), did not respond to interruption, and never "
862
+ "produced a completion event. The worker may be wedged inside a model API call — this is a known "
863
+ "failure mode of long-lived gateway processes (#60203). Re-dispatch the task if it is still needed.")
864
+ logger.error("Async delegation %s force-finalized as stalled after %.0fs", delegation_id, duration)
865
+ # Structured stall metadata lets parents/UIs distinguish a stall-monitor
866
+ # kill from other failures without parsing the error string.
867
+ stall_in_tool = event_record.get("_stall_in_tool")
868
+ stall_meta = {
869
+ "stalled_after_quiet_seconds": event_record.get("_stall_quiet_seconds"),
870
+ "stall_threshold_seconds": event_record.get("_stall_threshold_seconds"),
871
+ "stall_phase": "in_tool" if stall_in_tool else "idle" if stall_in_tool is not None else None,
872
+ "stall_grace_seconds": _STALL_GRACE_SECONDS}
873
+ if event_record.get("is_batch"):
874
+ return {**_batch_crash(error, duration), **stall_meta}
875
+ return {**_single_crash(error, duration), "status": "stalled", "exit_reason": "stalled", **stall_meta}
876
+
877
+
878
+ # ── Observability + control ─────────────────────────────────────────────────
879
+ def _children_activity_from_token(token: Any, now: float) -> Optional[List]:
880
+ """Parse a progress token into per-child activity dicts (best-effort): delegate_tool
881
+ emits one ``(api_call_count, current_tool, last_activity_ts)`` tuple per child;
882
+ foreign token shapes degrade to ``None`` entries."""
883
+ try:
884
+ parts = list(token)
885
+ except TypeError:
886
+ return None
887
+ out: List[Optional[Dict[str, Any]]] = []
888
+ for part in parts:
889
+ if not (isinstance(part, (list, tuple)) and len(part) >= 2):
890
+ out.append(None)
891
+ continue
892
+ entry: Dict[str, Any] = {"api_calls": part[0], "current_tool": part[1]}
893
+ if len(part) >= 3 and isinstance(part[2], (int, float)):
894
+ entry["seconds_since_activity"] = round(max(0.0, now - float(part[2])), 1)
895
+ out.append(entry)
896
+ return out
897
+
898
+
899
+ def list_async_delegations() -> List[Dict[str, Any]]:
900
+ """Snapshot of async delegations (running + recently completed) without callables or private
901
+ monitor bookkeeping; adds computed live fields for UIs (``seconds_since_progress``,
902
+ ``children_activity``/``in_tool`` sampled from ``progress_fn``) and stall context once tripped.
903
+
904
+ Safe to call from any thread. See #51690.
905
+ """
906
+ now = time.time()
907
+ samplers: Dict[str, Callable] = {}
908
+ with _records_lock:
909
+ items = []
910
+ for r in _records.values():
911
+ item = {k: v for k, v in r.items() if k not in {"interrupt_fn", "progress_fn"} and not k.startswith("_")}
912
+ status = r.get("status")
913
+ if status in _ACTIVE_STATES:
914
+ if r.get("_progress_ts"):
915
+ item["seconds_since_progress"] = round(now - r["_progress_ts"], 1)
916
+ if callable(r.get("progress_fn")):
917
+ samplers[r["delegation_id"]] = r["progress_fn"]
918
+ if status in ("stalling", "stalled"):
919
+ for src, dst in _STALL_FIELD_MAP:
920
+ if r.get(src) is not None:
921
+ item[dst] = r.get(src)
922
+ items.append(item)
923
+ # Sample OUTSIDE the lock — progress_fn reads child-agent attributes and a
924
+ # slow/broken sampler must not block every dispatch/finalize.
925
+ for item in items:
926
+ fn = samplers.get(item.get("delegation_id"))
927
+ if fn is None:
928
+ continue
929
+ try:
930
+ token, in_tool = fn()
931
+ except Exception:
932
+ continue
933
+ activity = _children_activity_from_token(token, now)
934
+ if activity is not None:
935
+ item["children_activity"] = activity
936
+ item["in_tool"] = bool(in_tool)
937
+ return items
938
+
939
+
940
+ def _interrupt_records(targets: List[Dict[str, Any]], caller: str, reason: str, msg: str) -> int:
941
+ """Call ``interrupt_fn`` on each record; log ``msg`` once; returns how many succeeded."""
942
+ count = sum(
943
+ _call_interrupt(r.get("interrupt_fn"), "%s: %s interrupt failed: %s", caller, r.get("delegation_id"))
944
+ for r in targets)
945
+ if count:
946
+ logger.info(msg, count, reason)
947
+ return count
948
+
949
+
950
+ def interrupt_all(reason: str = "shutdown") -> int:
951
+ """Signal every running async delegation to stop (``/stop``, shutdown). Returns how
952
+ many. The child still emits a completion event (status='interrupted') via the
953
+ normal finalize path."""
954
+ with _records_lock:
955
+ targets = [r for r in _records.values() if r.get("status") in _ACTIVE_STATES]
956
+ return _interrupt_records(targets, "interrupt_all", reason, "Interrupted %d async delegation(s) (%s)")
957
+
958
+
959
+ def interrupt_for_session(
960
+ session_key: str = "", origin_ui_session_id: str = "", parent_session_id: str = "", reason: str = "session_end",
961
+ ) -> int:
962
+ """Signal running async delegations owned by ONE ending session to stop (any
963
+ selector matches, see ``_session_records``). Returns how many."""
964
+ targets = _session_records(_ACTIVE_STATES, session_key, origin_ui_session_id, parent_session_id)
965
+ return _interrupt_records(
966
+ targets, "interrupt_for_session", reason, "Interrupted %d async delegation(s) for ending session (%s)")
967
+
968
+
969
+ def _reset_for_tests() -> None:
970
+ """Test-only: clear all state and tear down the executor + monitor."""
971
+ global _executor, _executor_max_workers, _monitor_thread
972
+ with _executor_lock:
973
+ if _executor is not None:
974
+ _executor.shutdown(wait=False)
975
+ _executor = None
976
+ _executor_max_workers = 0
977
+ _monitor_stop.set()
978
+ with _monitor_lock:
979
+ thread, _monitor_thread = _monitor_thread, None
980
+ if thread is not None and thread.is_alive():
981
+ thread.join(timeout=2)
982
+ with _records_lock:
983
+ _records.clear()
984
+
985
+
986
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
987
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
988
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
989
+ # The whole block is removed by reverting the commit that added it.
990
+
991
+ def active_for_session(origin_ui_session_id: str) -> int:
992
+ """Number of live async delegations owned by one UI session."""
993
+ if not origin_ui_session_id:
994
+ return 0
995
+ with _records_lock:
996
+ return sum(
997
+ 1
998
+ for r in _records.values()
999
+ if r.get("status") in {"running", "stalling", "finalizing"}
1000
+ and str(r.get("origin_ui_session_id") or "")
1001
+ == origin_ui_session_id
1002
+ )
1003
+ # ---- END PLUGIN-COMPAT ----
tools/bot_mode_dm.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bot Mode agent-to-agent DM tool — ``message_agent``.
2
+
3
+ Lets a Bot Mode agent message a teammate (a profile on this install, an agent on
4
+ a registered peer gateway, or one on another Desktop-connected machine): the
5
+ target is validated against the live roster, the attribution prefix is applied
6
+ server-side, and the reply arrives later via the background-process completion
7
+ notification (fire-and-forget). Containment: the schema is injected ONLY into a
8
+ bot's canonical "Bot Chat" session on a Bot-Mode-managed install (same gate as
9
+ ``tools/bot_mode_probe.py``; never in the registry or any toolset), and dispatch
10
+ re-checks that gate so a forged call returns a structured error. Transports:
11
+ local → ``hermes -p <name> chat --in ~ -c "Bot Chat" --create-if-missing -Q
12
+ --query-file <tmp>``; peer → ``hermes peer dm <peer>[/<name>] < <tmp>``; both via
13
+ ``terminal_tool(background=True, notify_on_complete=True)``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import contextlib
19
+ import hashlib
20
+ import json
21
+ import logging
22
+ import os
23
+ import re
24
+ import shlex
25
+ import stat
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+ import time
30
+ from pathlib import Path
31
+ from typing import Any, Optional
32
+
33
+ # Top-level imports stay stdlib-only: this module also runs directly as the background
34
+ # delivery runner (``python bot_mode_dm.py --run-delivery …``); Hermes helpers import lazily.
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ MESSAGE_AGENT_TOOL_NAME = "message_agent"
39
+
40
+ # Message body cap — generous for real work, small enough that a runaway paste can't
41
+ # turn one DM into a context bomb on the recipient.
42
+ MESSAGE_MAX_CHARS = 16000
43
+ # A runner owns and removes each DM file; this bounds residual plaintext lifetime if
44
+ # the machine dies between spawn ack and the runner's finally.
45
+ _DM_DIR_NAME = "hermes-dm"
46
+ _DM_STALE_SECONDS = 24 * 60 * 60
47
+ _LIVE_WAIT_SECONDS = 300
48
+
49
+ # '<peer>/<agent>' — peer names are lowercase (``hermes peer`` normalizes them).
50
+ _PEER_TARGET_RE = re.compile(r"^([a-z0-9][a-z0-9_-]{0,63})/([a-zA-Z0-9][a-zA-Z0-9_-]{0,63})$")
51
+ # Same shape as ``tools.bot_relay._HANDLE_RE`` (kept local: see import note above).
52
+ _LOCAL_TARGET_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$")
53
+
54
+
55
+ def _default_home() -> str:
56
+ from hermes_constants import get_process_hermes_home
57
+ return str(get_process_hermes_home())
58
+
59
+
60
+ def message_agent_tool_schema() -> dict:
61
+ """OpenAI-format schema for ``message_agent`` (injected, not registered)."""
62
+ return {
63
+ "type": "function",
64
+ "function": {
65
+ "name": MESSAGE_AGENT_TOOL_NAME,
66
+ "description": (
67
+ "Send a message to ANOTHER agent (teammate) on this install, or to an "
68
+ "agent on a registered peer gateway. This is FIRE-AND-FORGET and "
69
+ "asynchronous, like texting: it validates the target against the live "
70
+ "roster, delivers your message into that agent's own Bot Chat with your "
71
+ "attribution automatically prefixed, and returns immediately with a "
72
+ "delivery acknowledgement. It does NOT return their reply and you must "
73
+ "not wait or poll for one — send it, finish your turn, and the reply "
74
+ "arrives later as a background-process completion notification that "
75
+ "wakes you. COMPOSE the message yourself: write what YOU want to say to "
76
+ "that agent (lead with the point; include the concrete ask or result). "
77
+ "Never paste the user's words verbatim — paraphrase the actionable "
78
+ "substance, and keep private 1:1 chat content private. Message one "
79
+ "clearly relevant teammate when it genuinely helps the user's goal; "
80
+ "don't fan out to several agents unless the user explicitly asked. "
81
+ "Use the teammate roster in your system prompt (names + roles) to pick "
82
+ "the right recipient; targets: a teammate name (e.g. 'researcher'), "
83
+ "'<peer>/<agent>' for an agent on a registered peer gateway "
84
+ "(e.g. 'spark/researcher', or just '<peer>' for the peer's main agent), "
85
+ "or an agent on another connected machine from your roster (use "
86
+ "'<handle>@<connection>' if the same handle exists on several)."
87
+ ),
88
+ "parameters": {
89
+ "type": "object",
90
+ "properties": {
91
+ "target": {
92
+ "type": "string",
93
+ "description": (
94
+ "Who to message: a teammate profile name from your roster "
95
+ "('researcher', 'hermes' for the default agent), or "
96
+ "'<peer>' / '<peer>/<agent>' for a registered peer gateway."
97
+ ),
98
+ },
99
+ "message": {
100
+ "type": "string",
101
+ "description": (
102
+ "The message YOU composed for that agent (max "
103
+ f"{MESSAGE_MAX_CHARS} chars). Do not include the "
104
+ "'Message from …' prefix — it is added automatically."
105
+ ),
106
+ },
107
+ },
108
+ "required": ["target", "message"],
109
+ },
110
+ },
111
+ }
112
+
113
+
114
+ def message_agent_authorized(agent: Any) -> bool:
115
+ """The ``message_agent`` gate: a protocol-enabled agent whose session is a managed
116
+ Bot-Mode canonical Bot Chat. Session-stable, so it is prompt-cache safe to re-evaluate
117
+ on every tool-snapshot rebuild. Never raises."""
118
+ try:
119
+ if not getattr(agent, "_bot_mode_protocol", True):
120
+ return False
121
+ from tools.bot_mode_probe import BOT_CHAT_TITLE, is_bot_mode_managed
122
+
123
+ # Managed-install check, NOT section non-emptiness: a SOUL.md carrying the
124
+ # legacy protocol text gets an empty section but must still get the tool.
125
+ return _session_title(agent) == BOT_CHAT_TITLE and is_bot_mode_managed(_agent_home(agent))
126
+ except Exception: # pragma: no cover — must never break a turn
127
+ logger.debug("message_agent_authorized failed", exc_info=True)
128
+ return False
129
+
130
+
131
+ def ensure_message_agent_tool(agent: Any) -> bool:
132
+ """Inject the ``message_agent`` schema into a Bot Chat agent's tool list (once per turn).
133
+ Idempotent and deterministic for the session's life (the gate is stable from the
134
+ first turn), so the tool list is byte-identical across turns — prompt-cache safe. Never raises."""
135
+ try:
136
+ if not getattr(agent, "_bot_mode_protocol", True):
137
+ return False
138
+ tools = getattr(agent, "tools", None)
139
+ if tools and any(
140
+ isinstance(t, dict) and t.get("function", {}).get("name") == MESSAGE_AGENT_TOOL_NAME
141
+ for t in tools
142
+ ):
143
+ return True
144
+ if not message_agent_authorized(agent):
145
+ return False
146
+ if agent.tools is None:
147
+ agent.tools = []
148
+ agent.tools.append(message_agent_tool_schema())
149
+ valid = getattr(agent, "valid_tool_names", None)
150
+ if isinstance(valid, set):
151
+ valid.add(MESSAGE_AGENT_TOOL_NAME)
152
+ return True
153
+ except Exception: # pragma: no cover — must never break a turn
154
+ logger.debug("ensure_message_agent_tool failed", exc_info=True)
155
+ return False
156
+
157
+
158
+ def _resolve_local_name(target: str, roster: list[str]) -> Optional[str]:
159
+ """Map a target handle to a profile name ('hermes' → 'default')."""
160
+ want = target.strip().lower()
161
+ if want == "hermes":
162
+ return "default" if "default" in roster else None
163
+ return next((name for name in roster if name.lower() == want), None) if want else None
164
+
165
+
166
+ def _err(message: str, *, roster: list[str] | None = None, peers: list[str] | None = None) -> str:
167
+ from tools.bot_failure_reasons import classify_agent_error
168
+
169
+ payload: dict[str, Any] = {"error": message, "reason": classify_agent_error(message)}
170
+ if roster is not None:
171
+ payload["teammates"] = roster
172
+ if peers is not None:
173
+ payload["peers"] = peers
174
+ return json.dumps(payload)
175
+
176
+
177
+ def message_agent_tool(target: str = "", message: str = "", task_id: Optional[str] = None, agent: Any = None) -> str:
178
+ """Deliver ``message`` to ``target``'s Bot Chat. Returns a JSON ack/error.
179
+ ``agent`` is the calling AIAgent — used for the Bot Chat gate and sender identity."""
180
+ home = _agent_home(agent)
181
+ try:
182
+ from tools.bot_mode_probe import (
183
+ BOT_CHAT_TITLE, _handle, _hermes_root, _peers, _profile_name as _self_profile_name, _roster,
184
+ is_bot_mode_managed,
185
+ )
186
+ from tools.bot_relay import BOT_CHAT_TURN_ARGS, _hermes_cli
187
+
188
+ if _session_title(agent) != BOT_CHAT_TITLE:
189
+ return _err("message_agent is only available in a Bot Mode 'Bot Chat' session. "
190
+ "This session is not one; do not retry.")
191
+ if not is_bot_mode_managed(home):
192
+ return _err("This install is not Bot-Mode-managed (no bot roster); "
193
+ "message_agent is unavailable. Do not retry.")
194
+ except Exception as exc: # pragma: no cover — defensive
195
+ return _err(f"Bot Mode gate check failed: {exc}")
196
+
197
+ root, me = _hermes_root(Path(home)), _self_profile_name(Path(home))
198
+ roster_homes = dict(_roster(root))
199
+ roster = list(roster_homes)
200
+ peers = _peers(root)
201
+ teammates = [_handle(n) for n in roster if n != me]
202
+
203
+ def _roster_err(msg: str) -> str:
204
+ return _err(msg, roster=teammates, peers=peers)
205
+
206
+ body = str(message or "").strip()
207
+ if not body:
208
+ return _err("message is required — compose what you want to say to that agent.")
209
+ if len(body) > MESSAGE_MAX_CHARS:
210
+ return _err(f"message too long ({len(body)} chars > {MESSAGE_MAX_CHARS}). "
211
+ "Send the essentials; share large content as a file path instead.")
212
+
213
+ raw_target = str(target or "").strip().lstrip("@")
214
+ if not raw_target:
215
+ return _roster_err("target is required.")
216
+ content = f"Message from 🤖 {_handle(me)} (@{_handle(me)}): " + body
217
+ delivery = dict(task_id=task_id, agent=agent)
218
+ # Attribution for the recipient's memory hooks; the text prefix above stays the human-facing signature.
219
+ author = {"id": f"bot:{me}", "name": _handle(me), "is_bot": True}
220
+
221
+ # Peer target: '<peer>/<agent>' or a bare registered peer name.
222
+ peer_match = _PEER_TARGET_RE.match(raw_target)
223
+ if peer_match or raw_target.lower() in peers:
224
+ peer_name, peer_profile = peer_match.groups() if peer_match else (raw_target.lower(), None)
225
+ if peer_name not in peers:
226
+ return _roster_err(f"No registered peer named '{peer_name}'.")
227
+ dm_target = f"{peer_name}/{peer_profile}" if peer_profile else peer_name
228
+ # A peer dm crosses installs: qualify the id with this host so the peer's own '<me>' stays distinct.
229
+ from agent.turn_author import bot_author_id, local_origin
230
+ peer_author = {**author, "id": bot_author_id(me, local_origin())}
231
+ # Pin the registry-owning profile: `hermes peer` resolves bot_peers via the profile-scoped
232
+ # load_config(), while the roster above reads the machine-root config — the CLI must run
233
+ # in that same profile or a secondary-profile bot sees an empty registry.
234
+ # The delivery runs in a background service context whose PATH lacks the gateway's
235
+ # venv bin dir, so a bare "hermes" resolves to a system install and dies on import
236
+ # under the wrong interpreter (#108628). _hermes_cli pins the entrypoint beside
237
+ # this interpreter; _delivery_lock/_local_delivery_home match argv[0] by basename,
238
+ # so the absolute path stays compatible.
239
+ return _start_delivery([_hermes_cli(), "-p", _self_profile_name(root), "peer", "dm", dm_target], content,
240
+ f"@{peer_profile or peer_name} on peer '{peer_name}'", stdin_file=True,
241
+ author=peer_author, **delivery)
242
+
243
+ # Local teammate.
244
+ is_local_shape = bool(_LOCAL_TARGET_RE.match(raw_target))
245
+ if not is_local_shape and "@" not in raw_target:
246
+ return _roster_err(f"Invalid target: {raw_target!r}.")
247
+ resolved = _resolve_local_name(raw_target, roster) if is_local_shape else None
248
+ if resolved is None or resolved == me:
249
+ # Unknown locally, or same-name target on ANOTHER connection (this gateway's 'default'
250
+ # messaging the cloud 'default'): every Desktop-connected gateway is reachable via the
251
+ # relay roster, so try that before reporting a resolution failure / self-message.
252
+ relayed = _try_relay_delivery(root, raw_target, content, me, **delivery)
253
+ if relayed is not None:
254
+ return relayed
255
+ if resolved == me:
256
+ return _err("You can't message yourself. Pick a teammate from the roster.")
257
+ return _roster_err(f"No teammate named '{raw_target}' on this install, on a connected "
258
+ "machine, or on a registered peer. Pick a name from the roster "
259
+ "(roles are listed in your system prompt).")
260
+ return _start_delivery([_hermes_cli(), "-p", resolved, *BOT_CHAT_TURN_ARGS], content, f"@{_handle(resolved)}",
261
+ stdin_file=False, profile_home=roster_homes[resolved], author=author, **delivery)
262
+
263
+
264
+ def _try_relay_delivery(root: Path, raw_target: str, content: str, me: str, *,
265
+ task_id: Optional[str], agent: Any) -> Optional[str]:
266
+ """Cross-connection delivery via the Desktop relay; None when the target doesn't
267
+ resolve against the relay roster. The envelope is queued on disk for the Desktop
268
+ to drain; a background waiter is spawned immediately so the relayed reply wakes
269
+ the sender through the standard completion-notification path."""
270
+ try:
271
+ from tools.bot_mode_probe import _handle
272
+ from tools.bot_relay import (
273
+ EnvelopeRefusedError, enqueue_envelope, read_remote_roster, resolve_remote_target, waiter_command,
274
+ )
275
+
276
+ roster = read_remote_roster(root)
277
+ match = resolve_remote_target(raw_target, roster) if roster else None
278
+ if match is None:
279
+ return None
280
+ if match == "ambiguous":
281
+ want = raw_target.strip().lstrip("@").lower()
282
+ forms = ", ".join(f"{r['handle']}@{r['connection_id']}" for r in roster if r["handle"].lower() == want)
283
+ return _err(f"'{raw_target}' exists on several connected machines — disambiguate with one of: {forms}.")
284
+ try:
285
+ envelope = enqueue_envelope(root, target=match, message=content, sender_profile=me, sender_handle=_handle(me))
286
+ except EnvelopeRefusedError as exc:
287
+ # Fail fast: target definitively offline — nothing was queued.
288
+ # Structured refusal so the agent can distinguish it from a resolution error ('runtime_offline'
289
+ # per the #93091 reason enum).
290
+ return json.dumps({"error": str(exc), "reason": exc.reason})
291
+ label = f"@{match['handle']} on {match['connection_label'] or match['connection_id']}"
292
+ return _spawn_delivery(waiter_command(root, envelope), label, task_id=task_id, agent=agent)
293
+ except Exception:
294
+ logger.debug("relay delivery attempt failed", exc_info=True)
295
+ return None
296
+
297
+
298
+ def _dm_dir() -> Path:
299
+ uid_getter = getattr(os, "getuid", None)
300
+ uid = uid_getter() if callable(uid_getter) else None
301
+ path = Path(tempfile.gettempdir()) / (f"{_DM_DIR_NAME}-{uid}" if uid is not None else _DM_DIR_NAME)
302
+ path.mkdir(mode=0o700, exist_ok=True)
303
+ # Shared POSIX temp roots need a per-user directory. Fail closed if an
304
+ # attacker pre-created the expected path or replaced it with a symlink.
305
+ info = path.lstat()
306
+ if not stat.S_ISDIR(info.st_mode):
307
+ raise PermissionError(f"DM temp path is not a directory: {path}")
308
+ if uid is not None and info.st_uid != uid:
309
+ raise PermissionError(f"DM temp directory is owned by another user: {path}")
310
+ if stat.S_IMODE(info.st_mode) != 0o700:
311
+ path.chmod(0o700)
312
+ return path
313
+
314
+
315
+ def cleanup_bot_dm_cache(max_age_hours: float = _DM_STALE_SECONDS / 3600, *, now: float | None = None) -> int:
316
+ """Delete orphaned DM payload files older than *max_age_hours*; returns count.
317
+ Same contract as the other ``cleanup_*_cache`` helpers (hourly gateway housekeeping);
318
+ legacy temp-root locations from versions predating the dedicated directory are swept too."""
319
+ cutoff = (time.time() if now is None else now) - max_age_hours * 3600
320
+ temp_root = Path(tempfile.gettempdir())
321
+ locations = [(temp_root, "hermes-dm-*.txt"), (temp_root, "hermes-relay-dm-*.txt")]
322
+ with contextlib.suppress(OSError):
323
+ locations.append((_dm_dir(), "*.txt"))
324
+ from tools.bot_relay import unlink_files_older_than
325
+
326
+ return sum(unlink_files_older_than(d, pattern, cutoff) for d, pattern in locations)
327
+
328
+
329
+ def _unlink_dm_file(path: str) -> None:
330
+ with contextlib.suppress(OSError):
331
+ os.unlink(path)
332
+
333
+
334
+ def _write_dm_file(content: str) -> str:
335
+ """The message rides a temp file — never inline shell text."""
336
+ cleanup_bot_dm_cache()
337
+ fd, path = tempfile.mkstemp(prefix="dm-", suffix=".txt", dir=_dm_dir(), text=True)
338
+ try:
339
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
340
+ f.write(content)
341
+ except BaseException:
342
+ # If fdopen itself failed the raw descriptor is still ours; closing twice is harmless.
343
+ with contextlib.suppress(OSError):
344
+ os.close(fd)
345
+ _unlink_dm_file(path)
346
+ raise
347
+ return path
348
+
349
+
350
+ def _delivery_lock(argv: list[str], *, stdin_file: bool):
351
+ """Per-profile turn lock for a LOCAL teammate delivery: local and relay deliveries
352
+ into one profile both run a Bot Chat turn here, so the turn window is serialized on
353
+ ``tools.bot_relay``'s cross-process lock. Peer transports (stdin mode) are locked
354
+ on the remote gateway by its own deliver path.
355
+
356
+ See #93091.
357
+ """
358
+ # Match the CLI element by basename: argv[0] may be an absolute venv path
359
+ # (service contexts lack PATH) and carries .exe on Windows; split on both separators.
360
+ # Split on both separators so the shape matches regardless of which platform built the argv. See #93590.
361
+ cli = (argv[0] if argv else "").rsplit("\\", 1)[-1].rsplit("/", 1)[-1]
362
+ if stdin_file or len(argv) < 3 or cli not in ("hermes", "hermes.exe") or argv[1] != "-p":
363
+ return contextlib.nullcontext()
364
+ from tools.bot_mode_probe import _hermes_root
365
+ from tools.bot_relay import acquire_turn_lock
366
+
367
+ return acquire_turn_lock(_hermes_root(Path(_default_home())), argv[2])
368
+
369
+
370
+ def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, str]] = None) -> int:
371
+ """One Bot Chat turn via ``--query-file`` (plus one policy-gated retry); re-emits
372
+ the transport's streams and returns its exit code. Transient failures re-run the
373
+ same session; a context_overflow re-run lets the retried turn's pre-API compaction
374
+ compact the transcript first (no fresh session is ever minted). Auth/quota/config never retry."""
375
+
376
+ def _turn():
377
+ return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL,
378
+ capture_output=True, text=True, env=env)
379
+
380
+ proc = _turn()
381
+ if proc.returncode != 0:
382
+ from tools.bot_failure_reasons import RETRY_NONE, classify_agent_error, retry_action
383
+
384
+ if retry_action(classify_agent_error((proc.stderr or proc.stdout or "").strip()[-500:])) != RETRY_NONE:
385
+ proc = _turn()
386
+ stderr_text = proc.stderr or ""
387
+ reason = next((line.removeprefix("hermes-refusal-reason: ").strip()
388
+ for line in stderr_text.splitlines()
389
+ if line.startswith("hermes-refusal-reason: ")), None)
390
+ # A code wins over prose, including unknown codes from newer CLIs.
391
+ # Only older CLIs without a marker need the historical wording fallback.
392
+ refused_not_owned = (reason == "SESSION_NOT_OWNED" if reason is not None
393
+ else "already has a live owner" in stderr_text)
394
+ if proc.returncode != 0 and refused_not_owned:
395
+ # The target's Bot Chat is held live by another surface (Desktop); the turn
396
+ # never ran — tell the sender plainly instead of leaking a raw lease error.
397
+ # See #100523.
398
+ who = argv[argv.index("-p") + 1] if "-p" in argv[:-1] else "the teammate"
399
+ print(json.dumps({
400
+ "error": f"Delivery failed: @{who}'s Bot Chat is open on another "
401
+ "surface right now, so your message was NOT delivered. Try again later.",
402
+ "reason": "target_busy",
403
+ }))
404
+ return 1
405
+ # Re-emit the transport's streams: stdout is the reply text the
406
+ # completion notification carries back to the sending agent.
407
+ for stream, text in ((sys.stdout, proc.stdout), (sys.stderr, proc.stderr)):
408
+ if text:
409
+ stream.write(text)
410
+ stream.flush()
411
+ return proc.returncode
412
+
413
+
414
+ def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dict] = None) -> dict | None:
415
+ """Pin intent before admission; retries may inspect, never change transport."""
416
+ from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner, read_delivery_result
417
+ from utils import fsync_directory
418
+
419
+ intent: dict[str, Any]
420
+ intent_path = Path(dm_file + ".live.json")
421
+ if intent_path.exists():
422
+ intent = json.loads(intent_path.read_text(encoding="utf-8"))
423
+ else:
424
+ assert profile_home is not None
425
+ owner = find_canonical_live_owner(profile_home)
426
+ if owner is None:
427
+ return None
428
+ intent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8"),
429
+ delivery_id=hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest(),
430
+ **({"author": author} if author else {}))
431
+ try:
432
+ fd = os.open(intent_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
433
+ except FileExistsError:
434
+ intent = json.loads(intent_path.read_text(encoding="utf-8"))
435
+ else:
436
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
437
+ json.dump(intent, stream)
438
+ stream.flush()
439
+ os.fsync(stream.fileno())
440
+ fsync_directory(intent_path.parent)
441
+ home = intent["owner"]["profile_home"]
442
+ record = read_delivery_result(home, intent["delivery_id"])
443
+ if record is None:
444
+ record = deliver_to_live_owner(home, intent["owner"], intent["message"],
445
+ delivery_id=intent["delivery_id"], author=intent.get("author"))
446
+ return record
447
+
448
+
449
+ def _wait_live_dm(home: str, delivery_id: str) -> int:
450
+ from tools.bot_live_delivery import read_delivery_result
451
+
452
+ deadline = time.monotonic() + _LIVE_WAIT_SECONDS
453
+ while True:
454
+ record = read_delivery_result(home, delivery_id)
455
+ status = record["status"] if record else "ambiguous"
456
+ if status not in ("queued", "claimed") or time.monotonic() >= deadline:
457
+ break
458
+ time.sleep(min(0.5, max(0, deadline - time.monotonic())))
459
+ payload = {key: record[key] for key in ("reply", "error", "reason") if record and record.get(key)}
460
+ payload.update(status=status, delivery_id=delivery_id)
461
+ if status in ("queued", "claimed", "ambiguous"):
462
+ payload["detail"] = "Delivery remains pending or its outcome is unknown. Do not resend; receipt is retained."
463
+ print(json.dumps(payload))
464
+ return 0 if status in ("settled", "queued", "claimed") else 1
465
+
466
+
467
+ def _local_delivery_home(argv: list[str]) -> Path | None:
468
+ cli = (argv[0] if argv else "").rsplit("\\", 1)[-1].rsplit("/", 1)[-1]
469
+ if len(argv) < 3 or cli not in ("hermes", "hermes.exe") or argv[1] != "-p":
470
+ return None
471
+ from tools.bot_mode_probe import _hermes_root, _roster
472
+
473
+ return dict(_roster(_hermes_root(Path(_default_home())))).get(argv[2])
474
+
475
+
476
+ def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool,
477
+ profile_home: Path | None = None, author: Optional[dict] = None) -> int:
478
+ """Route to the live owner before attempting a CLI transport. Live deliveries
479
+ retain their intent/payload and immutable receipt; only CLI/peer payloads are
480
+ removed after consumption. The CLI turn window holds the profile lock, so two
481
+ deliveries into one profile queue; a bounded wait ends in a 'target_busy' refusal.
482
+ ``author`` rides to the child as HERMES_TURN_AUTHOR; ``hermes peer dm`` forwards it in the request body.
483
+
484
+ Local (query-file) turns get one policy-gated retry (#93091 item 5): transient failures re-run the same
485
+ session; a context_overflow re-run lets the retried turn's pre-API compaction pass compact the Bot Chat
486
+ transcript first (agent/conversation_loop.py) — the sanctioned compression lever; no fresh session is
487
+ ever minted. Auth/quota/config failures never retry. Peer transports (stdin mode) retry on their own
488
+ gateway's deliver path, not here.
489
+ """
490
+ # The live consumer owns turn admission; never compete for its CLI lease.
491
+ if not stdin_file:
492
+ home = profile_home or _local_delivery_home(argv)
493
+ if home is not None or Path(dm_file + ".live.json").exists():
494
+ try:
495
+ record = _admit_live_dm(home, dm_file, author)
496
+ except Exception as exc:
497
+ print(json.dumps({"status": "ambiguous", "delivery_id": hashlib.sha256(
498
+ str(Path(dm_file).resolve()).encode()).hexdigest(),
499
+ "error": f"Live admission outcome unknown: {exc}. Do not resend.",
500
+ "evidence_file": dm_file}))
501
+ return 1
502
+ if record is not None:
503
+ return _wait_live_dm(record["profile_home"], record["delivery_id"])
504
+ try:
505
+ from tools.bot_relay import delivery_env
506
+
507
+ env = delivery_env(author)
508
+ with _delivery_lock(argv, stdin_file=stdin_file):
509
+ if not stdin_file:
510
+ return _run_local_turn(argv, dm_file, env=env)
511
+ # Keep the file open until the transport exits; cleanup occurs
512
+ # after subprocess.run returns, not merely after stdin reaches EOF.
513
+ with open(dm_file, "r", encoding="utf-8") as stream:
514
+ return subprocess.run(argv, stdin=stream, check=False, env=env).returncode
515
+ finally:
516
+ _unlink_dm_file(dm_file)
517
+
518
+
519
+ def _delivery_command(argv: list[str], dm_file: str, *, stdin_file: bool,
520
+ profile_home: Path | None = None, author: Optional[dict] = None) -> str:
521
+ """Build an argv-safe command for the cleanup-owning background runner:
522
+ ``--run-delivery [--author <json>] <mode> <dm_file> [--profile-home <path>] <argv...>``."""
523
+ runner_argv = [sys.executable, str(Path(__file__).resolve()), "--run-delivery",
524
+ "stdin" if stdin_file else "query-file", dm_file]
525
+ if profile_home is not None:
526
+ runner_argv.extend(["--profile-home", str(Path(profile_home).resolve())])
527
+ runner_argv.extend(argv)
528
+ if sys.platform == "win32":
529
+ # The tracked local backend uses Git Bash on native Windows: forward slashes keep drive
530
+ # paths executable there; backslash paths are parsed as command names (exit 127).
531
+ runner_argv = [part.replace("\\", "/") for part in runner_argv]
532
+ if author:
533
+ # Inserted after the slash rewrite: JSON escapes are backslashes too.
534
+ runner_argv[3:3] = ["--author", json.dumps(author, separators=(",", ":"))]
535
+ return shlex.join(runner_argv)
536
+
537
+
538
+ def _start_delivery(argv: list[str], content: str, label: str, *, stdin_file: bool,
539
+ task_id: Optional[str], agent: Any, profile_home: Path | None = None,
540
+ author: Optional[dict] = None) -> str:
541
+ """Create a DM file and transfer its cleanup ownership to the runner."""
542
+ dm_file = _write_dm_file(content)
543
+ if profile_home is not None:
544
+ try:
545
+ record = _admit_live_dm(profile_home, dm_file, author)
546
+ except Exception as exc:
547
+ return json.dumps({"status": "ambiguous", "delivery_id": hashlib.sha256(
548
+ str(Path(dm_file).resolve()).encode()).hexdigest(),
549
+ "error": f"Live delivery admission could not be confirmed: {exc}. Do not resend.",
550
+ "evidence_file": dm_file})
551
+ if record is not None:
552
+ command = _delivery_command(argv, dm_file, stdin_file=False, profile_home=profile_home, author=author)
553
+ notification = json.loads(_spawn_delivery(command, label, task_id=task_id, agent=agent))
554
+ result = dict(status=record["status"], delivery_id=record["delivery_id"], to=label,
555
+ detail="Durably queued for the live Bot Chat owner. Do NOT wait or resend; finish your turn.")
556
+ if notification.get("error"):
557
+ result["notification_error"] = notification["error"]
558
+ elif notification.get("process_id"):
559
+ result["process_id"] = notification["process_id"]
560
+ return json.dumps(result)
561
+ try:
562
+ command = _delivery_command(argv, dm_file, stdin_file=stdin_file, profile_home=profile_home, author=author)
563
+ except BaseException:
564
+ _unlink_dm_file(dm_file)
565
+ raise
566
+ return _spawn_delivery(command, label, dm_file=dm_file, task_id=task_id, agent=agent)
567
+
568
+
569
+ def _spawn_delivery(command: str, label: str, *, dm_file: Optional[str] = None,
570
+ task_id: Optional[str], agent: Any) -> str:
571
+ """Launch the cleanup-owning runner and transfer file ownership on ack. ``dm_file``
572
+ is None for relay deliveries (the waiter watches a reply file; envelope artifacts
573
+ are owned/swept by ``tools/bot_relay.py``)."""
574
+ transferred = False
575
+ try:
576
+ from tools.terminal_tool import terminal_tool
577
+
578
+ raw = terminal_tool(command, background=True, notify_on_complete=True, task_id=task_id,
579
+ workdir=str(Path(__file__).resolve().parent.parent), _host_local=True)
580
+ try:
581
+ parsed = json.loads(raw)
582
+ except (ValueError, TypeError):
583
+ parsed = {}
584
+ proc_id = parsed.get("session_id") or ""
585
+ if parsed.get("error"):
586
+ return _err(f"Delivery to {label} failed to start: {parsed['error']}")
587
+ if not proc_id:
588
+ return _err(f"Delivery to {label} failed to start: no process id returned")
589
+ # From here the background runner owns the file (removed after the consumer finishes).
590
+ transferred = True
591
+ return json.dumps({
592
+ "status": "sent",
593
+ "to": label,
594
+ "detail": (f"Message dispatched to {label}. This is asynchronous — do NOT wait "
595
+ "or poll. Finish your turn now; when the delivery completes, its "
596
+ "notification carries the reply — relay it then, attributed to that agent."),
597
+ "process_id": proc_id,
598
+ "sent_at": int(time.time()),
599
+ })
600
+ except Exception as exc:
601
+ logger.error("message_agent delivery spawn failed: %s", exc, exc_info=True)
602
+ return _err(f"Delivery to {label} could not be started: {exc}")
603
+ finally:
604
+ if dm_file and not transferred:
605
+ _unlink_dm_file(dm_file)
606
+
607
+
608
+ def _delivery_main(args: list[str]) -> int:
609
+ """Runner entry for the argv ``_delivery_command`` builds. Malformed argv exits 2 without touching the DM file."""
610
+ if not args or args[0] != "--run-delivery":
611
+ return 2
612
+ rest, author = args[1:], None
613
+ if rest[:1] == ["--author"]:
614
+ from agent.turn_author import parse_turn_author
615
+
616
+ author = parse_turn_author(rest[1]) if len(rest) > 1 else None
617
+ if author is None:
618
+ return 2
619
+ rest = rest[2:]
620
+ if len(rest) < 2 or rest[0] not in ("stdin", "query-file"):
621
+ return 2
622
+ try:
623
+ argv, profile_home = rest[2:], None
624
+ if len(argv) >= 2 and argv[0] == "--profile-home":
625
+ profile_home, argv = Path(argv[1]), argv[2:]
626
+ return _run_delivery(argv, rest[1], stdin_file=rest[0] == "stdin", profile_home=profile_home, author=author)
627
+ except Exception as exc:
628
+ # 'target_busy': the queued delivery gave up after its bounded wait — surface the
629
+ # structured payload on stdout so the completion notification carries it back.
630
+ if getattr(exc, "reason", "") == "target_busy":
631
+ # See #93091.
632
+ print(json.dumps({"error": str(exc), "reason": "target_busy"}))
633
+ else:
634
+ print(f"message_agent delivery failed: {type(exc).__name__}: {exc}", file=sys.stderr)
635
+ return 1
636
+
637
+
638
+ # agent-context helpers (mirror system_prompt.py's resolution)
639
+
640
+
641
+ def _agent_home(agent: Any) -> str:
642
+ """The calling agent's OWN home (session-db derived), not ambient env."""
643
+ with contextlib.suppress(Exception):
644
+ db_path = getattr(getattr(agent, "_session_db", None), "db_path", None)
645
+ if db_path:
646
+ return str(Path(db_path).parent)
647
+ return _default_home()
648
+
649
+
650
+ def _session_title(agent: Any) -> str:
651
+ title = str(getattr(agent, "_session_title_hint", "") or "").strip()
652
+ if title:
653
+ return title
654
+ with contextlib.suppress(Exception):
655
+ sdb, sid = getattr(agent, "_session_db", None), getattr(agent, "session_id", None)
656
+ if sdb and sid:
657
+ return str(sdb.get_session_title(sid) or "").strip()
658
+ return ""
659
+
660
+
661
+ if __name__ == "__main__": # pragma: no cover - exercised as a background process
662
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
663
+ raise SystemExit(_delivery_main(sys.argv[1:]))
tools/browser_camofox.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Camofox browser backend — local anti-detection browser via REST API.
2
+
3
+ Camofox-browser (https://github.com/jo-inc/camofox-browser) is a self-hosted Node.js
4
+ server wrapping Camoufox (Firefox fork with C++ fingerprint spoofing); its REST API maps
5
+ 1:1 to our browser tool interface (accessibility snapshots with element refs, click/type/
6
+ scroll by ref, screenshots). Setup: ``npm start`` in a checkout or ``docker run -p 9377:9377
7
+ -e CAMOFOX_PORT=9377 jo-inc/camofox-browser``, then ``CAMOFOX_URL=http://localhost:9377`` in
8
+ ``~/.hermes/.env`` (Docker: see ``CAMOFOX_REWRITE_LOOPBACK_URLS`` below).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import ipaddress
15
+ import json
16
+ import logging
17
+ import os
18
+ import re
19
+ import threading
20
+ import uuid
21
+ from typing import Any, Callable, Dict, Optional
22
+ from urllib.parse import SplitResult, urlsplit, urlunsplit
23
+
24
+ import requests
25
+
26
+ from agent.secret_scope import get_secret
27
+ from hermes_cli.config import cfg_get, load_config, read_raw_config
28
+ from hermes_constants import get_hermes_home_override, hermes_home_key
29
+ from tools.browser_camofox_state import get_camofox_identity
30
+ from tools.registry import tool_error
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ # ---- Configuration ----
35
+
36
+ _DEFAULT_TIMEOUT = 30 # fallback when config is unreadable
37
+ _NO_SESSION_ERROR = "No browser session. Call browser_navigate first."
38
+ _vnc_url: Optional[str] = None # cached from /health response
39
+ _vnc_url_checked = False # only probe once per process
40
+ # Routed profiles (multiplexed gateway) each point CAMOFOX_URL at their own server, so the one-shot
41
+ # slot above would hand the launch profile's VNC address to every other profile: memo per server URL.
42
+ _vnc_url_by_camofox_url: Dict[str, Optional[str]] = {}
43
+ # browser.command_timeout, resolved lazily like browser_tool; keyed by profile home because the
44
+ # multiplexed gateway serves every profile from one process.
45
+ _cached_cmd_timeout: Optional[Dict[str, int]] = None
46
+ _cmd_timeout_resolved = False
47
+
48
+
49
+ def _get_command_timeout() -> int:
50
+ """``browser.command_timeout`` (floor 5s, default 30s), cached per profile home after first read."""
51
+ global _cached_cmd_timeout, _cmd_timeout_resolved
52
+ home = hermes_home_key()
53
+ if _cached_cmd_timeout is None:
54
+ _cached_cmd_timeout = {}
55
+ if _cmd_timeout_resolved and home in _cached_cmd_timeout:
56
+ return _cached_cmd_timeout[home]
57
+ timeout = _DEFAULT_TIMEOUT
58
+ try:
59
+ val = cfg_get(read_raw_config(), "browser", "command_timeout")
60
+ if val is not None:
61
+ timeout = max(int(val), 5)
62
+ except Exception as exc:
63
+ logger.debug("Could not read browser.command_timeout: %s", exc)
64
+ _cached_cmd_timeout[home] = timeout
65
+ _cmd_timeout_resolved = True
66
+ return timeout
67
+
68
+
69
+ def _auth_headers() -> Dict[str, str]:
70
+ """Return Authorization header when CAMOFOX_API_KEY is set."""
71
+ key = (get_secret("CAMOFOX_API_KEY", "") or "").strip()
72
+ return {"Authorization": f"Bearer {key}"} if key else {}
73
+
74
+
75
+ def get_camofox_url() -> str:
76
+ """Return the configured Camofox server URL, or empty string."""
77
+ return (get_secret("CAMOFOX_URL", "") or "").rstrip("/")
78
+
79
+
80
+ def _config_cdp_url() -> str:
81
+ """Persistent ``browser.cdp_url`` from config.yaml, or "" (read here, not via
82
+ ``browser_tool_cdp._get_cdp_override`` — circular import)."""
83
+ try:
84
+ from hermes_cli.config import read_raw_config # late-bound: tests patch the source module
85
+ browser_cfg = read_raw_config().get("browser", {})
86
+ if isinstance(browser_cfg, dict):
87
+ return str(browser_cfg.get("cdp_url", "") or "").strip()
88
+ except Exception:
89
+ pass
90
+ return ""
91
+
92
+
93
+ def is_camofox_mode() -> bool:
94
+ """True when the Camofox backend is selected and no CDP override is active.
95
+
96
+ Selection is ``browser.cloud_provider: camofox``; ``CAMOFOX_URL`` is only the address
97
+ and never overrides a different stored selection (legacy: with no selection ever
98
+ written, a set ``CAMOFOX_URL`` still activates Camofox). A CDP override (``BROWSER_CDP_URL``
99
+ env or ``browser.cdp_url``, same precedence as ``browser_tool_cdp._get_cdp_override()``) wins.
100
+ """
101
+ if os.getenv("BROWSER_CDP_URL", "").strip() or _config_cdp_url():
102
+ return False
103
+ try:
104
+ from tools.tool_backend_helpers import read_selection
105
+ selected = read_selection("browser")
106
+ except Exception: # pragma: no cover — helpers are in-repo
107
+ selected = None
108
+ if selected is not None:
109
+ return selected == "camofox"
110
+ return bool(get_camofox_url())
111
+
112
+
113
+ def _vnc_url_from_health(url: str, resp: Any) -> Optional[str]:
114
+ try:
115
+ vnc_port = resp.json().get("vncPort")
116
+ if isinstance(vnc_port, int) and 1 <= vnc_port <= 65535:
117
+ return f"http://{urlsplit(url).hostname or 'localhost'}:{vnc_port}"
118
+ except (ValueError, KeyError):
119
+ pass
120
+ return None
121
+
122
+
123
+ def check_camofox_available() -> bool:
124
+ """Verify the Camofox server is reachable (and cache its VNC URL once)."""
125
+ global _vnc_url, _vnc_url_checked
126
+ url = get_camofox_url()
127
+ if not url:
128
+ return False
129
+ try:
130
+ resp = requests.get(f"{url}/health", timeout=5)
131
+ except Exception:
132
+ return False
133
+ if resp.status_code == 200:
134
+ if get_hermes_home_override() is not None:
135
+ if url not in _vnc_url_by_camofox_url:
136
+ _vnc_url_by_camofox_url[url] = _vnc_url_from_health(url, resp)
137
+ elif not _vnc_url_checked:
138
+ _vnc_url = _vnc_url_from_health(url, resp) or _vnc_url
139
+ _vnc_url_checked = True
140
+ return resp.status_code == 200
141
+
142
+
143
+ def get_vnc_url() -> Optional[str]:
144
+ """Return the VNC URL if the Camofox server exposes one, or None."""
145
+ if get_hermes_home_override() is not None:
146
+ url = get_camofox_url()
147
+ if url not in _vnc_url_by_camofox_url:
148
+ check_camofox_available()
149
+ return _vnc_url_by_camofox_url.get(url)
150
+ if not _vnc_url_checked:
151
+ check_camofox_available()
152
+ return _vnc_url
153
+
154
+
155
+ def _get_camofox_config() -> Dict[str, Any]:
156
+ """Return the ``browser.camofox`` config block, or an empty dict."""
157
+ try:
158
+ camofox_cfg = load_config().get("browser", {}).get("camofox", {})
159
+ except Exception as exc:
160
+ logger.warning("camofox config check failed, defaulting to disabled: %s", exc)
161
+ return {}
162
+ return camofox_cfg if isinstance(camofox_cfg, dict) else {}
163
+
164
+
165
+ def _managed_persistence_enabled(camofox_cfg: Optional[Dict[str, Any]] = None) -> bool:
166
+ """``browser.camofox.managed_persistence``: stable profile-scoped userId vs random per session."""
167
+ return bool((_get_camofox_config() if camofox_cfg is None else camofox_cfg).get("managed_persistence"))
168
+
169
+
170
+ def _env_or_cfg(env_name: str, camofox_cfg: Dict[str, Any], cfg_key: str, *, secret: bool = False) -> str:
171
+ """Env/secret-scope value first, then the ``browser.camofox`` config key, else ""."""
172
+ raw = get_secret(env_name, "") if secret else os.getenv(env_name, "")
173
+ return (raw or "").strip() or str(camofox_cfg.get(cfg_key) or "").strip()
174
+
175
+
176
+ def _camofox_identity_override(task_id: Optional[str], camofox_cfg: Dict[str, Any]) -> Optional[Dict[str, str]]:
177
+ """Externally configured identity (integrations owning the visible Camofox browser
178
+ share a user ID so Hermes uses the same profile), or None."""
179
+ user_id = _env_or_cfg("CAMOFOX_USER_ID", camofox_cfg, "user_id", secret=True)
180
+ if not user_id:
181
+ return None
182
+ session_key = _env_or_cfg("CAMOFOX_SESSION_KEY", camofox_cfg, "session_key", secret=True)
183
+ return {"user_id": user_id, "session_key": session_key or f"task_{(task_id or 'default')[:16]}"}
184
+
185
+
186
+ def _flag(env_name: str, camofox_cfg: Dict[str, Any], cfg_key: str) -> bool:
187
+ """Boolean toggle: env var wins when set to a valid value, else config key."""
188
+ raw = os.getenv(env_name, "").strip().lower()
189
+ if raw in {"1", "true", "yes", "on"}:
190
+ return True
191
+ if raw in {"0", "false", "no", "off"}:
192
+ return False
193
+ if raw:
194
+ logger.debug("Ignoring invalid boolean env %s=%r", env_name, raw)
195
+ return bool(camofox_cfg.get(cfg_key))
196
+
197
+
198
+ def _is_loopback_hostname(hostname: Optional[str]) -> bool:
199
+ if not hostname:
200
+ return False
201
+ host = hostname.strip().strip("[]").lower()
202
+ if host in {"localhost", "localhost.localdomain"}:
203
+ return True
204
+ try:
205
+ return ipaddress.ip_address(host).is_loopback
206
+ except ValueError:
207
+ return False
208
+
209
+
210
+ def _rewrite_loopback_url_for_camofox(url: str) -> tuple[str, Optional[Dict[str, str]]]:
211
+ """Rewrite loopback page URLs for Docker-hosted Camofox, if configured.
212
+
213
+ ``CAMOFOX_URL`` may point at a host-published Docker port, but page URLs are opened by
214
+ the browser *inside* the container, where loopback is the container, not the host.
215
+ Opt-in (``CAMOFOX_REWRITE_LOOPBACK_URLS`` / config) because non-Docker installs run the
216
+ browser on the host. Returns ``(rewritten_url, metadata)``; ``metadata`` is present only
217
+ when a rewrite happened so the tool result can disclose the change to the model.
218
+ """
219
+ camofox_cfg = _get_camofox_config()
220
+ if not _flag("CAMOFOX_REWRITE_LOOPBACK_URLS", camofox_cfg, "rewrite_loopback_urls"):
221
+ return url, None
222
+ try:
223
+ parsed = urlsplit(url)
224
+ except ValueError:
225
+ return url, None
226
+ alias = _env_or_cfg("CAMOFOX_LOOPBACK_HOST_ALIAS", camofox_cfg, "loopback_host_alias") or "host.docker.internal"
227
+ if parsed.scheme not in {"http", "https"} or not _is_loopback_hostname(parsed.hostname) or not alias:
228
+ return url, None
229
+ userinfo = (parsed.username + (f":{parsed.password}" if parsed.password else "") + "@") if parsed.username else ""
230
+ host_part = f"[{alias}]" if ":" in alias and not alias.startswith("[") else alias
231
+ port_part = f":{parsed.port}" if parsed.port else ""
232
+ rewritten = urlunsplit(
233
+ SplitResult(parsed.scheme, f"{userinfo}{host_part}{port_part}", parsed.path, parsed.query, parsed.fragment))
234
+ return rewritten, {"from": parsed.hostname or "", "to": alias, "original_url": url, "rewritten_url": rewritten}
235
+
236
+
237
+ # ---- Session management ----
238
+ _sessions: Dict[str, Dict[str, Any]] = {} # task_id -> {"user_id": str, "tab_id": str|None, ...}
239
+ _sessions_lock = threading.Lock()
240
+
241
+
242
+ def _adopt_existing_tab(session: Dict[str, Any]) -> Dict[str, Any]:
243
+ """Rehydrate tab_id from an already-open managed tab: gateway restarts empty the
244
+ in-memory cache while Camofox still holds the integration-owned tab."""
245
+ if session.get("tab_id") or not session.get("adopt_existing_tab") or not get_camofox_url():
246
+ return session
247
+ try:
248
+ tabs = _get("/tabs", params=_user_params(session), timeout=5).get("tabs", [])
249
+ except Exception as exc:
250
+ logger.debug("Camofox tab adoption failed for %s: %s", session.get("user_id"), exc)
251
+ return session
252
+ dict_tabs = [tab for tab in tabs if isinstance(tab, dict)] if isinstance(tabs, list) else []
253
+ candidates = [tab for tab in dict_tabs if tab.get("listItemId") == session.get("session_key")] or dict_tabs
254
+ tab_id = candidates[-1].get("tabId") if candidates else None
255
+ if isinstance(tab_id, str) and tab_id:
256
+ session["tab_id"] = tab_id
257
+ logger.debug("Adopted existing Camofox tab %s for %s", tab_id, session.get("user_id"))
258
+ return session
259
+
260
+
261
+ def _get_session(task_id: Optional[str]) -> Dict[str, Any]:
262
+ """Get or create the task's session. Identity precedence: external override
263
+ (CAMOFOX_USER_ID / config) → profile-scoped identity when managed persistence
264
+ is on → random ephemeral userId."""
265
+ task_id = task_id or "default"
266
+ with _sessions_lock:
267
+ if task_id in _sessions:
268
+ return _adopt_existing_tab(_sessions[task_id])
269
+ camofox_cfg = _get_camofox_config()
270
+ identity = _camofox_identity_override(task_id, camofox_cfg)
271
+ if identity is None and _managed_persistence_enabled(camofox_cfg):
272
+ identity = get_camofox_identity(task_id)
273
+ if identity is None:
274
+ identity = {"user_id": f"hermes_{uuid.uuid4().hex[:10]}", "session_key": f"task_{task_id[:16]}"}
275
+ managed, adopt = False, False
276
+ else:
277
+ managed, adopt = True, _flag("CAMOFOX_ADOPT_EXISTING_TAB", camofox_cfg, "adopt_existing_tab")
278
+ session = {"user_id": identity["user_id"], "tab_id": None, "session_key": identity["session_key"],
279
+ "managed": managed, "adopt_existing_tab": adopt}
280
+ _sessions[task_id] = session
281
+ return _adopt_existing_tab(session)
282
+
283
+
284
+ def _ensure_tab(task_id: Optional[str], url: str = "about:blank") -> Dict[str, Any]:
285
+ """Ensure a tab exists for the session, creating one if needed."""
286
+ session = _get_session(task_id)
287
+ if not session["tab_id"]:
288
+ data = _post("/tabs", {"userId": session["user_id"], "listItemId": session["session_key"], "url": url})
289
+ session["tab_id"] = data.get("tabId")
290
+ return session
291
+
292
+
293
+ def _drop_session(task_id: Optional[str]) -> Optional[Dict[str, Any]]:
294
+ """Remove and return session info."""
295
+ with _sessions_lock:
296
+ return _sessions.pop(task_id or "default", None)
297
+
298
+
299
+ def camofox_soft_cleanup(task_id: Optional[str] = None) -> bool:
300
+ """Drop only the local tracking entry (``True``) for managed profiles, which must
301
+ survive across agent tasks; ``False`` for ephemeral sessions so the caller falls back
302
+ to :func:`camofox_close`."""
303
+ camofox_cfg = _get_camofox_config()
304
+ if _managed_persistence_enabled(camofox_cfg) or _camofox_identity_override(task_id, camofox_cfg):
305
+ _drop_session(task_id)
306
+ logger.debug("Camofox soft cleanup for task %s (managed persistence)", task_id)
307
+ return True
308
+ return False
309
+
310
+
311
+ # ---- HTTP helpers ----
312
+ def _request(method: str, path: str, timeout: Optional[int] = None, **kwargs: Any) -> requests.Response:
313
+ """Issue an authenticated request to camofox and return the raised-for-status response."""
314
+ resp = getattr(requests, method)(f"{get_camofox_url()}{path}", headers=_auth_headers(),
315
+ timeout=_get_command_timeout() if timeout is None else timeout, **kwargs)
316
+ resp.raise_for_status()
317
+ return resp
318
+
319
+
320
+ def _post(path: str, body: dict, timeout: Optional[int] = None) -> dict:
321
+ return _request("post", path, timeout, json=body).json()
322
+
323
+
324
+ def _get(path: str, params: dict = None, timeout: Optional[int] = None) -> dict:
325
+ return _request("get", path, timeout, params=params).json()
326
+
327
+
328
+ def _get_raw(path: str, params: dict = None, timeout: Optional[int] = None) -> requests.Response:
329
+ """GET and return the raw response (for binary data)."""
330
+ return _request("get", path, timeout, params=params)
331
+
332
+
333
+ def _delete(path: str, body: dict = None, timeout: Optional[int] = None) -> dict:
334
+ return _request("delete", path, timeout, json=body).json()
335
+
336
+
337
+ # ---- Tool implementations ----
338
+ def _tab_path(session: Dict[str, Any], suffix: str) -> str:
339
+ return f"/tabs/{session['tab_id']}/{suffix}"
340
+
341
+
342
+ def _user_params(session: Dict[str, Any]) -> Dict[str, str]:
343
+ return {"userId": session["user_id"]}
344
+
345
+
346
+ def _snapshot_data(session: Dict[str, Any]) -> dict:
347
+ return _get(_tab_path(session, "snapshot"), params=_user_params(session))
348
+
349
+
350
+ def _parse_snapshot_images(snapshot: str) -> list[Dict[str, str]]:
351
+ """Images from an accessibility snapshot: ``img "alt" [eN]`` entries with the URL on
352
+ the following ``/url:`` line (Camofox has no /images endpoint)."""
353
+ images = []
354
+ lines = snapshot.split("\n")
355
+ for i, line in enumerate(lines):
356
+ stripped = line.strip()
357
+ if not stripped.startswith(("- img ", "img ")):
358
+ continue
359
+ alt_match = re.search(r'img\s+"([^"]*)"', stripped)
360
+ url_match = re.search(r'/url:\s*(\S+)', lines[i + 1].strip()) if i + 1 < len(lines) else None
361
+ alt, src = (alt_match.group(1) if alt_match else ""), (url_match.group(1) if url_match else "")
362
+ if alt or src:
363
+ images.append({"src": src, "alt": alt})
364
+ return images
365
+
366
+
367
+ def _fetch_snapshot(session: Dict[str, Any]) -> tuple[str, int]:
368
+ """``(snapshot_text, refs_count)`` truncated like the main browser tool (line boundaries,
369
+ full tree stored to cache/web, read_file pointer appended). Lazy import: ``browser_tool``
370
+ imports this module."""
371
+ from tools.browser_tool_snapshot import _truncate_snapshot
372
+ from tools.browser_tool import get_browser_snapshot_threshold
373
+ data = _snapshot_data(session)
374
+ snapshot, threshold = data.get("snapshot", ""), get_browser_snapshot_threshold()
375
+ if len(snapshot) > threshold:
376
+ snapshot = _truncate_snapshot(snapshot, max_chars=threshold)
377
+ return snapshot, data.get("refsCount", 0)
378
+
379
+
380
+ def _navigate_tab(task_id: Optional[str], browser_url: str) -> tuple[Dict[str, Any], dict]:
381
+ """Open ``browser_url`` in the task's tab (creating it if missing) and return
382
+ ``(session, navigate_response)``. A 404 on the existing tab means the server
383
+ garbage-collected it — recreate instead of failing."""
384
+ session = _get_session(task_id)
385
+ if session["tab_id"]:
386
+ try:
387
+ data = _post(_tab_path(session, "navigate"), {"userId": session["user_id"], "url": browser_url}, timeout=60)
388
+ return session, data
389
+ except requests.HTTPError as e:
390
+ if e.response is None or e.response.status_code != 404:
391
+ raise
392
+ logger.warning("Camofox tab %s returned 404 — tab was garbage collected. Creating a fresh tab.",
393
+ session["tab_id"])
394
+ session["tab_id"] = None
395
+ return _ensure_tab(task_id, browser_url), {"ok": True, "url": browser_url}
396
+
397
+
398
+ def camofox_navigate(url: str, task_id: Optional[str] = None) -> str:
399
+ """Navigate to a URL via Camofox."""
400
+ try:
401
+ browser_url, rewrite_info = _rewrite_loopback_url_for_camofox(url)
402
+ session, data = _navigate_tab(task_id, browser_url)
403
+ result = {"success": True, "url": data.get("url", browser_url), "title": data.get("title", "")}
404
+ if rewrite_info:
405
+ result["requested_url"], result["url_rewrite"] = url, rewrite_info
406
+ result["warning"] = ("Rewrote loopback URL for Docker-hosted Camofox: "
407
+ f"{rewrite_info['from']} -> {rewrite_info['to']}")
408
+ vnc = get_vnc_url()
409
+ if vnc:
410
+ result["vnc_url"] = vnc
411
+ result["vnc_hint"] = ("Browser is visible via VNC. "
412
+ "Share this link with the user so they can watch the browser live.")
413
+ try: # Auto-take a compact snapshot so the model can act immediately.
414
+ result["snapshot"], result["element_count"] = _fetch_snapshot(session)
415
+ except Exception:
416
+ pass # Navigation succeeded; snapshot is a bonus
417
+ return json.dumps(result)
418
+ except requests.HTTPError as e:
419
+ return tool_error(f"Navigation failed: {e}", success=False)
420
+ except requests.ConnectionError:
421
+ return json.dumps({"success": False, "error": (
422
+ f"Cannot connect to Camofox at {get_camofox_url()}. "
423
+ "Is the server running? Start with: npm start (in camofox-browser dir) "
424
+ "or: docker run -p 9377:9377 -e CAMOFOX_PORT=9377 jo-inc/camofox-browser")})
425
+ except Exception as e:
426
+ return tool_error(str(e), success=False)
427
+
428
+
429
+ def _camofox_private_page_block(session: Dict[str, Any], task_id: Optional[str], action: str) -> Optional[str]:
430
+ """Blocked payload when the current page is private/internal, else None.
431
+
432
+ Mirrors the ``_camofox_eval`` guard in browser_tool.py: page-state reads on a non-local
433
+ backend can leak an intranet/metadata page the terminal can't reach. Only active when
434
+ the SSRF guard applies (non-local backend, not a local sidecar, ``allow_private_urls``
435
+ unset); fail-open on probe failure like sibling guards. Lazy import (cycle).
436
+ """
437
+ from tools.browser_tool_eval_policy import _camofox_current_page_private_url, _eval_ssrf_guard_active
438
+ if not _eval_ssrf_guard_active(task_id or "default"):
439
+ return None
440
+ blocked_url = _camofox_current_page_private_url(session["tab_id"], session["user_id"])
441
+ if not blocked_url:
442
+ return None
443
+ return json.dumps({"success": False, "error": (
444
+ "Blocked: page URL targets a private or internal address "
445
+ f"({blocked_url}). Refusing to {action} on this page in this browser mode.")}, ensure_ascii=False)
446
+
447
+
448
+ def _require_tab(task_id: Optional[str], action: Optional[str] = None) -> tuple[Dict[str, Any], Optional[str]]:
449
+ """Return ``(session, error_payload)``: error when no tab exists or, if ``action`` given, the page is private."""
450
+ session = _get_session(task_id)
451
+ if not session["tab_id"]:
452
+ return session, tool_error(_NO_SESSION_ERROR, success=False)
453
+ return session, (_camofox_private_page_block(session, task_id, action) if action is not None else None)
454
+
455
+
456
+ def _with_tab(task_id: Optional[str], guard_action: Optional[str], body: Callable[[Dict[str, Any]], str]) -> str:
457
+ """Require a tab (+ private-page guard when ``guard_action`` is set), then run ``body(session)``;
458
+ any exception becomes a ``tool_error``."""
459
+ try:
460
+ session, blocked = _require_tab(task_id, guard_action)
461
+ if blocked:
462
+ return blocked
463
+ return body(session)
464
+ except Exception as e:
465
+ return tool_error(str(e), success=False)
466
+
467
+
468
+ def _tab_action(task_id: Optional[str], guard_action: Optional[str], suffix: str,
469
+ body: Dict[str, Any], result: Callable[[dict], dict]) -> str:
470
+ """Simple tab action: POST ``body`` to ``/tabs/<id>/<suffix>``, build the result."""
471
+ return _with_tab(task_id, guard_action, lambda session: json.dumps(
472
+ result(_post(_tab_path(session, suffix), {"userId": session["user_id"], **body}))))
473
+
474
+
475
+ def camofox_snapshot(full: bool = False, task_id: Optional[str] = None, user_task: Optional[str] = None) -> str:
476
+ """Accessibility tree snapshot. ``user_task`` is deprecated and ignored —
477
+ oversized snapshots always truncate-and-store (no LLM summarization)."""
478
+ def body(session):
479
+ snapshot, refs_count = _fetch_snapshot(session)
480
+ return json.dumps({"success": True, "snapshot": snapshot, "element_count": refs_count})
481
+ return _with_tab(task_id, "read a page snapshot", body)
482
+
483
+
484
+ def camofox_click(ref: str, task_id: Optional[str] = None) -> str:
485
+ """Click an element by ref via Camofox."""
486
+ clean_ref = ref.lstrip("@") # our tool convention prefixes refs with @
487
+ return _tab_action(task_id, "click", "click", {"ref": clean_ref},
488
+ lambda data: {"success": True, "clicked": clean_ref, "url": data.get("url", "")})
489
+
490
+
491
+ def camofox_type(ref: str, text: str, task_id: Optional[str] = None) -> str:
492
+ """Type text into an element by ref via Camofox."""
493
+ try:
494
+ session, blocked = _require_tab(task_id, "type")
495
+ if blocked:
496
+ return blocked
497
+ clean_ref = ref.lstrip("@")
498
+ _post(_tab_path(session, "type"), {"userId": session["user_id"], "ref": clean_ref, "text": text})
499
+ from agent.display import redact_browser_typed_text_for_display, redact_tool_args_for_display
500
+ # Match browser_tool.browser_type: the raw text is typed into the page, but the
501
+ # returned display value is run through the secret-pattern redactor so API keys /
502
+ # tokens don't leak into tool progress or chat history.
503
+ display_text = (redact_tool_args_for_display("browser_type", {"text": text}) or {})["text"]
504
+ response = {"success": True, "typed": display_text, "element": clean_ref}
505
+ return json.dumps(redact_browser_typed_text_for_display(response, text))
506
+ except Exception as e:
507
+ from agent.display import redact_browser_typed_text_for_display
508
+ return tool_error(redact_browser_typed_text_for_display(str(e), text), success=False)
509
+
510
+
511
+ def camofox_scroll(direction: str, task_id: Optional[str] = None) -> str:
512
+ """Scroll the page via Camofox."""
513
+ return _tab_action(task_id, None, "scroll", {"direction": direction},
514
+ lambda data: {"success": True, "scrolled": direction})
515
+
516
+
517
+ def camofox_back(task_id: Optional[str] = None) -> str:
518
+ """Navigate back via Camofox."""
519
+ return _tab_action(task_id, None, "back", {}, lambda data: {"success": True, "url": data.get("url", "")})
520
+
521
+
522
+ def camofox_press(key: str, task_id: Optional[str] = None) -> str:
523
+ """Press a keyboard key via Camofox."""
524
+ return _tab_action(task_id, "press", "press", {"key": key}, lambda data: {"success": True, "pressed": key})
525
+
526
+
527
+ def camofox_close(task_id: Optional[str] = None) -> str:
528
+ """Close the browser session via Camofox."""
529
+ try:
530
+ session = _drop_session(task_id)
531
+ if session:
532
+ _delete(f"/sessions/{session['user_id']}")
533
+ return json.dumps({"success": True, "closed": True})
534
+ except Exception as e:
535
+ return json.dumps({"success": True, "closed": True, "warning": str(e)})
536
+
537
+
538
+ def camofox_get_images(task_id: Optional[str] = None) -> str:
539
+ """Get images on the current page via Camofox (parsed from the snapshot)."""
540
+ def body(session):
541
+ images = _parse_snapshot_images(_snapshot_data(session).get("snapshot", ""))
542
+ return json.dumps({"success": True, "images": images, "count": len(images)})
543
+ return _with_tab(task_id, "extract page images", body)
544
+
545
+
546
+ def _vision_llm_settings() -> tuple[float, float]:
547
+ """``auxiliary.vision`` ``(timeout, temperature)``; defaults 120s / 0.1 on any config error."""
548
+ try:
549
+ cfg = cfg_get(load_config(), "auxiliary", "vision", default={})
550
+ return float(cfg.get("timeout", 120)), float(cfg.get("temperature", 0.1))
551
+ except Exception:
552
+ return 120.0, 0.1
553
+
554
+
555
+ def _save_screenshot(content: bytes) -> str:
556
+ """Write PNG bytes under ``$HERMES_HOME/browser_screenshots`` and return the path."""
557
+ from hermes_constants import get_hermes_home
558
+ screenshots_dir = get_hermes_home() / "browser_screenshots"
559
+ screenshots_dir.mkdir(parents=True, exist_ok=True)
560
+ screenshot_path = str(screenshots_dir / f"browser_screenshot_{uuid.uuid4().hex[:8]}.png")
561
+ with open(screenshot_path, "wb") as f:
562
+ f.write(content)
563
+ return screenshot_path
564
+
565
+
566
+ def camofox_vision(question: str, annotate: bool = False, task_id: Optional[str] = None) -> str:
567
+ """Take a screenshot and analyze it with vision AI via Camofox."""
568
+ def body(session):
569
+ resp = _get_raw(_tab_path(session, "screenshot"), params=_user_params(session))
570
+ screenshot_path = _save_screenshot(resp.content)
571
+ img_b64 = base64.b64encode(resp.content).decode("utf-8")
572
+ annotation_context = ""
573
+ if annotate:
574
+ try:
575
+ snapshot = _snapshot_data(session).get("snapshot", "")
576
+ annotation_context = f"\n\nAccessibility tree (element refs for interaction):\n{snapshot[:3000]}"
577
+ except Exception:
578
+ pass
579
+ # The screenshot itself cannot be redacted, but the text-based accessibility snippet
580
+ # sent alongside it must not leak secret values.
581
+ from agent.redact import redact_sensitive_text
582
+ from agent.auxiliary_client import call_llm
583
+ vision_prompt = f"Analyze this browser screenshot and answer: {question}{redact_sensitive_text(annotation_context)}"
584
+ timeout, temperature = _vision_llm_settings()
585
+ response = call_llm(
586
+ messages=[{"role": "user", "content": [
587
+ {"type": "text", "text": vision_prompt},
588
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_b64}"}}]}],
589
+ task="vision", temperature=temperature, timeout=timeout)
590
+ analysis = (response.choices[0].message.content or "").strip() if response.choices else ""
591
+ # Redact secrets the vision LLM may have read from the screenshot.
592
+ return json.dumps({"success": True, "analysis": redact_sensitive_text(analysis), "screenshot_path": screenshot_path})
593
+ return _with_tab(task_id, "capture a screenshot", body)
594
+
595
+
596
+ def camofox_console(clear: bool = False, task_id: Optional[str] = None) -> str:
597
+ """Console output is not exposed by the Camofox REST API; return an empty result with a note."""
598
+ return json.dumps({
599
+ "success": True, "console_messages": [], "js_errors": [], "total_messages": 0, "total_errors": 0,
600
+ "note": "Console log capture is not available with the Camofox backend. "
601
+ "Use browser_snapshot or browser_vision to inspect page state."})
tools/browser_dialog_tool.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent-facing tool: respond to a native JS dialog captured by the CDP supervisor.
2
+
3
+ Response-only: the agent reads ``pending_dialogs`` from ``browser_snapshot``,
4
+ then calls ``browser_dialog(action=...)``. Gated on ``_browser_cdp_check`` so it
5
+ appears together with ``browser_cdp``. Design: ``website/docs/developer-guide/browser-supervisor.md``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from typing import Any, Dict, Optional
12
+
13
+ from tools.browser_supervisor import SUPERVISOR_REGISTRY
14
+ from tools.registry import registry
15
+
16
+ BROWSER_DIALOG_SCHEMA: Dict[str, Any] = {
17
+ "name": "browser_dialog",
18
+ "description": (
19
+ "Respond to a native JavaScript dialog (alert / confirm / prompt / "
20
+ "beforeunload) that is currently blocking the page.\n\n"
21
+ "**Workflow:** call ``browser_snapshot`` first — if a dialog is open, "
22
+ "it appears in the ``pending_dialogs`` field with ``id``, ``type``, "
23
+ "and ``message``. Then call this tool with ``action='accept'`` or "
24
+ "``action='dismiss'``.\n\n"
25
+ "**Prompt dialogs:** pass ``prompt_text`` to supply the response "
26
+ "string. Ignored for alert/confirm/beforeunload.\n\n"
27
+ "**Multiple dialogs:** if more than one dialog is queued (rare — "
28
+ "happens when a second dialog fires while the first is still open), "
29
+ "pass ``dialog_id`` from the snapshot to disambiguate.\n\n"
30
+ "**Availability:** only present when a CDP-capable backend is "
31
+ "attached — Browserbase sessions, local Chromium-family browser via "
32
+ "``/browser connect``, or ``browser.cdp_url`` in config.yaml. "
33
+ "Not available on Camofox (REST-only) or the default Playwright "
34
+ "local browser (CDP port is hidden)."
35
+ ),
36
+ "parameters": {
37
+ "type": "object",
38
+ "properties": {
39
+ "action": {
40
+ "type": "string",
41
+ "enum": ["accept", "dismiss"],
42
+ "description": (
43
+ "'accept' clicks OK / returns the prompt text. "
44
+ "'dismiss' clicks Cancel / returns null from prompt(). "
45
+ "For ``beforeunload`` dialogs: 'accept' allows the "
46
+ "navigation, 'dismiss' keeps the page."
47
+ ),
48
+ },
49
+ "prompt_text": {
50
+ "type": "string",
51
+ "description": (
52
+ "Response string for a ``prompt()`` dialog. Ignored for "
53
+ "other dialog types. Defaults to empty string."
54
+ ),
55
+ },
56
+ "dialog_id": {
57
+ "type": "string",
58
+ "description": (
59
+ "Specific dialog to respond to, from "
60
+ "``browser_snapshot.pending_dialogs[].id``. Required "
61
+ "only when multiple dialogs are queued."
62
+ ),
63
+ },
64
+ },
65
+ "required": ["action"],
66
+ },
67
+ }
68
+
69
+
70
+ def browser_dialog(
71
+ action: str,
72
+ prompt_text: Optional[str] = None,
73
+ dialog_id: Optional[str] = None,
74
+ task_id: Optional[str] = None,
75
+ ) -> str:
76
+ """Respond to a pending dialog on the active task's CDP supervisor."""
77
+ supervisor = SUPERVISOR_REGISTRY.get(task_id or "default")
78
+ if supervisor is None:
79
+ return json.dumps({
80
+ "success": False,
81
+ "error": (
82
+ "No CDP supervisor is attached to this task. Either the "
83
+ "browser backend doesn't expose CDP (Camofox, default "
84
+ "Playwright) or no browser session has been started yet. "
85
+ "Call browser_navigate or /browser connect first."
86
+ ),
87
+ })
88
+ result = supervisor.respond_to_dialog(action=action, prompt_text=prompt_text, dialog_id=dialog_id)
89
+ if result.get("ok"):
90
+ return json.dumps({"success": True, "action": action, "dialog": result.get("dialog", {})})
91
+ return json.dumps({"success": False, "error": result.get("error", "unknown error")})
92
+
93
+
94
+ def _browser_dialog_check() -> bool:
95
+ """Gate: same as ``browser_cdp`` so the two tools appear/disappear together."""
96
+ from tools.browser_cdp_tool import _browser_cdp_check
97
+
98
+ return _browser_cdp_check()
99
+
100
+
101
+ registry.register(
102
+ name="browser_dialog",
103
+ toolset="browser-cdp",
104
+ schema=BROWSER_DIALOG_SCHEMA,
105
+ handler=lambda args, **kw: browser_dialog(action=args.get("action", ""), prompt_text=args.get("prompt_text"),
106
+ dialog_id=args.get("dialog_id"), task_id=kw.get("task_id")),
107
+ check_fn=_browser_dialog_check,
108
+ emoji="💬",
109
+ )
110
+
111
+
112
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
113
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
114
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
115
+ # The whole block is removed by reverting the commit that added it.
116
+ import logging # noqa: F401,E402
117
+
118
+
119
+ _PLUGIN_COMPAT_LAZY = {
120
+ 'logger': ('tools.approval', 'logger'),
121
+ }
122
+
123
+
124
+ def __getattr__(name): # PEP 562 — lazy so no import cycles
125
+ target = _PLUGIN_COMPAT_LAZY.get(name)
126
+ if target is None:
127
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
128
+ import importlib
129
+ from hermes_cli.plugin_compat import warn_once
130
+ warn_once(__name__, name, *target)
131
+ return getattr(importlib.import_module(target[0]), target[1])
132
+ # ---- END PLUGIN-COMPAT ----
tools/browser_extension_router.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Registry-level browser extension router.
2
+
3
+ Agent-side half of browser-extension-control: decides, per ``browser_*`` handler
4
+ invocation, whether an attached extension controller (via
5
+ :mod:`gateway.browser_control_broker`) or the legacy backend executes it.
6
+
7
+ Routing contract (see ``tests/tools/test_browser_extension_router.py``):
8
+ - Feature off ⇒ legacy, broker never touched, ``fallback()`` called exactly once.
9
+ - No server-bound identity ⇒ legacy.
10
+ - Bound identity ⇒ authoritative extension lane; missing/ambiguous scope,
11
+ disconnect, or capability mismatch fail closed (never jump to another browser).
12
+ - Selected controller ⇒ authoritative; its errors propagate, legacy never retried.
13
+ - ``args`` is never mutated.
14
+
15
+ :func:`routed_browser_handler` resolves the flag and broker lazily on every call
16
+ so importing this module never pulls in the gateway and config changes apply
17
+ without restart.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import logging
24
+ from typing import Any, Callable, Dict, Optional, Tuple
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def _bound_identity() -> Tuple[Optional[str], Optional[str], Optional[str]]:
30
+ """(session_id, principal_id, transport_family) from the session context."""
31
+ from gateway.session_context import get_session_env
32
+
33
+ return tuple( # type: ignore[return-value]
34
+ get_session_env(key, "") or None
35
+ for key in ("HERMES_SESSION_ID", "HERMES_BROWSER_CONTROL_PRINCIPAL",
36
+ "HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY")
37
+ )
38
+
39
+
40
+ def _controller_unavailable(message: str) -> Exception:
41
+ from gateway.browser_control_broker import ControllerUnavailable
42
+
43
+ return ControllerUnavailable(message)
44
+
45
+
46
+ def extension_controller_available(action: str) -> bool:
47
+ """Whether this request owns one exact controller capable of ``action``.
48
+ Runs during tool-schema assembly inside the request's session context;
49
+ consults the process-local broker directly and fails closed on any gap."""
50
+ try:
51
+ from gateway.browser_control_broker import browser_control_enabled, get_browser_control_broker
52
+
53
+ if not browser_control_enabled():
54
+ return False
55
+ session_id, principal_id, transport_family = identity = _bound_identity()
56
+ if not all(identity):
57
+ return False
58
+ broker = get_browser_control_broker()
59
+ scope = broker.scope_for_session(session_id=session_id, principal_id=principal_id, transport_family=transport_family)
60
+ return scope is not None and broker.select(scope, action) is not None
61
+ except Exception:
62
+ logger.debug("browser extension availability check failed for %s", action, exc_info=True)
63
+ return False
64
+
65
+
66
+ def route_browser_tool(
67
+ action: str, args: Dict[str, Any], *, fallback: Callable[[], Any], broker: Any, enabled: bool,
68
+ session_id: Optional[str] = None, task_id: Optional[str] = None, principal_id: Optional[str] = None,
69
+ transport_family: Optional[str] = None, tool_call_id: Optional[str] = "",
70
+ ) -> Any:
71
+ """Route one browser action through the extension-control broker.
72
+
73
+ ``broker`` exposes ``scope_for_session(**identity)``, ``select(scope, cap)``
74
+ and ``dispatch(scope, *, action, arguments, tool_call_id)``. ``fallback`` is
75
+ called exactly once when the feature is off or no server-bound identity
76
+ exists; once a controller is selected its result/exception is final.
77
+ """
78
+ if not enabled or not str(principal_id or "").strip() or not str(transport_family or "").strip():
79
+ return fallback()
80
+
81
+ identity = dict(session_id=session_id, task_id=task_id, principal_id=principal_id, transport_family=transport_family)
82
+ scope = broker.scope_for_session(**identity)
83
+ if scope is None:
84
+ # A stamped identity only becomes authoritative once a controller has
85
+ # registered for the lane; unregistered lanes keep the legacy backend,
86
+ # registered-but-offline lanes fail closed.
87
+ lane_bound = getattr(broker, "lane_registered", None)
88
+ if callable(lane_bound) and not lane_bound(**identity):
89
+ return fallback()
90
+ raise _controller_unavailable(f"bound browser controller unavailable for {action}")
91
+
92
+ if broker.select(scope, action) is None:
93
+ raise _controller_unavailable(f"bound browser controller cannot execute {action}")
94
+
95
+ # Controller is authoritative: never retry the legacy backend. Registry
96
+ # handlers must return a string; keep string results byte-identical and
97
+ # serialize decoded JSON values at this boundary.
98
+ result = broker.dispatch(scope, action=action, arguments=args, tool_call_id=tool_call_id)
99
+ return result if isinstance(result, str) else json.dumps(result, ensure_ascii=False)
100
+
101
+
102
+ def current_tool_call_id() -> str:
103
+ """Active tool_call_id bound by the agent executor, or ``""`` when none."""
104
+ try:
105
+ from tools.approval_context import _approval_tool_call_id
106
+
107
+ return _approval_tool_call_id.get() or ""
108
+ except Exception:
109
+ return ""
110
+
111
+
112
+ def routed_browser_handler(
113
+ action: str, args: Dict[str, Any], *, fallback: Callable[[], Any], task_id: Optional[str] = None,
114
+ session_id: Optional[str] = None, principal_id: Optional[str] = None,
115
+ transport_family: Optional[str] = None, tool_call_id: Optional[str] = None,
116
+ ) -> Any:
117
+ """Lazy registry-handler route wrapper for ``browser_*`` tools.
118
+ Feature off (or gateway unimportable) ⇒ the legacy handler runs unchanged."""
119
+ try:
120
+ from gateway.browser_control_broker import browser_control_enabled, get_browser_control_broker
121
+ except Exception as exc: # pragma: no cover - defensive, gateway always present
122
+ logger.debug("browser extension router unavailable (%s); using legacy backend", exc)
123
+ return fallback()
124
+ if not browser_control_enabled():
125
+ return fallback()
126
+
127
+ try:
128
+ env_session, env_principal, env_transport = _bound_identity()
129
+ except Exception:
130
+ env_session = env_principal = env_transport = None
131
+
132
+ return route_browser_tool(
133
+ action, args, fallback=fallback, broker=get_browser_control_broker(), enabled=True,
134
+ session_id=session_id or env_session, task_id=task_id, principal_id=principal_id or env_principal,
135
+ transport_family=transport_family or env_transport,
136
+ tool_call_id=current_tool_call_id() if tool_call_id is None else tool_call_id,
137
+ )
tools/browser_supervisor.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persistent CDP supervisor for browser dialog + frame detection.
2
+
3
+ One ``CDPSupervisor`` per Hermes ``task_id`` with a reachable CDP endpoint: one
4
+ persistent WebSocket, ``Page`` / ``Runtime`` / ``Target`` events on every attached
5
+ session (top page + auto-attached OOPIF / worker targets), pending dialogs + frame
6
+ tree exposed via a thread-safe snapshot. Not in the tool schema — output reaches the
7
+ agent via ``browser_snapshot`` / ``browser_dialog``. Dialog capture and frame tracking
8
+ are mixins (``browser_supervisor_dialogs`` / ``browser_supervisor_frames``).
9
+ Design spec: ``website/docs/developer-guide/browser-supervisor.md``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import contextlib
16
+ import json
17
+ import logging
18
+ import threading
19
+ import time
20
+ from dataclasses import dataclass
21
+ from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING
22
+
23
+ from tools.browser_supervisor_dialogs import (
24
+ DEFAULT_DIALOG_POLICY, DEFAULT_DIALOG_TIMEOUT_S, RECENT_DIALOGS_MAX, _VALID_POLICIES, DialogRecord,
25
+ DialogSupervisionMixin, PendingDialog,
26
+ )
27
+ from tools.browser_supervisor_frames import FrameInfo, FrameTrackingMixin
28
+
29
+ # ``websockets`` costs ~22 ms at import and is only needed once a supervisor connects.
30
+ if TYPE_CHECKING:
31
+ from websockets.asyncio.client import ClientConnection
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ def _redact_cdp_error_text(exc: object) -> str:
37
+ """Redact CDP endpoint credentials from an exception's (or URL's) string form.
38
+ ``websockets`` bakes the raw URL (``?token=`` / ``user:pass@``) into its exception
39
+ messages, so every egress point turning one into log/re-raise text MUST route through
40
+ here; falls back to a fixed sentinel if redaction itself raises (err toward masking)."""
41
+ try:
42
+ from agent.redact import redact_cdp_url
43
+
44
+ return redact_cdp_url(str(exc))
45
+ except Exception:
46
+ return "<error redacted>"
47
+
48
+
49
+ class _LoopUnavailable(RuntimeError):
50
+ """The supervisor loop refused new work (closed / shutting down)."""
51
+
52
+
53
+ def _schedule(coro, loop, *, timeout: float):
54
+ """Run ``coro`` on the supervisor loop from a sync caller and wait for its result."""
55
+ from agent.async_utils import safe_schedule_threadsafe
56
+
57
+ fut = safe_schedule_threadsafe(coro, loop)
58
+ if fut is None:
59
+ raise _LoopUnavailable("Browser supervisor loop unavailable")
60
+ return fut.result(timeout=timeout)
61
+
62
+
63
+ def _fail(error: str) -> Dict[str, Any]:
64
+ return {"ok": False, "error": error}
65
+
66
+
67
+ def _err(exc: BaseException) -> Dict[str, Any]:
68
+ return _fail(f"{type(exc).__name__}: {exc}")
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class SupervisorSnapshot:
73
+ """Read-only snapshot of supervisor state for tool handlers."""
74
+
75
+ pending_dialogs: Tuple[PendingDialog, ...]
76
+ recent_dialogs: Tuple[DialogRecord, ...]
77
+ frame_tree: Dict[str, Any]
78
+ active: bool # False if supervisor is detached/stopped
79
+ cdp_url: str
80
+ task_id: str
81
+
82
+ def to_dict(self) -> Dict[str, Any]:
83
+ """Serialize for inclusion in ``browser_snapshot`` output."""
84
+ out: Dict[str, Any] = {"pending_dialogs": [d.to_dict() for d in self.pending_dialogs], "frame_tree": self.frame_tree}
85
+ if self.recent_dialogs:
86
+ out["recent_dialogs"] = [d.to_dict() for d in self.recent_dialogs]
87
+ return out
88
+
89
+
90
+ class CDPSupervisor(DialogSupervisionMixin, FrameTrackingMixin):
91
+ """One supervisor per (task_id, cdp_url) pair. ``start()`` spawns a daemon thread
92
+ running its own asyncio loop, connects, attaches to the first page target, enables
93
+ domains and auto-attach. ``snapshot()`` / ``respond_to_dialog()`` / ``evaluate_runtime()``
94
+ are sync, thread-safe bridges onto that loop; all CDP I/O lives on the loop."""
95
+
96
+ def __init__(self, task_id: str, cdp_url: str, *, dialog_policy: str = DEFAULT_DIALOG_POLICY,
97
+ dialog_timeout_s: float = DEFAULT_DIALOG_TIMEOUT_S) -> None:
98
+ if dialog_policy not in _VALID_POLICIES:
99
+ raise ValueError(f"Invalid dialog_policy {dialog_policy!r}; must be one of {sorted(_VALID_POLICIES)}")
100
+ self.task_id = task_id
101
+ self.cdp_url = cdp_url
102
+ self.dialog_policy = dialog_policy
103
+ self.dialog_timeout_s = float(dialog_timeout_s)
104
+
105
+ # State protected by ``_state_lock`` for cross-thread reads.
106
+ self._state_lock = threading.Lock()
107
+ self._pending_dialogs: Dict[str, PendingDialog] = {}
108
+ self._recent_dialogs: List[DialogRecord] = []
109
+ self._frames: Dict[str, FrameInfo] = {}
110
+ self._active = False
111
+ # Supervisor loop machinery — populated in start().
112
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
113
+ self._thread: Optional[threading.Thread] = None
114
+ self._ready_event = threading.Event()
115
+ self._start_error: Optional[BaseException] = None
116
+ self._stop_requested = False
117
+ # CDP call tracking (runs on supervisor loop only).
118
+ self._next_call_id = 1
119
+ self._pending_calls: Dict[int, asyncio.Future] = {}
120
+ self._ws: Optional[ClientConnection] = None
121
+ self._page_session_id: Optional[str] = None
122
+ # Dialog auto-dismiss watchdog handles (per dialog id) + id generator.
123
+ self._dialog_watchdogs: Dict[str, asyncio.TimerHandle] = {}
124
+ self._dialog_seq = 0
125
+
126
+ # ── Public sync API ──────────────────────────────────────────────────────
127
+
128
+ def start(self, timeout: float = 15.0) -> None:
129
+ """Launch the background loop and block until attachment completes; raises what attach failed with (redacted)."""
130
+ if self._thread and self._thread.is_alive():
131
+ return
132
+ self._ready_event.clear()
133
+ self._start_error, self._stop_requested = None, False
134
+ self._thread = threading.Thread(target=self._thread_main, name=f"cdp-supervisor-{self.task_id}", daemon=True)
135
+ self._thread.start()
136
+ if not self._ready_event.wait(timeout=timeout):
137
+ self.stop()
138
+ raise TimeoutError(f"CDP supervisor did not attach within {timeout}s "
139
+ f"(cdp_url={_redact_cdp_error_text(self.cdp_url)[:80]}...)")
140
+ if (err := self._start_error) is not None:
141
+ self.stop()
142
+ # ``err`` is a raw ``websockets`` exception embedding the full cdp_url (token /
143
+ # userinfo): re-raise redacted, ``from None`` so the traceback chain leaks nothing.
144
+ raise RuntimeError(f"CDP supervisor failed to start: {_redact_cdp_error_text(err)}") from None
145
+
146
+ def stop(self, timeout: float = 5.0) -> None:
147
+ """Cancel the supervisor task and join the thread."""
148
+ self._stop_requested = True
149
+ loop = self._loop
150
+ if loop is not None and loop.is_running():
151
+ # Close the WebSocket from inside the loop so ``async for raw in self._ws``
152
+ # returns cleanly, ``_run`` hits its ``finally``, THEN the thread exits.
153
+ with contextlib.suppress(Exception): # loop already shutting down / close timed out
154
+ _schedule(self._close_ws(), loop, timeout=2.0)
155
+ if self._thread is not None:
156
+ self._thread.join(timeout=timeout)
157
+ self._set_active(False)
158
+
159
+ def _set_active(self, value: bool) -> None:
160
+ with self._state_lock:
161
+ self._active = value
162
+
163
+ def snapshot(self) -> SupervisorSnapshot:
164
+ """Return an immutable snapshot of current state."""
165
+ with self._state_lock:
166
+ return SupervisorSnapshot(
167
+ pending_dialogs=tuple(self._pending_dialogs.values()),
168
+ recent_dialogs=tuple(self._recent_dialogs[-RECENT_DIALOGS_MAX:]),
169
+ frame_tree=self._build_frame_tree_locked(),
170
+ active=self._active, cdp_url=self.cdp_url, task_id=self.task_id,
171
+ )
172
+
173
+ def respond_to_dialog(self, action: str, *, prompt_text: Optional[str] = None,
174
+ dialog_id: Optional[str] = None, timeout: float = 10.0) -> Dict[str, Any]:
175
+ """Accept/dismiss a pending dialog (sync bridge onto the supervisor loop). Returns
176
+ ``{"ok": True, "dialog"}`` or ``{"ok": False, "error"}`` for recoverable errors."""
177
+ if action not in {"accept", "dismiss"}:
178
+ return _fail(f"action must be 'accept' or 'dismiss', got {action!r}")
179
+ with self._state_lock:
180
+ if not self._active:
181
+ return _fail("supervisor is not active")
182
+ pending = list(self._pending_dialogs.values())
183
+ if not pending:
184
+ return _fail("no dialog is currently open")
185
+ if dialog_id:
186
+ dialog = self._pending_dialogs.get(dialog_id)
187
+ if dialog is None:
188
+ return _fail(f"dialog_id {dialog_id!r} not found (known: {sorted(self._pending_dialogs)})")
189
+ elif len(pending) > 1:
190
+ return _fail(f"{len(pending)} pending dialogs; specify dialog_id. Candidates: {[d.id for d in pending]}")
191
+ else:
192
+ dialog = pending[0]
193
+ loop = self._loop
194
+ if loop is None:
195
+ return _fail("supervisor loop is not running")
196
+ try:
197
+ coro = self._handle_dialog_cdp(dialog, accept=(action == "accept"), prompt_text=prompt_text or "")
198
+ _schedule(coro, loop, timeout=timeout)
199
+ except _LoopUnavailable as e:
200
+ return _fail(str(e))
201
+ except Exception as e:
202
+ return _err(e)
203
+ return {"ok": True, "dialog": dialog.to_dict()}
204
+
205
+ def evaluate_runtime(self, expression: str, *, return_by_value: bool = True,
206
+ await_promise: bool = True, timeout: float = 10.0) -> Dict[str, Any]:
207
+ """Evaluate ``expression`` in the page's Runtime context over the live WS.
208
+ Returns ``{"ok": True, "result", "result_type"}`` or ``{"ok": False, "error"}``.
209
+ ``return_by_value=True`` JSON-serializes the result (DevTools-console
210
+ semantics); non-serializable objects come back as a description string."""
211
+ loop = self._loop
212
+ if loop is None or not loop.is_running():
213
+ return _fail("supervisor loop is not running")
214
+ with self._state_lock:
215
+ active, session_id = self._active, self._page_session_id
216
+ if not active:
217
+ return _fail("supervisor is not active")
218
+ if not session_id:
219
+ return _fail("supervisor has no attached page session")
220
+
221
+ def _run_eval(by_value: bool) -> Dict[str, Any]:
222
+ # userGesture: clipboard / fullscreen APIs need user activation.
223
+ params = {"expression": expression, "returnByValue": by_value,
224
+ "awaitPromise": await_promise, "userGesture": True}
225
+ coro = self._cdp("Runtime.evaluate", params, session_id=session_id, timeout=timeout)
226
+ return _schedule(coro, loop, timeout=timeout + 1)
227
+
228
+ try:
229
+ response = _run_eval(return_by_value)
230
+ except Exception as exc:
231
+ # Deep-serializing live DOM nodes / NodeLists / Window can blow past
232
+ # CDP's recursion guard (``Object reference chain is too long``).
233
+ # Retry once with returnByValue=False so Chrome returns the description.
234
+ if not (return_by_value and "reference chain is too long" in str(exc).lower()):
235
+ return _err(exc)
236
+ try:
237
+ response = _run_eval(False)
238
+ except Exception as exc2:
239
+ return _err(exc2)
240
+
241
+ # Response: {"result": {"result": {"type", "value", ...}, "exceptionDetails"?}}
242
+ result_payload = response.get("result", {}) if isinstance(response, dict) else {}
243
+ exception_details = result_payload.get("exceptionDetails")
244
+ if exception_details:
245
+ exc_text = exception_details.get("text") or "JavaScript exception"
246
+ description = (exception_details.get("exception") or {}).get("description")
247
+ return _fail(f"{exc_text}: {description}" if description else exc_text)
248
+
249
+ result_obj = result_payload.get("result", {})
250
+ result_type = result_obj.get("type", "undefined")
251
+ if "value" in result_obj:
252
+ value = result_obj["value"]
253
+ elif result_type == "undefined":
254
+ value = None
255
+ else:
256
+ # Non-serializable (functions, DOM nodes…) — give the model the browser's description.
257
+ value = result_obj.get("description") or result_obj.get("unserializableValue")
258
+ return {"ok": True, "result": value, "result_type": result_type}
259
+
260
+ def focus_page(self, origin: str, *, accept: Optional[str] = None, timeout: float = 10.0) -> Dict[str, Any]:
261
+ """Re-attach the supervisor's page session to an open page target on ``origin``
262
+ (``scheme://host[:port]``). The initial attach picks the FIRST page target, but tools
263
+ that open their own tabs (browser_exec) put the login form somewhere else. With
264
+ ``accept`` (a JS expression) the first same-origin tab where it evaluates truthy wins,
265
+ so a login and a checkout tab on one site resolve to the right one. Returns
266
+ ``{"ok": True, "url"}`` or ``{"ok": False, "error"}``; on failure the previous session stays."""
267
+ loop = self._loop
268
+ if loop is None or not loop.is_running():
269
+ return _fail("supervisor loop is not running")
270
+
271
+ async def _attach(target_id: str) -> str:
272
+ attach = await self._cdp("Target.attachToTarget", {"targetId": target_id, "flatten": True}, timeout=timeout)
273
+ sid = attach["result"]["sessionId"]
274
+ await self._enable_page_domains(sid, timeout=timeout)
275
+ await self._install_dialog_bridge(sid)
276
+ return sid
277
+
278
+ async def _focus() -> Dict[str, Any]:
279
+ from agent.vault_store import normalize_origin
280
+ targets = (await self._cdp("Target.getTargets", timeout=timeout)).get("result", {}).get("targetInfos", [])
281
+ candidates = []
282
+ for t in targets:
283
+ url = str(t.get("url") or "")
284
+ try:
285
+ # origin="" = any http(s) page (used to FIND the login tab before its origin is known)
286
+ if t.get("type") == "page" and url.startswith(("http://", "https://")) \
287
+ and (not origin or normalize_origin(url) == origin):
288
+ candidates.append((t["targetId"], url))
289
+ except Exception:
290
+ continue
291
+ for target_id, url in candidates:
292
+ sid = await _attach(target_id)
293
+ if accept:
294
+ probe = await self._cdp("Runtime.evaluate", {"expression": accept, "returnByValue": True},
295
+ session_id=sid, timeout=timeout)
296
+ if not probe.get("result", {}).get("result", {}).get("value"):
297
+ await self._cdp("Target.detachFromTarget", {"sessionId": sid}, timeout=timeout)
298
+ continue
299
+ with self._state_lock:
300
+ self._page_session_id = sid
301
+ return {"ok": True, "url": url}
302
+ return _fail(f"no open page on {origin or 'any site'}" + (" with the expected form" if accept and candidates else ""))
303
+
304
+ try:
305
+ return _schedule(_focus(), loop, timeout=timeout + 1)
306
+ except Exception as exc:
307
+ return _err(exc)
308
+
309
+ # ── Supervisor loop internals ────────────────────────────────────────────
310
+
311
+ def _thread_main(self) -> None:
312
+ """Entry point for the supervisor's dedicated thread."""
313
+ loop = asyncio.new_event_loop()
314
+ self._loop = loop
315
+ try:
316
+ asyncio.set_event_loop(loop)
317
+ loop.run_until_complete(self._run())
318
+ except BaseException as e: # noqa: BLE001 — propagate via _start_error
319
+ if not self._fail_start(e):
320
+ logger.warning("CDP supervisor %s crashed: %s", self.task_id, e)
321
+ finally:
322
+ # Cancel + flush remaining tasks before closing the loop to avoid
323
+ # "Task was destroyed but it is pending" warnings.
324
+ with contextlib.suppress(Exception):
325
+ pending = [t for t in asyncio.all_tasks(loop) if not t.done()]
326
+ for t in pending:
327
+ t.cancel()
328
+ if pending:
329
+ loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
330
+ with contextlib.suppress(Exception):
331
+ loop.close()
332
+ self._set_active(False)
333
+
334
+ def _fail_start(self, e: BaseException) -> bool:
335
+ """Propagate ``e`` to ``start()`` if we never got ready; True if it was consumed."""
336
+ if self._ready_event.is_set():
337
+ return False
338
+ self._start_error = e
339
+ self._ready_event.set()
340
+ return True
341
+
342
+ async def _close_ws(self) -> None:
343
+ """Detach and close the current WebSocket, swallowing close errors."""
344
+ ws, self._ws = self._ws, None
345
+ if ws is not None:
346
+ with contextlib.suppress(Exception):
347
+ await ws.close()
348
+
349
+ async def _run(self) -> None:
350
+ """Top-level reconnecting supervisor coroutine. Browserbase tears down the CDP
351
+ socket whenever a short-lived client (agent-browser's per-command CDP client)
352
+ disconnects, so on drop we reset per-session ids, re-attach, and keep going.
353
+ A failure before the first successful attach is fatal for ``start()``."""
354
+ attempt, last_success_at, backoff = 0, 0.0, 0.5
355
+ import websockets # deferred: only supervisors that connect pay the import
356
+ while not self._stop_requested:
357
+ try:
358
+ self._ws = await asyncio.wait_for(websockets.connect(self.cdp_url, max_size=50 * 1024 * 1024), timeout=10.0)
359
+ except Exception as e:
360
+ attempt += 1
361
+ if self._fail_start(e):
362
+ return
363
+ logger.warning("CDP supervisor %s: connect failed (attempt %s): %s",
364
+ self.task_id, attempt, _redact_cdp_error_text(e))
365
+ await asyncio.sleep(min(backoff, 10.0))
366
+ backoff = min(backoff * 2, 10.0)
367
+ continue
368
+
369
+ reader_task = asyncio.create_task(self._read_loop(), name="cdp-reader")
370
+ try:
371
+ # Reset the per-connection page session id; ``_pending_dialogs`` / ``_frames``
372
+ # are deliberately kept — they reconcile as fresh events arrive (worst case a
373
+ # stale dialog entry is rejected with "no dialog is showing", logged only).
374
+ self._page_session_id = None
375
+ await self._attach_initial_page()
376
+ self._set_active(True)
377
+ last_success_at = time.time()
378
+ backoff = 0.5 # reset after a successful attach
379
+ self._ready_event.set()
380
+ await reader_task
381
+ except BaseException as e:
382
+ if self._fail_start(e):
383
+ raise
384
+ logger.warning("CDP supervisor %s: session dropped after %.1fs: %s",
385
+ self.task_id, time.time() - last_success_at, _redact_cdp_error_text(e))
386
+ finally:
387
+ self._set_active(False)
388
+ if not reader_task.done():
389
+ reader_task.cancel()
390
+ with contextlib.suppress(asyncio.CancelledError, Exception):
391
+ await reader_task
392
+ for handle in self._dialog_watchdogs.values():
393
+ handle.cancel()
394
+ self._dialog_watchdogs.clear()
395
+ await self._close_ws()
396
+
397
+ if self._stop_requested:
398
+ return
399
+ logger.debug("CDP supervisor %s: reconnecting in %.1fs...", self.task_id, backoff)
400
+ await asyncio.sleep(backoff)
401
+ backoff = min(backoff * 2, 10.0)
402
+
403
+ async def _attach_initial_page(self) -> None:
404
+ """Find (or create) a page target, attach flattened, enable domains, install dialog bridge."""
405
+ targets = (await self._cdp("Target.getTargets")).get("result", {}).get("targetInfos", [])
406
+ page_target = next((t for t in targets if t.get("type") == "page"), None)
407
+ if page_target is None:
408
+ page_target = (await self._cdp("Target.createTarget", {"url": "about:blank"}))["result"]
409
+ attach = await self._cdp("Target.attachToTarget", {"targetId": page_target["targetId"], "flatten": True})
410
+ self._page_session_id = sid = attach["result"]["sessionId"]
411
+ await self._enable_page_domains(sid, timeout=10.0)
412
+ await self._install_dialog_bridge(sid)
413
+
414
+ async def _cdp(self, method: str, params: Optional[Dict[str, Any]] = None, *,
415
+ session_id: Optional[str] = None, timeout: float = 10.0) -> Dict[str, Any]:
416
+ """Send a CDP command and await its response."""
417
+ if self._ws is None:
418
+ raise RuntimeError("supervisor WebSocket is not connected")
419
+ call_id, self._next_call_id = self._next_call_id, self._next_call_id + 1
420
+ payload: Dict[str, Any] = {"id": call_id, "method": method}
421
+ payload.update({k: v for k, v in (("params", params), ("sessionId", session_id)) if v})
422
+ fut: asyncio.Future = asyncio.get_running_loop().create_future()
423
+ self._pending_calls[call_id] = fut
424
+ await self._ws.send(json.dumps(payload))
425
+ try:
426
+ return await asyncio.wait_for(fut, timeout=timeout)
427
+ finally:
428
+ self._pending_calls.pop(call_id, None)
429
+
430
+ async def _read_loop(self) -> None:
431
+ """Continuously dispatch incoming CDP frames (responses → futures, events → handlers)."""
432
+ assert self._ws is not None
433
+ try:
434
+ async for raw in self._ws:
435
+ if self._stop_requested:
436
+ break
437
+ try:
438
+ msg = json.loads(raw)
439
+ except Exception:
440
+ logger.debug("CDP supervisor: non-JSON frame dropped")
441
+ continue
442
+ if "id" in msg:
443
+ fut = self._pending_calls.pop(msg["id"], None)
444
+ if fut is None or fut.done():
445
+ continue
446
+ if "error" in msg:
447
+ fut.set_exception(RuntimeError(f"CDP error on id={msg['id']}: {msg['error']}"))
448
+ else:
449
+ fut.set_result(msg)
450
+ elif handler := self._EVENT_HANDLERS.get(msg.get("method")):
451
+ result = handler(self, msg.get("params", {}), msg.get("sessionId"))
452
+ if result is not None:
453
+ await result
454
+ except Exception as e:
455
+ logger.debug("CDP read loop exited: %s", e)
456
+
457
+ # CDP event → handler(self, params, session_id). Async handlers return an
458
+ # awaitable that ``_read_loop`` awaits; sync handlers return None.
459
+ _EVENT_HANDLERS: Dict[str, Callable[..., Any]] = {
460
+ **DialogSupervisionMixin.EVENT_HANDLERS, **FrameTrackingMixin.EVENT_HANDLERS
461
+ }
462
+
463
+
464
+ class _SupervisorRegistry:
465
+ """Process-global (task_id → supervisor) map with idempotent start/stop (``SUPERVISOR_REGISTRY``)."""
466
+
467
+ def __init__(self) -> None:
468
+ self._lock = threading.Lock()
469
+ self._by_task: Dict[str, CDPSupervisor] = {}
470
+
471
+ def get(self, task_id: str) -> Optional[CDPSupervisor]:
472
+ with self._lock:
473
+ return self._by_task.get(task_id)
474
+
475
+ def _pop(self, task_id: str) -> Optional[CDPSupervisor]:
476
+ with self._lock:
477
+ return self._by_task.pop(task_id, None)
478
+
479
+ def get_or_start(self, task_id: str, cdp_url: str, *, dialog_policy: str = DEFAULT_DIALOG_POLICY,
480
+ dialog_timeout_s: float = DEFAULT_DIALOG_TIMEOUT_S, start_timeout: float = 15.0) -> CDPSupervisor:
481
+ """Idempotently ensure a supervisor runs for ``(task_id, cdp_url)``; one bound to a
482
+ different ``cdp_url`` or unhealthy (dead thread / stopped loop) is stopped and replaced."""
483
+ with self._lock:
484
+ existing = self._by_task.get(task_id)
485
+ if existing is not None:
486
+ thread, loop = existing._thread, existing._loop
487
+ healthy = thread is not None and thread.is_alive() and loop is not None and loop.is_running()
488
+ if existing.cdp_url == cdp_url and healthy:
489
+ return existing
490
+ self._by_task.pop(task_id, None)
491
+ if existing is not None:
492
+ existing.stop()
493
+
494
+ supervisor = CDPSupervisor(task_id=task_id, cdp_url=cdp_url,
495
+ dialog_policy=dialog_policy, dialog_timeout_s=dialog_timeout_s)
496
+ supervisor.start(timeout=start_timeout)
497
+ with self._lock:
498
+ # Guard against a concurrent get_or_start from another thread.
499
+ already = self._by_task.get(task_id)
500
+ if already is not None and already.cdp_url == cdp_url:
501
+ supervisor.stop()
502
+ return already
503
+ self._by_task[task_id] = supervisor
504
+ return supervisor
505
+
506
+ def stop(self, task_id: str) -> None:
507
+ supervisor = self._pop(task_id)
508
+ if supervisor is not None:
509
+ supervisor.stop()
510
+
511
+ def stop_all(self) -> None:
512
+ """Stop every running supervisor. For shutdown / test teardown."""
513
+ with self._lock:
514
+ items = list(self._by_task.values())
515
+ self._by_task.clear()
516
+ for supervisor in items:
517
+ supervisor.stop()
518
+
519
+
520
+ SUPERVISOR_REGISTRY = _SupervisorRegistry()
521
+
522
+
523
+ __all__ = ["CDPSupervisor", "SUPERVISOR_REGISTRY", "SupervisorSnapshot", "_SupervisorRegistry"]
524
+
525
+
526
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
527
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
528
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
529
+ # The whole block is removed by reverting the commit that added it.
530
+
531
+ CONSOLE_HISTORY_MAX = 50
532
+
533
+ @dataclass
534
+ class ConsoleEvent:
535
+ """Ring buffer entry for console + exception traffic."""
536
+
537
+ ts: float
538
+ level: str # "log" | "error" | "warning" | "exception"
539
+ text: str
540
+ url: Optional[str] = None
541
+
542
+
543
+ _PLUGIN_COMPAT_LAZY = {
544
+ 'DIALOG_BRIDGE_HOST': ('tools.browser_supervisor_dialogs', 'DIALOG_BRIDGE_HOST'),
545
+ 'DIALOG_BRIDGE_URL_PATTERN': ('tools.browser_supervisor_dialogs', 'DIALOG_BRIDGE_URL_PATTERN'),
546
+ 'DIALOG_POLICY_AUTO_ACCEPT': ('tools.browser_supervisor_dialogs', 'DIALOG_POLICY_AUTO_ACCEPT'),
547
+ 'DIALOG_POLICY_AUTO_DISMISS': ('tools.browser_supervisor_dialogs', 'DIALOG_POLICY_AUTO_DISMISS'),
548
+ 'DIALOG_POLICY_MUST_RESPOND': ('tools.browser_supervisor_dialogs', 'DIALOG_POLICY_MUST_RESPOND'),
549
+ 'FRAME_TREE_MAX_ENTRIES': ('tools.browser_supervisor_frames', 'FRAME_TREE_MAX_ENTRIES'),
550
+ 'FRAME_TREE_MAX_OOPIF_DEPTH': ('tools.browser_supervisor_frames', 'FRAME_TREE_MAX_OOPIF_DEPTH'),
551
+ }
552
+
553
+
554
+ def __getattr__(name): # PEP 562 — lazy so no import cycles
555
+ target = _PLUGIN_COMPAT_LAZY.get(name)
556
+ if target is None:
557
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
558
+ import importlib
559
+ from hermes_cli.plugin_compat import warn_once
560
+ warn_once(__name__, name, *target)
561
+ return getattr(importlib.import_module(target[0]), target[1])
562
+ # ---- END PLUGIN-COMPAT ----
tools/browser_supervisor_dialogs.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dialog capture + response half of the CDP supervisor.
2
+
3
+ Two capture paths feed one ``PendingDialog`` queue: native ``Page.javascriptDialogOpening``
4
+ events (answered with ``Page.handleJavaScriptDialog``), and the injected *dialog bridge* —
5
+ a page script rewriting alert/confirm/prompt into a sync XHR to a magic host we intercept
6
+ via the CDP ``Fetch`` domain and answer with ``Fetch.fulfillRequest``. The bridge works on
7
+ Browserbase (whose CDP proxy auto-dismisses native dialogs) because the native dialog never fires.
8
+ ``DialogSupervisionMixin`` relies on state ``CDPSupervisor.__init__`` sets.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import base64
15
+ import json
16
+ import logging
17
+ import time
18
+ from dataclasses import dataclass
19
+ from typing import Any, Callable, Dict, Optional
20
+ from urllib.parse import parse_qs, urlparse
21
+
22
+ # Logger-name parity with the origin module (records must look unchanged).
23
+ logger = logging.getLogger("tools.browser_supervisor")
24
+
25
+
26
+ def _redact_supervisor_text(value: str) -> str:
27
+ """Redact page-originated text before exposing supervisor snapshots."""
28
+ from agent.redact import redact_sensitive_text
29
+
30
+ return redact_sensitive_text(value, force=True)
31
+
32
+
33
+ def _trim_ring(events: list, keep: int) -> list:
34
+ """Cap a ring buffer at ``keep`` entries once it overflows to 2x (slack reduces churn)."""
35
+ return events[-keep:] if len(events) > keep * 2 else events
36
+
37
+
38
+ _REDACTED_FIELDS = frozenset({"message", "default_prompt"})
39
+
40
+
41
+ def _dialog_dict(obj: Any, keys: tuple) -> Dict[str, Any]:
42
+ """Snapshot dict of ``keys`` with page-originated text fields redacted."""
43
+ return {k: _redact_supervisor_text(getattr(obj, k)) if k in _REDACTED_FIELDS else getattr(obj, k) for k in keys}
44
+
45
+
46
+ DIALOG_POLICY_MUST_RESPOND = "must_respond"
47
+ DIALOG_POLICY_AUTO_DISMISS = "auto_dismiss"
48
+ DIALOG_POLICY_AUTO_ACCEPT = "auto_accept"
49
+ _VALID_POLICIES = frozenset(
50
+ {DIALOG_POLICY_MUST_RESPOND, DIALOG_POLICY_AUTO_DISMISS, DIALOG_POLICY_AUTO_ACCEPT}
51
+ )
52
+ DEFAULT_DIALOG_POLICY = DIALOG_POLICY_MUST_RESPOND
53
+ DEFAULT_DIALOG_TIMEOUT_S = 300.0
54
+
55
+ # Last N closed dialogs kept so agents on backends that auto-dismiss server-side
56
+ # (Browserbase) can still observe that a dialog fired.
57
+ RECENT_DIALOGS_MAX = 20
58
+
59
+ # Magic host the bridge XHRs to; intercepted via CDP Fetch before any network
60
+ # resolution, so it never has to exist. Keep ASCII + URL-safe (Fetch patterns gate on it).
61
+ DIALOG_BRIDGE_HOST = "hermes-dialog-bridge.invalid"
62
+ DIALOG_BRIDGE_URL_PATTERN = f"http://{DIALOG_BRIDGE_HOST}/*"
63
+
64
+ # Injected into every frame via Page.addScriptToEvaluateOnNewDocument. Sync GET with
65
+ # query params so the Fetch interceptor never parses a body; unreachable bridge → null
66
+ # so the page still sees *some* behavior. onbeforeunload is left native (can't be
67
+ # prompted synchronously without racing navigation); the native path still records it.
68
+ _DIALOG_BRIDGE_SCRIPT = r"""
69
+ (() => {
70
+ if (window.__hermesDialogBridgeInstalled) return;
71
+ window.__hermesDialogBridgeInstalled = true;
72
+ const ENDPOINT = "http://hermes-dialog-bridge.invalid/";
73
+ function ask(kind, message, defaultPrompt) {
74
+ try {
75
+ const xhr = new XMLHttpRequest();
76
+ const params = new URLSearchParams({
77
+ kind: String(kind || ""),
78
+ message: String(message == null ? "" : message),
79
+ default_prompt: String(defaultPrompt == null ? "" : defaultPrompt),
80
+ });
81
+ xhr.open("GET", ENDPOINT + "?" + params.toString(), false); // sync
82
+ xhr.send(null);
83
+ if (xhr.status !== 200) return null;
84
+ let parsed;
85
+ try { parsed = JSON.parse(xhr.responseText || ""); } catch (e) { return null; }
86
+ if (kind === "alert") return undefined;
87
+ if (kind === "confirm") return Boolean(parsed && parsed.accept);
88
+ if (kind === "prompt") {
89
+ if (!parsed || !parsed.accept) return null;
90
+ return parsed.prompt_text == null ? "" : String(parsed.prompt_text);
91
+ }
92
+ return null;
93
+ } catch (e) {
94
+ return null;
95
+ }
96
+ }
97
+ window.alert = function(message) { ask("alert", message, ""); };
98
+ window.confirm = function(message) {
99
+ const r = ask("confirm", message, "");
100
+ return r === null ? false : Boolean(r);
101
+ };
102
+ window.prompt = function(message, def) {
103
+ const r = ask("prompt", message, def == null ? "" : def);
104
+ return r === null ? null : String(r);
105
+ };
106
+ })();
107
+ """
108
+
109
+
110
+ @dataclass
111
+ class PendingDialog:
112
+ """A JS dialog currently open on some frame's session."""
113
+
114
+ id: str
115
+ type: str # "alert" | "confirm" | "prompt" | "beforeunload"
116
+ message: str
117
+ default_prompt: str
118
+ opened_at: float
119
+ cdp_session_id: str # which attached CDP session the dialog fired in
120
+ frame_id: Optional[str] = None
121
+ # Bridge XHR path: respond via Fetch.fulfillRequest, NOT Page.handleJavaScriptDialog.
122
+ bridge_request_id: Optional[str] = None
123
+
124
+ def to_dict(self) -> Dict[str, Any]:
125
+ return _dialog_dict(self, ("id", "type", "message", "default_prompt", "opened_at", "frame_id"))
126
+
127
+
128
+ @dataclass
129
+ class DialogRecord:
130
+ """A dialog that was opened and then handled (kept briefly in ``recent_dialogs``)."""
131
+
132
+ id: str
133
+ type: str
134
+ message: str
135
+ opened_at: float
136
+ closed_at: float
137
+ closed_by: str # "agent" | "auto_policy" | "remote" | "watchdog"
138
+ frame_id: Optional[str] = None
139
+
140
+ def to_dict(self) -> Dict[str, Any]:
141
+ return _dialog_dict(self, ("id", "type", "message", "opened_at", "closed_at", "closed_by", "frame_id"))
142
+
143
+
144
+ class DialogSupervisionMixin:
145
+ """Dialog event handling for ``CDPSupervisor`` (all methods run on its loop)."""
146
+
147
+ async def _cdp_quiet(self, method: str, params: Dict[str, Any], *, session_id: Optional[str],
148
+ timeout: float, what: str) -> None:
149
+ """Best-effort CDP call: failures are logged at debug and swallowed."""
150
+ try:
151
+ await self._cdp(method, params, session_id=session_id, timeout=timeout)
152
+ except Exception as e:
153
+ logger.debug("%s failed (%s): %s", method, what, e)
154
+
155
+ async def _install_dialog_bridge(self, session_id: str) -> None:
156
+ """Install the dialog-bridge init script + Fetch interceptor on a session. Idempotent at
157
+ the CDP level (Chromium de-dupes identical add-script calls; Fetch.enable replaces prior
158
+ patterns); the final Runtime.evaluate injects into the already-loaded document so
159
+ existing pages pick up the override on reconnect."""
160
+ sid = (session_id or "")[:16]
161
+ steps = (
162
+ ("Page.addScriptToEvaluateOnNewDocument", {"source": _DIALOG_BRIDGE_SCRIPT, "runImmediately": True},
163
+ 5.0, f"dialog bridge sid={sid}"),
164
+ ("Fetch.enable", {"patterns": [{"urlPattern": DIALOG_BRIDGE_URL_PATTERN, "requestStage": "Request"}],
165
+ "handleAuthRequests": False}, 5.0, f"dialog bridge sid={sid}"),
166
+ ("Runtime.evaluate", {"expression": _DIALOG_BRIDGE_SCRIPT, "returnByValue": True},
167
+ 3.0, f"dialog bridge inject sid={sid}"),
168
+ )
169
+ for method, params, timeout, what in steps:
170
+ await self._cdp_quiet(method, params, session_id=session_id, timeout=timeout, what=what)
171
+
172
+ # ── Capture ──────────────────────────────────────────────────────────────
173
+
174
+ async def _on_dialog_opening(self, params: Dict[str, Any], session_id: Optional[str]) -> None:
175
+ self._admit_dialog(
176
+ type=str(params.get("type") or ""), message=str(params.get("message") or ""),
177
+ default_prompt=str(params.get("defaultPrompt") or ""), session_id=session_id, frame_id=params.get("frameId"),
178
+ )
179
+
180
+ async def _on_fetch_paused(self, params: Dict[str, Any], session_id: Optional[str]) -> None:
181
+ """Bridge XHR captured mid-flight — materialize as a pending dialog. The page's JS
182
+ thread is blocked on the XHR until we Fetch.fulfillRequest (agent or watchdog);
183
+ requests for other hosts are forwarded unchanged."""
184
+ url = str(params.get("request", {}).get("url") or "")
185
+ request_id = params.get("requestId")
186
+ if not request_id:
187
+ return
188
+ if DIALOG_BRIDGE_HOST not in url:
189
+ await self._cdp_quiet("Fetch.continueRequest", {"requestId": request_id},
190
+ session_id=session_id, timeout=3.0, what="passthrough")
191
+ return
192
+ q = {k: v[0] for k, v in parse_qs(urlparse(url).query).items()}
193
+ self._admit_dialog(
194
+ type=q.get("kind") or "alert", message=q.get("message", ""), default_prompt=q.get("default_prompt", ""),
195
+ session_id=session_id, frame_id=params.get("frameId"), bridge_request_id=str(request_id),
196
+ )
197
+
198
+ def _admit_dialog(self, *, type: str, message: str, default_prompt: str, session_id: Optional[str],
199
+ frame_id: Optional[str], bridge_request_id: Optional[str] = None) -> None:
200
+ """Create the dialog and apply the policy: auto-respond, or queue + arm the watchdog.
201
+ Auto policies archive FIRST (tagged ``auto_policy``) so the ``closed`` event that
202
+ follows our own response isn't re-archived as ``remote``."""
203
+ self._dialog_seq += 1
204
+ dialog = PendingDialog(
205
+ id=f"d-{self._dialog_seq}", type=type, message=message, default_prompt=default_prompt,
206
+ opened_at=time.time(), cdp_session_id=session_id or self._page_session_id or "",
207
+ frame_id=frame_id, bridge_request_id=bridge_request_id,
208
+ )
209
+ auto = {DIALOG_POLICY_AUTO_DISMISS: (False, ""), DIALOG_POLICY_AUTO_ACCEPT: (True, default_prompt)}.get(
210
+ self.dialog_policy
211
+ )
212
+ if auto is not None:
213
+ with self._state_lock:
214
+ self._archive_dialog_locked(dialog, "auto_policy")
215
+ asyncio.create_task(self._respond_quiet(dialog, accept=auto[0], prompt_text=auto[1]))
216
+ return
217
+ with self._state_lock:
218
+ self._pending_dialogs[dialog.id] = dialog
219
+ self._dialog_watchdogs[dialog.id] = asyncio.get_running_loop().call_later(
220
+ self.dialog_timeout_s,
221
+ lambda: asyncio.create_task(self._dialog_timeout_expired(dialog.id)),
222
+ )
223
+
224
+ # ── Responding ───────────────────────────────────────────────────────────
225
+
226
+ async def _respond(self, dialog: PendingDialog, *, accept: bool, prompt_text: Optional[str]) -> None:
227
+ """Bridge-fulfill for XHR-captured dialogs (swallows failures so the page
228
+ unblocks), else native CDP — ``promptText`` only for prompt dialogs when
229
+ given; raises on CDP failure."""
230
+ session_id = dialog.cdp_session_id or None
231
+ if dialog.bridge_request_id:
232
+ body = json.dumps({"accept": bool(accept), "dialog_id": dialog.id,
233
+ "prompt_text": (prompt_text or "") if dialog.type == "prompt" else ""}).encode()
234
+ await self._cdp_quiet(
235
+ "Fetch.fulfillRequest",
236
+ {"requestId": dialog.bridge_request_id, "responseCode": 200,
237
+ "responseHeaders": [{"name": "Content-Type", "value": "application/json"},
238
+ {"name": "Access-Control-Allow-Origin", "value": "*"}],
239
+ "body": base64.b64encode(body).decode()},
240
+ session_id=session_id, timeout=5.0, what=f"bridge fulfill {dialog.id}",
241
+ )
242
+ return
243
+ params: Dict[str, Any] = {"accept": accept}
244
+ if prompt_text is not None and dialog.type == "prompt":
245
+ params["promptText"] = prompt_text
246
+ await self._cdp("Page.handleJavaScriptDialog", params, session_id=session_id, timeout=5.0)
247
+
248
+ async def _respond_quiet(self, dialog: PendingDialog, *, accept: bool, prompt_text: Optional[str]) -> None:
249
+ """Auto-policy / watchdog response (already archived by the caller); failures logged only."""
250
+ try:
251
+ await self._respond(dialog, accept=accept, prompt_text=prompt_text)
252
+ except Exception as e:
253
+ logger.debug("auto response failed for %s: %s", dialog.id, e)
254
+
255
+ async def _handle_dialog_cdp(self, dialog: PendingDialog, *, accept: bool, prompt_text: str) -> None:
256
+ """Agent response path. The dialog is retired regardless of outcome — a CDP
257
+ error usually means it already closed (browser auto-dismissed after navigation)."""
258
+ try:
259
+ await self._respond(dialog, accept=accept, prompt_text=prompt_text)
260
+ finally:
261
+ self._retire_dialog(dialog.id, "agent")
262
+
263
+ async def _dialog_timeout_expired(self, dialog_id: str) -> None:
264
+ with self._state_lock:
265
+ dialog = self._pending_dialogs.get(dialog_id)
266
+ if dialog is None:
267
+ return
268
+ logger.warning("CDP supervisor %s: dialog %s (%s) auto-dismissed after %ss timeout",
269
+ self.task_id, dialog_id, dialog.type, self.dialog_timeout_s)
270
+ # Archive with watchdog tag BEFORE unblocking the page.
271
+ self._retire_dialog(dialog_id, "watchdog")
272
+ await self._respond_quiet(dialog, accept=False, prompt_text=None)
273
+
274
+ # ── Bookkeeping ──────────────────────────────────────────────────────────
275
+
276
+ def _retire_dialog(self, dialog_id: str, closed_by: str) -> None:
277
+ """Remove a pending dialog (archiving it with ``closed_by``) and cancel its watchdog."""
278
+ with self._state_lock:
279
+ dialog = self._pending_dialogs.pop(dialog_id, None)
280
+ if dialog is not None:
281
+ self._archive_dialog_locked(dialog, closed_by)
282
+ handle = self._dialog_watchdogs.pop(dialog_id, None)
283
+ if handle is not None:
284
+ handle.cancel()
285
+
286
+ def _archive_dialog_locked(self, dialog: PendingDialog, closed_by: str) -> None:
287
+ """Move a pending dialog to the recent_dialogs ring buffer. Must hold state_lock."""
288
+ record = DialogRecord(id=dialog.id, type=dialog.type, message=dialog.message, opened_at=dialog.opened_at,
289
+ closed_at=time.time(), closed_by=closed_by, frame_id=dialog.frame_id)
290
+ self._recent_dialogs = _trim_ring([*self._recent_dialogs, record], RECENT_DIALOGS_MAX)
291
+
292
+ async def _on_dialog_closed(self, params: Dict[str, Any], session_id: Optional[str]) -> None:
293
+ # ``Page.javascriptDialogClosed`` carries only ``result``/``userInput``: match by
294
+ # session id and clear the oldest native dialog on it (the JS thread blocks while
295
+ # a dialog is up, so at most one is in flight). Bridge dialogs resolve via Fetch.
296
+ with self._state_lock:
297
+ candidate = next((d.id for d in self._pending_dialogs.values()
298
+ if d.cdp_session_id == session_id and d.bridge_request_id is None), None)
299
+ if candidate:
300
+ self._retire_dialog(candidate, "remote")
301
+
302
+ # CDP event → handler(self, params, session_id); merged into CDPSupervisor._EVENT_HANDLERS.
303
+ EVENT_HANDLERS: Dict[str, Callable[..., Any]] = {
304
+ "Page.javascriptDialogOpening": _on_dialog_opening,
305
+ "Page.javascriptDialogClosed": _on_dialog_closed,
306
+ "Fetch.requestPaused": _on_fetch_paused,
307
+ }
tools/browser_tool_eval_policy.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """browser_console(expression=...) policy: SSRF guard gating, private-URL probes,
2
+ and the opt-in sensitive-primitive denylist.
3
+
4
+ Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle.
5
+ """
6
+
7
+ import re
8
+ from typing import Optional
9
+ from utils import is_truthy_value
10
+ from tools.browser_tool_origin import origin_module as _origin
11
+ from tools import browser_tool_cloud as _cloud
12
+ from tools import browser_tool_session as _session
13
+
14
+
15
+ def _eval_ssrf_guard_active(effective_task_id: str) -> bool:
16
+ """Return True when eval-driven private-network access must be guarded.
17
+
18
+ Same gating as ``browser_navigate`` / ``browser_snapshot`` / ``browser_vision``: the SSRF guard
19
+ only matters for non-local backends (cloud browser, or a containerized terminal whose
20
+ browser-on-host reaches networks the terminal can't); skipped for local sidecars / ``allow_private_urls``.
21
+ """
22
+ _bt = _origin()
23
+ return not _cloud._is_local_backend() and not _bt._is_local_sidecar_key(effective_task_id) and not _cloud._allow_private_urls()
24
+
25
+
26
+ def _url_blocked(_bt, url: str) -> bool:
27
+ """True when ``url`` hits the always-blocked cloud-metadata floor or fails the SSRF guard."""
28
+ return _bt._is_always_blocked_url(url) or not _bt._is_safe_url(url)
29
+
30
+
31
+ # URL-shaped literals embedded in a JS expression (http/https only). fetch/XHR/navigate
32
+ # to a private host never updates ``location.href``, so the post-eval page-URL recheck
33
+ # can't see it; pre-screen the literals instead.
34
+ _JS_URL_LITERAL_RE = re.compile(r"""https?://[^\s'"`)\]<>]+""", re.IGNORECASE)
35
+
36
+
37
+ def _expression_targets_private_url(expression: str) -> Optional[str]:
38
+ """Return the first private/always-blocked ``http(s)://`` literal in a JS expression (best-effort), else None."""
39
+ _bt = _origin()
40
+ literals = _JS_URL_LITERAL_RE.findall(expression) if isinstance(expression, str) else []
41
+ return next((c for c in (m.rstrip(".,;") for m in literals) if _url_blocked(_bt, c)), None)
42
+
43
+
44
+ def _current_page_private_url(effective_task_id: str) -> Optional[str]:
45
+ """Return the current page URL when it targets a private/internal address (e.g. after a prior
46
+ ``location.href = '...'`` eval). Fail-open on probe failure, matching the snapshot/vision guards."""
47
+ _bt = _origin()
48
+ try:
49
+ url_result = _session._run_browser_command(effective_task_id, "eval", ["window.location.href"], timeout=5, _engine_override="auto")
50
+ if url_result.get("success"):
51
+ current_url = url_result.get("data", {}).get("result", "").strip().strip('"').strip("'")
52
+ if current_url and _url_blocked(_bt, current_url):
53
+ return current_url
54
+ except Exception as exc:
55
+ _bt.logger.debug("_current_page_private_url: probe failed (%s)", exc)
56
+ return None
57
+
58
+
59
+ _RISKY_BROWSER_EVAL_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
60
+ (re.compile(r"\bdocument\s*\.\s*cookie\b", re.I), "document.cookie"),
61
+ (re.compile(r"\b(?:localStorage|sessionStorage)\b", re.I), "web storage"),
62
+ (re.compile(r"\bindexedDB\b", re.I), "IndexedDB"),
63
+ (re.compile(r"\bcaches\s*\.\s*(?:open|match|keys)\b", re.I), "Cache Storage"),
64
+ (re.compile(r"\bnavigator\s*\.\s*(?:clipboard|credentials|serviceWorker)\b", re.I), "navigator sensitive API"),
65
+ (re.compile(r"\b(?:fetch|XMLHttpRequest|WebSocket|EventSource)\s*\(", re.I), "network request"),
66
+ (re.compile(r"\bnavigator\s*\.\s*sendBeacon\s*\(", re.I), "network beacon"),
67
+ (re.compile(r"\bdocument\s*\.\s*forms\b.*\bvalue\b", re.I | re.S), "form value extraction"),
68
+ (re.compile(r"\bquerySelector(?:All)?\s*\([^)]*(?:input|textarea|password)[^)]*\).*\bvalue\b", re.I | re.S), "form value extraction"),
69
+ )
70
+
71
+ _JS_STRING_LITERAL_RE = re.compile(r"""'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"|`(?:\\.|[^`\\])*`""", re.S)
72
+
73
+
74
+ _SENSITIVE_BROWSER_EVAL_TOKENS: tuple[tuple[str, str], ...] = (
75
+ ("cookie", "document.cookie"),
76
+ ("localStorage", "web storage"), ("sessionStorage", "web storage"),
77
+ ("indexedDB", "IndexedDB"), ("caches", "Cache Storage"),
78
+ ("clipboard", "navigator sensitive API"), ("credentials", "navigator sensitive API"),
79
+ ("serviceWorker", "navigator sensitive API"),
80
+ ("fetch", "network request"), ("XMLHttpRequest", "network request"),
81
+ ("WebSocket", "network request"), ("EventSource", "network request"),
82
+ ("sendBeacon", "network beacon"),
83
+ )
84
+
85
+
86
+ def _browser_eval_flag(key: str) -> bool:
87
+ """Read boolean ``browser.<key>`` (default False) through the origin's config reader."""
88
+ _bt = _origin()
89
+ return _bt._browser_cfg(key, False, lambda v: is_truthy_value(v, default=False), f"browser.{key} from config")
90
+
91
+
92
+ def _allow_unsafe_browser_evaluate() -> bool:
93
+ """Whether sensitive browser JS evaluation is explicitly allowed (overrides ``restrict_evaluate``)."""
94
+ return _browser_eval_flag("allow_unsafe_evaluate")
95
+
96
+
97
+ def _restrict_browser_evaluate() -> bool:
98
+ """Whether the sensitive-primitive eval denylist is enabled (off by default).
99
+
100
+ It blocks the *names* of common primitives (``fetch``, ``cookie``, ``querySelector(...input...)``),
101
+ not actual exfiltration, so it also blocks much legitimate DOM extraction; egress is still gated
102
+ by the SSRF/private-URL guards in ``_browser_eval`` regardless. Opt in via
103
+ ``browser.restrict_evaluate: true`` (e.g. hostile pages with a logged-in profile).
104
+ """
105
+ return _browser_eval_flag("restrict_evaluate")
106
+
107
+
108
+ def _decode_js_string_literal(literal: str) -> str:
109
+ """Best-effort decode of a JS string literal (not a parser): normalizes escapes like ``"co\\x6fkie"``."""
110
+ if len(literal) < 2:
111
+ return literal
112
+ try:
113
+ return bytes(literal[1:-1], "utf-8").decode("unicode_escape")
114
+ except Exception:
115
+ return literal[1:-1]
116
+
117
+
118
+ def _decoded_js_string_literals(expression: str) -> list[str]:
119
+ return [_decode_js_string_literal(match.group(0)) for match in _JS_STRING_LITERAL_RE.finditer(expression)]
120
+
121
+
122
+ def _sensitive_browser_eval_token_reason(expression: str) -> Optional[str]:
123
+ """Risk reason for direct or quoted sensitive primitives: direct spellings alone miss
124
+ ``document["cookie"]`` / ``globalThis["fetch"]``, so tokens are also matched inside the decoded,
125
+ concatenated string literals (catches ``document["coo" + "kie"]``)."""
126
+ literals = "".join(_decoded_js_string_literals(expression)).lower()
127
+ return next((reason for token, reason in _SENSITIVE_BROWSER_EVAL_TOKENS
128
+ if re.search(rf"\b{re.escape(token)}\b", expression, re.I) or token.lower() in literals), None)
129
+
130
+
131
+ def _risky_browser_eval_reason(expression: str) -> Optional[str]:
132
+ """Return a human-readable reason if a JS expression uses risky primitives."""
133
+ if not expression:
134
+ return None
135
+ hit = next((reason for pattern, reason in _RISKY_BROWSER_EVAL_PATTERNS if pattern.search(expression)), None)
136
+ return hit or _sensitive_browser_eval_token_reason(expression)
137
+
138
+
139
+ def _enforce_browser_eval_policy(expression: str) -> Optional[str]:
140
+ """Block sensitive browser JS evaluation when the opt-in denylist is on (opt-in because it gates on
141
+ primitive *names*; private-address egress is enforced separately in ``_browser_eval``)."""
142
+ if not _restrict_browser_evaluate() or _allow_unsafe_browser_evaluate():
143
+ return None
144
+ reason = _risky_browser_eval_reason(expression)
145
+ if not reason:
146
+ return None
147
+ return ("Blocked: browser_console(expression=...) tried to use sensitive browser "
148
+ f"JavaScript primitive ({reason}) while browser.restrict_evaluate is "
149
+ "enabled. Use browser_snapshot/browser_get_images/browser_console "
150
+ "without expression for normal inspection, or set "
151
+ "browser.restrict_evaluate: false in config.yaml to allow programmatic evaluation.")
152
+
153
+
154
+ def _camofox_current_page_private_url(tab_id: str, user_id: str) -> Optional[str]:
155
+ """Camofox analogue of ``_current_page_private_url`` (evaluate endpoint instead of the CLI). Fail-open
156
+ on probe failure, matching the snapshot/vision guards — do not make fail-closed without the sibling."""
157
+ _bt = _origin()
158
+ try:
159
+ from tools.browser_camofox import _post
160
+ data = _post(f"/tabs/{tab_id}/evaluate", body={"expression": "window.location.href", "userId": user_id})
161
+ current_url = str(data.get("result") if isinstance(data, dict) else data or "")
162
+ current_url = current_url.strip().strip('"').strip("'")
163
+ if current_url and _url_blocked(_bt, current_url):
164
+ return current_url
165
+ except Exception as exc:
166
+ _bt.logger.debug("_camofox_current_page_private_url: probe failed (%s)", exc)
167
+ return None
tools/browser_tool_lightpanda_fallback.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lightpanda engine status and the automatic Chrome fallback for browser commands
2
+ that Lightpanda cannot serve (screenshots, empty snapshots, failed commands).
3
+
4
+ Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle.
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import shutil
10
+ import subprocess
11
+ from typing import Any, Dict, List, Optional, Tuple
12
+ from tools.browser_tool_origin import origin_module as _origin
13
+ from tools import browser_tool_cdp as _cdp
14
+ from tools import browser_tool_cloud as _cloud
15
+ from tools import browser_tool_install as _install
16
+ from tools import browser_tool_session as _session
17
+
18
+ # Commands where Chrome can meaningfully produce a different result. Session-management
19
+ # commands (close, record) are tied to the engine's daemon and can't be retried elsewhere.
20
+ _FALLBACK_ELIGIBLE = frozenset({"open", "snapshot", "screenshot", "eval", "click",
21
+ "fill", "scroll", "back", "press", "console", "errors"})
22
+
23
+
24
+ def _using_lightpanda_engine() -> bool:
25
+ """Return True when local browser commands are configured for Lightpanda."""
26
+ return _cloud._get_browser_engine() == "lightpanda"
27
+
28
+
29
+ def lightpanda_engine_status() -> Tuple[bool, str]:
30
+ """Whether ``browser.engine: lightpanda`` is actually in effect, and why.
31
+
32
+ ``(False, "")`` when the engine isn't lightpanda; else the reason names the setting shadowing
33
+ it or the driver running it. Mirrors ``_should_inject_engine`` / ``_resolve_backend_cdp``
34
+ precedence with config-only gates (no network I/O) for ``/browser status`` / ``hermes doctor``.
35
+ """
36
+ _bt = _origin()
37
+ if not _using_lightpanda_engine():
38
+ return False, ""
39
+ if _cdp._get_cdp_override_raw():
40
+ return False, "a CDP override is active (/browser connect or browser.cdp_url)"
41
+ if _bt._is_camofox_mode():
42
+ return False, "Camofox is the selected browser (CAMOFOX_URL)"
43
+ # Real-profile before cloud provider: browser_exec resolves real-profile before
44
+ # the backend, so with both set the real-profile toggle claims the session.
45
+ if _cloud._use_real_profile():
46
+ return False, "browser.use_real_profile is on (Lightpanda cannot load a Chromium profile)"
47
+ try:
48
+ provider = _cloud._get_cloud_provider()
49
+ except Exception:
50
+ provider = None
51
+ if provider is not None:
52
+ try:
53
+ name = provider.display_name
54
+ except Exception:
55
+ name = type(provider).__name__
56
+ return False, f"cloud provider {name} is selected (browser.cloud_provider, or auto-detected from credentials)"
57
+ if not _bt._is_browser_use_cli_mode():
58
+ return True, "built-in browser tools: agent-browser --engine lightpanda"
59
+ try:
60
+ from tools.browser_use_cli import _read_browser_cfg, is_legacy_browser_use_cloud_config
61
+ if is_legacy_browser_use_cloud_config(_read_browser_cfg()):
62
+ return False, "Browser Use cloud (BROWSER_USE_API_KEY) is selected"
63
+ except Exception as e:
64
+ _bt.logger.debug("legacy Browser Use cloud check failed: %s", e)
65
+ return True, "Browser Use mode: Hermes spawns `lightpanda serve` per session"
66
+
67
+
68
+ def _lightpanda_fallback_reason(engine: str, command: str, result: Dict[str, Any]) -> Optional[str]:
69
+ """User-visible reason a Lightpanda result needs the Chrome fallback (copied into the result), or None."""
70
+ if engine != "lightpanda" or command not in _FALLBACK_ELIGIBLE:
71
+ return None
72
+ if not result.get("success"):
73
+ return f"Lightpanda {command!r} failed ({str(result.get('error') or 'command failed').strip()}); retried with Chrome."
74
+ data = result.get("data", {})
75
+ if command == "snapshot" and len((data.get("snapshot", "") or "").strip()) < 20: # couldn't render
76
+ return "Lightpanda returned an empty/too-short snapshot; retried with Chrome."
77
+ if command == "screenshot" and data.get("path", ""):
78
+ # Lightpanda returns a ~17 KB placeholder PNG (panda logo at 1920x1080); real Chromium is 100 KB+.
79
+ try:
80
+ size = os.path.getsize(data["path"])
81
+ except OSError:
82
+ return "Lightpanda screenshot file was missing/unreadable; retried with Chrome."
83
+ if size < 20480:
84
+ _origin().logger.debug("Lightpanda screenshot is suspiciously small (%d bytes), "
85
+ "triggering Chrome fallback", size)
86
+ return f"Lightpanda screenshot was suspiciously small ({size} bytes); " "retried with Chrome."
87
+ return None
88
+
89
+
90
+ def _needs_lightpanda_fallback(engine: str, command: str, result: Dict[str, Any]) -> bool:
91
+ """Check if a Lightpanda result should trigger an automatic Chrome fallback."""
92
+ return _lightpanda_fallback_reason(engine, command, result) is not None
93
+
94
+
95
+ def _annotate_lightpanda_fallback(result: Dict[str, Any], reason: str) -> Dict[str, Any]:
96
+ """Add a user-visible Chrome fallback warning to a browser command result."""
97
+ warning = "⚠ Lightpanda fallback: Chrome was used for this browser action. " f"{reason}"
98
+ fields = {"fallback_warning": warning, "browser_engine": "chrome",
99
+ "browser_engine_fallback": {"from": "lightpanda", "to": "chrome", "reason": reason}}
100
+ annotated = {**result, **fields}
101
+ data = annotated.get("data")
102
+ if isinstance(data, dict):
103
+ annotated["data"] = data = dict(data)
104
+ for key, value in fields.items():
105
+ data.setdefault(key, dict(value) if isinstance(value, dict) else value)
106
+ return annotated
107
+
108
+
109
+ def _copy_fallback_warning(target: Dict[str, Any], result: Dict[str, Any]) -> Dict[str, Any]:
110
+ """Copy browser fallback metadata from an internal result into a tool response."""
111
+ if result.get("fallback_warning"):
112
+ target["fallback_warning"] = result["fallback_warning"]
113
+ target["browser_engine"] = result.get("browser_engine")
114
+ target["browser_engine_fallback"] = result.get("browser_engine_fallback")
115
+ return target
116
+
117
+
118
+ def _run_chrome_fallback_command(task_id: str, command: str, args: List[str], timeout: int) -> Dict[str, Any]:
119
+ """Run a browser command in a temporary Chrome session at the current URL.
120
+
121
+ agent-browser locks the engine when a named daemon starts, so ``--engine chrome`` on the
122
+ Lightpanda session is ignored: fresh temp Chrome session -> same URL -> ``command`` -> tear down.
123
+ """
124
+ _bt = _origin()
125
+ import uuid
126
+ # 1. Current URL from the Lightpanda session. ``get url`` is not fallback-eligible,
127
+ # so this can't recurse; the explicit override strips Chromium-only env flags.
128
+ url_result = _session._run_browser_command(task_id, "get", ["url"], timeout=10, _engine_override="lightpanda")
129
+ current_url = str(url_result.get("data", {}).get("url", "")).strip() if url_result.get("success") else None
130
+ if not current_url:
131
+ _bt.logger.warning("Chrome fallback: could not determine current URL from LP session")
132
+ return {"success": False, "error": "Chrome fallback failed: could not determine current URL"}
133
+
134
+ # 2. Temporary Chrome session (bypasses _get_session_info's cache).
135
+ tmp_session = f"h_cfb_{uuid.uuid4().hex[:8]}"
136
+ try:
137
+ browser_cmd = _install._find_agent_browser()
138
+ except FileNotFoundError as e:
139
+ return {"success": False, "error": str(e)}
140
+
141
+ if not _install._chromium_installed():
142
+ if _install._running_in_docker():
143
+ hint = ("Chrome fallback requires Chromium, but it is missing. You're running in Docker — "
144
+ "pull the latest image: docker pull ghcr.io/nousresearch/hermes-agent:latest")
145
+ else:
146
+ hint = ("Chrome fallback requires Chromium, but it is missing. Install it with: "
147
+ "npx agent-browser install --with-deps (or: npx playwright install --with-deps chromium)")
148
+ return {"success": False, "error": hint}
149
+
150
+ base_args = _session._agent_browser_argv(browser_cmd) + ["--engine", "chrome", "--session", tmp_session, "--json"]
151
+ task_socket_dir = _session._prepare_session_socket_dir(tmp_session)
152
+ # Bypasses _run_browser_command, so apply the same Chromium sandbox policy explicitly.
153
+ browser_env = _session._agent_browser_command_env(task_socket_dir)
154
+ _session._apply_chromium_sandbox_args(browser_env)
155
+
156
+ def _run_tmp(cmd: str, cmd_args: List[str]) -> Dict[str, Any]:
157
+ proc = _session._popen_agent_browser(base_args + [cmd] + cmd_args, browser_env, task_socket_dir, cmd)
158
+ stdout_path = os.path.join(task_socket_dir, f"_stdout_{cmd}")
159
+ stderr_path = os.path.join(task_socket_dir, f"_stderr_{cmd}")
160
+ try:
161
+ proc.wait(timeout=timeout)
162
+ except subprocess.TimeoutExpired:
163
+ proc.kill()
164
+ proc.wait()
165
+ return {"success": False, "error": f"Chrome fallback '{cmd}' timed out"}
166
+ try:
167
+ with open(stdout_path, encoding="utf-8") as f:
168
+ stdout = f.read().strip()
169
+ if stdout:
170
+ return json.loads(stdout.split("\n")[-1])
171
+ except Exception as exc:
172
+ _bt.logger.debug("Chrome fallback tmp cmd '%s' error: %s", cmd, exc)
173
+ finally:
174
+ _session._unlink_command_output_files(stdout_path, stderr_path)
175
+ return {"success": False, "error": f"Chrome fallback '{cmd}' failed"}
176
+
177
+ try:
178
+ # 3. Navigate Chrome to the same URL, then 4. run the requested command.
179
+ nav = _run_tmp("open", [current_url])
180
+ if not nav.get("success"):
181
+ _bt.logger.warning("Chrome fallback: navigate failed: %s", nav.get("error"))
182
+ return {"success": False, "error": f"Chrome fallback navigate failed: {nav.get('error')}"}
183
+ return _run_tmp(command, args)
184
+ finally:
185
+ # 5. Tear down the temporary Chrome session and its socket directory.
186
+ try:
187
+ _run_tmp("close", [])
188
+ except Exception:
189
+ pass
190
+ shutil.rmtree(task_socket_dir, ignore_errors=True)
191
+
192
+
193
+ def _chrome_fallback_screenshot(task_id: str, args: List[str], timeout: int) -> Dict[str, Any]:
194
+ """Take a screenshot using a temporary Chrome session."""
195
+ return _run_chrome_fallback_command(task_id, "screenshot", args, timeout)
tools/browser_tool_origin.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Origin-module lookup shared by the ``tools.browser_tool_*`` extraction modules.
2
+
3
+ Extracted code reads facade-owned state (caches, locks, session tables, facade-defined
4
+ helpers) *through* ``tools.browser_tool`` and must not import it at import time (cycle) —
5
+ hence the lazy :func:`origin_module` and the :data:`origin` proxy.
6
+ """
7
+
8
+ import sys
9
+ from types import ModuleType
10
+
11
+ _ORIGIN_NAME = "tools.browser_tool"
12
+
13
+
14
+ class _NamespaceView:
15
+ """Live view over a module namespace whose module object is gone (a test purged
16
+ ``sys.modules``): the old code still runs with its own globals, so hit *those*."""
17
+
18
+ __slots__ = ("_g",)
19
+
20
+ def __init__(self, g):
21
+ object.__setattr__(self, "_g", g)
22
+
23
+ def __getattr__(self, name):
24
+ try:
25
+ return self._g[name]
26
+ except KeyError:
27
+ raise AttributeError(name) from None
28
+
29
+ def __setattr__(self, name, value):
30
+ self._g[name] = value
31
+
32
+
33
+ def _module_for_globals(g: dict):
34
+ """The module object whose namespace is ``g`` (or a live view over it)."""
35
+ import tools
36
+
37
+ for mod in (sys.modules.get(_ORIGIN_NAME), getattr(tools, "browser_tool", None)):
38
+ if mod is not None and mod.__dict__ is g:
39
+ return mod
40
+ return _NamespaceView(g)
41
+
42
+
43
+ def origin_module(_depth: int = 2):
44
+ """The ``tools.browser_tool`` instance the *calling* moved function belongs to, mirroring
45
+ what in-file code would see: (1) the nearest enclosing frame executing origin code (the
46
+ exact module copy, even after a test purged/reloaded ``sys.modules``); (2) an origin
47
+ module referenced from a calling frame's globals; (3) ``sys.modules`` / ``tools``
48
+ package attribute / fresh import. ``_depth`` is the frame of the moved function's caller."""
49
+ try:
50
+ start = sys._getframe(_depth)
51
+ except ValueError: # called directly by the interpreter (atexit callback)
52
+ start = None
53
+ frame = start
54
+ while frame is not None:
55
+ if frame.f_globals.get("__name__") == _ORIGIN_NAME:
56
+ return _module_for_globals(frame.f_globals)
57
+ frame = frame.f_back
58
+ frame = start
59
+ while frame is not None:
60
+ for value in list(frame.f_globals.values()):
61
+ if isinstance(value, ModuleType) and getattr(value, "__name__", None) == _ORIGIN_NAME:
62
+ return value
63
+ frame = frame.f_back
64
+ mod = sys.modules.get(_ORIGIN_NAME)
65
+ if mod is None:
66
+ import tools
67
+
68
+ mod = getattr(tools, "browser_tool", None)
69
+ if mod is None:
70
+ import tools.browser_tool as mod
71
+ return mod
72
+
73
+
74
+ class _OriginProxy:
75
+ """Module-level ``_bt`` stand-in: every attribute read/write forwards to the origin
76
+ module resolved at that moment."""
77
+
78
+ __slots__ = ()
79
+
80
+ def __getattr__(self, name):
81
+ return getattr(origin_module(3), name)
82
+
83
+ def __setattr__(self, name, value):
84
+ setattr(origin_module(3), name, value)
85
+
86
+
87
+ origin = _OriginProxy()
tools/browser_tool_session.py ADDED
@@ -0,0 +1,614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """agent-browser session management: daemon spawn, per-backend session creation
2
+ (local/lightpanda/cdp/cloud), cached lookup, command execution + output interpretation.
3
+
4
+ Split out of ``tools/browser_tool.py``. Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle.
5
+ """
6
+
7
+ import json
8
+ import logging
9
+ import os
10
+ import shutil
11
+ import subprocess
12
+ import uuid
13
+ from pathlib import Path
14
+ from typing import Any, Dict, List, Optional
15
+
16
+ from hermes_cli._subprocess_compat import windows_hide_flags
17
+ from tools.browser_tool_origin import origin as _bt
18
+ from tools import browser_tool_cdp as _cdp
19
+ from tools import browser_tool_cloud as _cloud
20
+ from tools import browser_tool_install as _install
21
+ from tools import browser_tool_lifecycle as _lifecycle
22
+ from tools import browser_tool_lightpanda_fallback as _lp
23
+ from tools import browser_tool_real_profile as _real_profile
24
+ from tools import browser_tool_snapshot as _snapshot
25
+
26
+ _DOCKER_PULL = "docker pull ghcr.io/nousresearch/hermes-agent:latest"
27
+ _CHROMIUM_INSTALL = "npx agent-browser install --with-deps (or: npx playwright install --with-deps chromium)"
28
+ _CHROMIUM_MISSING_DOCKER_HINT = ("Chromium browser is missing. You're running in Docker — pull the latest image "
29
+ f"to get the bundled Chromium: {_DOCKER_PULL}")
30
+ _CHROMIUM_MISSING_HINT = f"Chromium browser is missing. Install it with: {_CHROMIUM_INSTALL}"
31
+
32
+
33
+ def _needs_chromium_sandbox_bypass() -> bool:
34
+ """True when Chromium needs --no-sandbox to start reliably (root, Docker, AppArmor userns)."""
35
+ if hasattr(os, "geteuid") and os.geteuid() == 0:
36
+ return True
37
+ if _install._running_in_docker():
38
+ return True
39
+ try:
40
+ with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8") as f:
41
+ return f.read().strip() == "1"
42
+ except OSError:
43
+ return False
44
+
45
+
46
+ def _apply_chromium_sandbox_args(browser_env: Dict[str, str]) -> None:
47
+ """Add required Chromium sandbox flags without overriding user settings."""
48
+ if ("AGENT_BROWSER_ARGS" not in browser_env and "AGENT_BROWSER_CHROME_FLAGS" not in browser_env
49
+ and _needs_chromium_sandbox_bypass()):
50
+ _bt.logger.debug("browser: sandbox bypass needed (root/docker/AppArmor userns) — injecting --no-sandbox")
51
+ browser_env["AGENT_BROWSER_ARGS"] = "--no-sandbox,--disable-dev-shm-usage"
52
+
53
+
54
+ def _read_command_output_files(stdout_path: str, stderr_path: str) -> tuple[str, str]:
55
+ """Best-effort read of agent-browser stdout/stderr temp files."""
56
+ out = []
57
+ for path in (stdout_path, stderr_path):
58
+ try:
59
+ with open(path, "r", encoding="utf-8") as f:
60
+ out.append(f.read().strip())
61
+ except OSError:
62
+ out.append("")
63
+ return out[0], out[1]
64
+
65
+
66
+ def _unlink_command_output_files(*paths: str) -> None:
67
+ for path in paths:
68
+ try:
69
+ os.unlink(path)
70
+ except OSError:
71
+ pass
72
+
73
+
74
+ def _format_browser_timeout_error(
75
+ command: str, timeout: int, stdout: str, stderr: str
76
+ ) -> str:
77
+ """Actionable timeout message from captured daemon output."""
78
+ parts = [f"Command timed out after {timeout} seconds"]
79
+ detail = (stderr or stdout or "").strip()
80
+ if detail:
81
+ parts.append(detail[:1500])
82
+
83
+ if "sandbox" in f"{stderr}\n{stdout}".lower():
84
+ parts.append("Chromium sandbox launch failed. Set AGENT_BROWSER_ARGS="
85
+ "'--no-sandbox,--disable-dev-shm-usage' in your environment, "
86
+ "or run: npx agent-browser install --with-deps")
87
+ elif command == "open" and _cloud._is_local_mode():
88
+ if _install._running_in_docker():
89
+ parts.append("The browser daemon may still be starting or Chromium may be "
90
+ f"missing. Pull the latest image: {_DOCKER_PULL}")
91
+ else:
92
+ parts.append("The browser daemon may still be starting, or Chromium may be "
93
+ f"missing system libraries. Install/repair with: {_CHROMIUM_INSTALL}")
94
+ return "\n".join(parts)
95
+
96
+
97
+ def _agent_browser_argv(browser_cmd: str) -> list:
98
+ """Command prefix to invoke agent-browser (concrete binary, or the npx sentinel expanded).
99
+
100
+ npx is resolved through the same PATH cascade as ``_find_agent_browser`` (a bare
101
+ ``which("npx")`` would let a broken system npx shadow a healthy managed one); if
102
+ absent the bare name gives a readable ``FileNotFoundError``. ``--ignore-scripts``:
103
+ the spec is a floating range — a compromised future patch must not run install scripts.
104
+ """
105
+ if _install._is_npx_agent_browser_sentinel(browser_cmd):
106
+ _npx_bin = _install._resolve_npx_bin() or "npx"
107
+ return [_npx_bin, "--ignore-scripts", "--prefer-offline", "-y", _bt.AGENT_BROWSER_NPX_SPEC]
108
+ return [browser_cmd]
109
+
110
+
111
+ def _prepare_session_socket_dir(session_name: str) -> str:
112
+ """Create the per-session socket dir (parallel workers must not share one) and claim it
113
+ with our PID BEFORE first use — another hermes process's orphan reaper rmtree's any
114
+ ownerless agent-browser-* dir in the shared tmpdir."""
115
+ socket_dir = os.path.join(_bt._socket_safe_tmpdir(), f"agent-browser-{session_name}")
116
+ os.makedirs(socket_dir, mode=0o700, exist_ok=True)
117
+ _lifecycle._write_owner_pid(socket_dir, session_name)
118
+ return socket_dir
119
+
120
+
121
+ def _agent_browser_command_env(socket_dir: str) -> Dict[str, str]:
122
+ """Credential-scrubbed env for one command: PATH fallbacks, the session socket dir, and
123
+ daemon-side idle self-termination (agent-browser 0.24+) mirroring the Python janitor
124
+ unless the user set ``AGENT_BROWSER_IDLE_TIMEOUT_MS`` explicitly."""
125
+ env = _bt._build_browser_env()
126
+ env["PATH"] = _install._merge_browser_path(env.get("PATH", ""))
127
+ env["AGENT_BROWSER_SOCKET_DIR"] = socket_dir
128
+ if "AGENT_BROWSER_IDLE_TIMEOUT_MS" not in env:
129
+ env["AGENT_BROWSER_IDLE_TIMEOUT_MS"] = str(_bt.BROWSER_SESSION_INACTIVITY_TIMEOUT * 1000)
130
+ return env
131
+
132
+
133
+ def _popen_agent_browser(argv: List[str], env: Dict[str, str], socket_dir: str, tag: str) -> "subprocess.Popen":
134
+ """Spawn agent-browser with stdout/stderr redirected to ``socket_dir/_std{out,err}_<tag>``.
135
+
136
+ Temp files, not pipes: the CLI forks a daemon that inherits its fds, so pipes never
137
+ see EOF until the timeout. Windows: CREATE_NO_WINDOW only (CREATE_NEW_PROCESS_GROUP
138
+ cancels asyncio's running task on 3.11), STARTF_USESTDHANDLES + close_fds so the child
139
+ gets ONLY our three handles (leaked console handles kill the Rust daemon grandchild).
140
+ """
141
+ fds = [os.open(os.path.join(socket_dir, f"_{slot}_{tag}"), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
142
+ for slot in ("stdout", "stderr")]
143
+ try:
144
+ _popen_extra: dict = {}
145
+ if os.name == "nt":
146
+ _si = subprocess.STARTUPINFO()
147
+ _si.dwFlags |= subprocess.STARTF_USESTDHANDLES
148
+ _popen_extra = {"creationflags": windows_hide_flags(), "close_fds": True, "startupinfo": _si}
149
+ return subprocess.Popen(argv, stdout=fds[0], stderr=fds[1], stdin=subprocess.DEVNULL, env=env, **_popen_extra)
150
+ finally:
151
+ for fd in fds:
152
+ os.close(fd)
153
+
154
+
155
+ def _session_record(prefix: str, cdp_url: Optional[str], features: Dict[str, Any]) -> Dict[str, Any]:
156
+ """Fresh session dict with a random ``<prefix>_<hex10>`` session name."""
157
+ return {"session_name": f"{prefix}_{uuid.uuid4().hex[:10]}", "bb_session_id": None,
158
+ "cdp_url": cdp_url, "features": features}
159
+
160
+
161
+ def _create_local_session(task_id: str, allow_real_profile: bool = True) -> Dict[str, str]:
162
+ """Local Chromium session; consented real-profile CDP attach when allowed.
163
+
164
+ Real-profile fails closed on resolver/launch errors (a consented user must never be
165
+ silently downgraded to a throwaway). The hybrid private-URL sidecar passes
166
+ ``allow_real_profile=False``: the user's cookie jar must not reach an arbitrary
167
+ internal host the model chose.
168
+ """
169
+ if allow_real_profile:
170
+ cdp_url, err = _real_profile._real_profile_cdp()
171
+ if err:
172
+ raise RuntimeError(err)
173
+ if cdp_url:
174
+ info = _session_record("rp", _cdp._resolve_cdp_override(cdp_url), {"local": True, "real_profile": True})
175
+ _bt.logger.info("Created real-profile local session %s for task %s", info["session_name"], task_id)
176
+ return info
177
+
178
+ # Browser Use mode + ``browser.engine: lightpanda`` drives a Hermes-spawned
179
+ # ``lightpanda serve`` (the built-in tools are hidden in that mode).
180
+ if _bt._is_browser_use_cli_mode() and _lp._using_lightpanda_engine():
181
+ return _create_lightpanda_session(task_id)
182
+
183
+ info = _session_record("h", None, {"local": True})
184
+ _bt.logger.info("Created local browser session %s for task %s", info["session_name"], task_id)
185
+ return info
186
+
187
+
188
+ def _create_lightpanda_session(task_id: str) -> Dict[str, Any]:
189
+ """Spawn ``lightpanda serve`` for this session key (Browser Use mode)."""
190
+ from tools.browser_lightpanda import launch_lightpanda
191
+
192
+ info = _session_record("lp", None, {"local": True, "lightpanda": True})
193
+ server, err = launch_lightpanda(info["session_name"], block_private_networks=not _cloud._is_local_backend())
194
+ if err:
195
+ raise RuntimeError(err)
196
+ info["cdp_url"] = server.cdp_url
197
+ _bt.logger.info("Created Lightpanda session %s (port %s) for task %s", info["session_name"], server.port, task_id)
198
+ return info
199
+
200
+
201
+ def _local_backend_process_dead(session_info: Dict[str, Any]) -> bool:
202
+ """True for a Lightpanda session whose ``lightpanda serve`` is gone."""
203
+ if not (session_info.get("features") or {}).get("lightpanda"):
204
+ return False
205
+ from tools.browser_lightpanda import get_server
206
+
207
+ server = get_server(session_info.get("session_name", ""))
208
+ return server is None or not server.is_alive()
209
+
210
+
211
+ def _create_cdp_session(task_id: str, cdp_url: str) -> Dict[str, str]:
212
+ """Session connecting to a user-supplied CDP endpoint."""
213
+ info = _session_record("cdp", cdp_url, {"cdp_override": True})
214
+ _bt.logger.info("Created CDP browser session %s → %s for task %s",
215
+ info["session_name"], _bt._sanitize_url_for_logs(cdp_url), task_id)
216
+ return info
217
+
218
+
219
+ def _create_cloud_session_or_fallback(task_id: str, provider) -> Dict[str, Any]:
220
+ """Cloud session; fall back to local Chromium (marked degraded) on failure. ``cdp_url``
221
+ is resolved here because some providers return an HTTP discovery URL, not a websocket."""
222
+ try:
223
+ session_info = provider.create_session(task_id)
224
+ if not session_info or not isinstance(session_info, dict):
225
+ raise ValueError(f"Cloud provider returned invalid session: {session_info!r}")
226
+ if session_info.get("cdp_url"):
227
+ session_info = dict(session_info)
228
+ session_info["cdp_url"] = _cdp._resolve_cdp_override(str(session_info["cdp_url"]))
229
+ return session_info
230
+ except Exception as e:
231
+ provider_name = type(provider).__name__
232
+ _bt.logger.warning("Cloud provider %s failed (%s); attempting fallback to local Chromium for task %s",
233
+ provider_name, e, task_id, exc_info=True)
234
+ try:
235
+ session_info = _create_local_session(task_id)
236
+ except Exception as local_error:
237
+ raise RuntimeError(f"Cloud provider {provider_name} failed ({e}) and local "
238
+ f"fallback also failed ({local_error})") from e
239
+ if isinstance(session_info, dict): # mark degraded for observability
240
+ session_info = {**session_info, "fallback_from_cloud": True, "fallback_reason": str(e),
241
+ "fallback_provider": provider_name}
242
+ return session_info
243
+
244
+
245
+ def _create_session_for_key(task_id: str, force_local: bool) -> Dict[str, Any]:
246
+ """Fresh session for ``task_id`` (runs OUTSIDE the lock: cloud mode makes a network call).
247
+ Precedence: CDP override > hybrid local sidecar (never real-profile) > cloud > local."""
248
+ cdp_override = _cdp._get_cdp_override()
249
+ if cdp_override and not force_local:
250
+ return _create_cdp_session(task_id, cdp_override)
251
+ if force_local:
252
+ return _create_local_session(task_id, allow_real_profile=False)
253
+ provider = _cloud._get_cloud_provider()
254
+ if provider is None:
255
+ return _create_local_session(task_id)
256
+ return _create_cloud_session_or_fallback(task_id, provider)
257
+
258
+
259
+ def _get_session_info(task_id: Optional[str] = None) -> Dict[str, Any]:
260
+ """Get or create session info for a session key (thread-safe); also starts the
261
+ inactivity thread and touches activity. A ``::local`` key forces local Chromium
262
+ even with a cloud provider configured."""
263
+ if task_id is None:
264
+ task_id = "default"
265
+
266
+ _lifecycle._start_browser_cleanup_thread()
267
+ _lifecycle._update_session_activity(task_id)
268
+
269
+ with _bt._cleanup_lock:
270
+ existing_session = _bt._active_sessions.get(task_id)
271
+
272
+ def _replacement_after_teardown() -> Optional[Dict[str, Any]]:
273
+ # Teardown removes the activity entry; re-touch so the reaper tracks the
274
+ # replacement. Another thread may already have re-created it — reuse that.
275
+ _lifecycle._update_session_activity(task_id)
276
+ with _bt._cleanup_lock:
277
+ replacement = _bt._active_sessions.get(task_id)
278
+ return replacement if replacement is not None and replacement is not existing_session else None
279
+
280
+ if existing_session is not None:
281
+ # Suspect recycle: a command timeout marked this session; the expensive recycle
282
+ # lives here at next use, not on the timeout path (mark must stay cheap).
283
+ if not _bt._browser_session_backend(task_id).ensure_healthy():
284
+ replacement = _replacement_after_teardown()
285
+ if replacement is not None:
286
+ return replacement
287
+ existing_session = None
288
+ elif not _lifecycle._session_has_expired(existing_session) and not _local_backend_process_dead(existing_session):
289
+ return existing_session
290
+ else:
291
+ _bt.logger.info("Replacing expired or dead browser session for task %s", task_id)
292
+ _lifecycle._cleanup_single_browser_session(task_id)
293
+ replacement = _replacement_after_teardown()
294
+ if replacement is not None:
295
+ return replacement
296
+
297
+ force_local = _bt._is_local_sidecar_key(task_id)
298
+ session_info = _create_session_for_key(task_id, force_local)
299
+
300
+ with _bt._cleanup_lock:
301
+ if task_id in _bt._active_sessions: # created concurrently during the network call — don't leak ours
302
+ return _bt._active_sessions[task_id]
303
+ session_info = dict(session_info)
304
+ session_info.setdefault("session_key", task_id)
305
+ session_info.setdefault("owner_task_id", _bt._bare_task_id_for_session_key(task_id))
306
+ _bt._active_sessions[task_id] = session_info
307
+ _bt._suspect_browser_sessions.pop(task_id, None) # brand-new session is healthy by definition
308
+
309
+ # Lazy-start the CDP supervisor (idempotent). Skip local sidecars (no CDP URL) and
310
+ # Lightpanda sessions (Browser Use mode hides the tools that consume supervisor state).
311
+ if not force_local and not (session_info.get("features") or {}).get("lightpanda"):
312
+ _cdp._ensure_cdp_supervisor(task_id)
313
+
314
+ return session_info
315
+
316
+
317
+ def _discard_timed_out_browser_session(task_id: str, session_info: Dict[str, Any], task_socket_dir: str) -> None:
318
+ """Drop a stuck client generation without losing cloud cleanup state."""
319
+ with _bt._cleanup_lock:
320
+ if _bt._active_sessions.get(task_id) is not session_info:
321
+ return
322
+ _cdp._stop_cdp_supervisor(task_id)
323
+ if session_info.get("bb_session_id") or session_info.get("cdp_url"):
324
+ replacement = dict(session_info)
325
+ replacement["session_name"] = f"h_{uuid.uuid4().hex[:10]}"
326
+ replacement.pop("_first_nav", None)
327
+ _bt._active_sessions[task_id] = replacement
328
+ else:
329
+ _bt._active_sessions.pop(task_id, None)
330
+ _bt._session_last_activity.pop(task_id, None)
331
+
332
+ bare_task_id = _bt._bare_task_id_for_session_key(task_id)
333
+ if _bt._last_active_session_key.get(bare_task_id) == task_id:
334
+ _bt._last_active_session_key.pop(bare_task_id, None)
335
+
336
+ session_name = str(session_info.get("session_name") or "")
337
+ if session_name and os.path.isfile(os.path.join(task_socket_dir, f"{session_name}.pid")):
338
+ daemon_pid = _read_browser_daemon_pid(task_socket_dir, session_name)
339
+ if daemon_pid is None: # corrupt pid file
340
+ _bt.logger.debug("Could not kill timed-out browser daemon for %s", session_name)
341
+ return
342
+ if not _lifecycle._verify_reapable_browser_daemon(daemon_pid, task_socket_dir, session_name):
343
+ return
344
+ try:
345
+ # Tree-kill: terminating only the daemon PID leaks the Chromium tree.
346
+ # See #68139.
347
+ from agent import deadline as _deadline
348
+
349
+ _deadline.kill_process_tree(daemon_pid)
350
+ except (ProcessLookupError, PermissionError, OSError):
351
+ _bt.logger.debug("Could not kill timed-out browser daemon for %s", session_name)
352
+ return
353
+ shutil.rmtree(task_socket_dir, ignore_errors=True)
354
+
355
+
356
+ def _read_browser_daemon_pid(task_socket_dir: str, session_name: str) -> Optional[int]:
357
+ """Read the agent-browser daemon PID for a session (best-effort)."""
358
+ pid_file = os.path.join(task_socket_dir, f"{session_name}.pid")
359
+ try:
360
+ return int(Path(pid_file).read_text(encoding="utf-8").strip())
361
+ except (OSError, ValueError):
362
+ return None
363
+
364
+
365
+ def _browser_daemon_responsive(task_socket_dir: str, probe_timeout_s: float = 1.0) -> bool:
366
+ """Cheap liveness probe: a connect to the daemon's unix control socket proves the accept
367
+ loop is alive (the command wedged page/CDP-side). Windows named pipes can't be probed →
368
+ report unresponsive (tree-kill + respawn is the safe recovery)."""
369
+ if os.name == "nt":
370
+ return False
371
+ import socket as socket_mod
372
+
373
+ if not hasattr(socket_mod, "AF_UNIX"):
374
+ return False
375
+ try:
376
+ entries = os.listdir(task_socket_dir)
377
+ except OSError:
378
+ return False
379
+ for entry in (e for e in entries if e.endswith(".sock")):
380
+ try:
381
+ with socket_mod.socket(socket_mod.AF_UNIX, socket_mod.SOCK_STREAM) as s:
382
+ s.settimeout(probe_timeout_s)
383
+ s.connect(os.path.join(task_socket_dir, entry))
384
+ return True
385
+ except OSError:
386
+ continue
387
+ return False
388
+
389
+
390
+ def _handle_browser_command_timeout(task_id: str, session_info: Dict[str, Any], task_socket_dir: str) -> None:
391
+ """Recover session state after a command timeout.
392
+
393
+ Cloud/CDP: no daemon to probe — replace the stuck client generation now (same
394
+ ``bb_session_id`` so cloud cleanup works). Local daemon alive (PID live, verified,
395
+ socket accepts): only the command wedged — mark suspect, recycle at next use.
396
+ Local daemon wedged/dead: tree-kill and evict now (Chromium children would leak).
397
+ Both local branches ``mark_suspect`` first so the poisoned-cache invariant holds
398
+ even if eviction races another thread's replacement.
399
+
400
+ See #68139, #72205.
401
+ * **Local daemon alive** (PID readable, process alive, identity-verified as ours, control socket accepts
402
+ a connection): the *command* wedged — page hang, stuck navigation — but the daemon itself is fine.
403
+ Killing it would be overkill and slow. Mark the session suspect only; the next use recycles it through
404
+ ``ensure_healthy`` → clean agent-browser ``close`` → fresh session. Tree-kill the daemon's process tree
405
+ via ``agent.deadline.kill_process_tree`` and evict the cache entry now; the next browser call respawns
406
+ from scratch. See #72206.
407
+ """
408
+ if session_info.get("bb_session_id") or session_info.get("cdp_url"):
409
+ _discard_timed_out_browser_session(task_id, session_info, task_socket_dir)
410
+ return
411
+
412
+ _bt._browser_session_backend(task_id).mark_suspect("browser command timed out; session may be poisoned")
413
+
414
+ session_name = str(session_info.get("session_name") or "")
415
+ daemon_pid = _read_browser_daemon_pid(task_socket_dir, session_name) if session_name else None
416
+ daemon_alive = (
417
+ daemon_pid is not None
418
+ and _lifecycle._pid_exists(daemon_pid)
419
+ and _lifecycle._verify_reapable_browser_daemon(daemon_pid, task_socket_dir, session_name)
420
+ and _browser_daemon_responsive(task_socket_dir)
421
+ )
422
+ if daemon_alive:
423
+ _bt.logger.warning("browser daemon for %s is alive after command timeout; session "
424
+ "marked suspect and will be recycled at next use", task_id)
425
+ return
426
+
427
+ _bt.logger.warning("browser daemon for %s is wedged or dead after command timeout; "
428
+ "tree-killing and evicting the session", task_id)
429
+ _discard_timed_out_browser_session(task_id, session_info, task_socket_dir)
430
+ # The poisoned entry is gone either way; the flag must not poison a session
431
+ # created later under the same key.
432
+ _bt._suspect_browser_sessions.pop(task_id, None)
433
+
434
+
435
+ def _interpret_browser_command_output(command: str, stdout: str, stderr: str, returncode: int) -> Dict[str, Any]:
436
+ """Finished agent-browser process output → result dict. Empty stdout with rc=0 is a
437
+ broken state (stale daemon) reported as failure except for ``_EMPTY_OK_COMMANDS``;
438
+ non-JSON output is an error except ``screenshot``, whose path is recovered from prose."""
439
+ if stderr and stderr.strip():
440
+ level = logging.WARNING if returncode != 0 else logging.DEBUG
441
+ _bt.logger.log(level, "browser '%s' stderr: %s", command, stderr.strip()[:500])
442
+
443
+ stdout_text = stdout.strip()
444
+ if not stdout_text:
445
+ if returncode != 0:
446
+ error_msg = stderr.strip() if stderr else f"Command failed with code {returncode}"
447
+ _bt.logger.warning("browser '%s' failed (rc=%s): %s", command, returncode, error_msg[:300])
448
+ return {"success": False, "error": error_msg}
449
+ if command not in _bt._EMPTY_OK_COMMANDS:
450
+ _bt.logger.warning("browser '%s' returned empty output (rc=0)", command)
451
+ return {"success": False, "error": f"Browser command '{command}' returned no output"}
452
+ return {"success": True, "data": {}}
453
+
454
+ try:
455
+ parsed = json.loads(stdout_text)
456
+ except json.JSONDecodeError:
457
+ raw = stdout_text[:2000]
458
+ _bt.logger.warning("browser '%s' returned non-JSON output (rc=%s): %s", command, returncode, raw[:500])
459
+ if command == "screenshot":
460
+ combined_text = "\n".join(part for part in [stdout_text, (stderr or "").strip()] if part)
461
+ recovered_path = _snapshot._extract_screenshot_path_from_text(combined_text)
462
+ if recovered_path and Path(recovered_path).exists():
463
+ _bt.logger.info("browser 'screenshot' recovered file from non-JSON output: %s", recovered_path)
464
+ return {"success": True, "data": {"path": recovered_path, "raw": raw}}
465
+ return {"success": False, "error": f"Non-JSON output from agent-browser for '{command}': {raw}"}
466
+
467
+ # Empty snapshot content is a common sign of daemon/CDP issues.
468
+ if command == "snapshot" and parsed.get("success"):
469
+ snap_data = parsed.get("data", {})
470
+ if not snap_data.get("snapshot") and not snap_data.get("refs"):
471
+ _bt.logger.warning("snapshot returned empty content. Possible stale daemon or CDP connection issue. "
472
+ "returncode=%s", returncode)
473
+ return parsed
474
+
475
+
476
+ def _browser_command_preflight() -> Dict[str, Any]:
477
+ """Fail fast before spawning (missing CLI, Termux gap, interrupt, no Chromium in local
478
+ mode — else every call hangs for command_timeout). Error result, or ``{"browser_cmd": path}``."""
479
+ try:
480
+ browser_cmd = _install._find_agent_browser()
481
+ except FileNotFoundError as e:
482
+ _bt.logger.warning("agent-browser CLI not found: %s", e)
483
+ return {"success": False, "error": str(e)}
484
+
485
+ if _install._requires_real_termux_browser_install(browser_cmd):
486
+ error = _install._termux_browser_install_error()
487
+ _bt.logger.warning("browser command blocked on Termux: %s", error)
488
+ return {"success": False, "error": error}
489
+
490
+ # Skip when engine=lightpanda — LP doesn't need Chromium for navigation.
491
+ if (
492
+ _cloud._is_local_mode()
493
+ and not _install._chromium_installed()
494
+ and _cloud._get_browser_engine() != "lightpanda"
495
+ and not _install._maybe_autoinstall_chromium()
496
+ ):
497
+ hint = _CHROMIUM_MISSING_DOCKER_HINT if _install._running_in_docker() else _CHROMIUM_MISSING_HINT
498
+ _bt.logger.warning("browser command blocked: %s", hint)
499
+ return {"success": False, "error": hint}
500
+
501
+ from tools.interrupt import is_interrupted
502
+ if is_interrupted():
503
+ return {"success": False, "error": "Interrupted"}
504
+ return {"browser_cmd": browser_cmd}
505
+
506
+
507
+ def _spawn_and_collect(
508
+ task_id: str, session_info: Dict[str, Any], cmd_parts: List[str],
509
+ command: str, engine: str, timeout: int,
510
+ ) -> Dict[str, Any]:
511
+ """Run the prepared agent-browser argv once and interpret its output (handles timeout)."""
512
+ task_socket_dir = _prepare_session_socket_dir(session_info["session_name"])
513
+ _bt.logger.debug("browser cmd=%s task=%s socket_dir=%s (%d chars)",
514
+ command, task_id, task_socket_dir, len(task_socket_dir))
515
+ browser_env = _agent_browser_command_env(task_socket_dir)
516
+
517
+ # Lightpanda rejects Chromium-only launch flags: strip current and legacy vars;
518
+ # Chrome commands and fallback use the shared Chromium policy.
519
+ if engine == "lightpanda":
520
+ stripped = [browser_env.pop(k, None) for k in ("AGENT_BROWSER_ARGS", "AGENT_BROWSER_CHROME_FLAGS")]
521
+ if any(v is not None for v in stripped):
522
+ _bt.logger.debug("browser: stripped Chromium-only AGENT_BROWSER_ARGS/AGENT_BROWSER_CHROME_FLAGS "
523
+ "for Lightpanda command %s (agent-browser rejects them with --engine lightpanda)",
524
+ command)
525
+ else:
526
+ _apply_chromium_sandbox_args(browser_env)
527
+
528
+ stdout_path = os.path.join(task_socket_dir, f"_stdout_{command}")
529
+ stderr_path = os.path.join(task_socket_dir, f"_stderr_{command}")
530
+ proc = _popen_agent_browser(cmd_parts, browser_env, task_socket_dir, command)
531
+
532
+ try:
533
+ proc.wait(timeout=timeout)
534
+ except subprocess.TimeoutExpired:
535
+ proc.kill()
536
+ proc.wait()
537
+ stdout, stderr = _read_command_output_files(stdout_path, stderr_path)
538
+ _unlink_command_output_files(stdout_path, stderr_path)
539
+ _handle_browser_command_timeout(task_id, session_info, task_socket_dir)
540
+ if stderr and stderr.strip():
541
+ _bt.logger.warning("browser '%s' stderr after timeout: %s", command, stderr.strip()[:500])
542
+ _bt.logger.warning("browser '%s' timed out after %ds (task=%s, socket_dir=%s)",
543
+ command, timeout, task_id, task_socket_dir)
544
+ return {"success": False, "error": _format_browser_timeout_error(command, timeout, stdout, stderr)}
545
+ with open(stdout_path, "r", encoding="utf-8") as f:
546
+ stdout = f.read()
547
+ with open(stderr_path, "r", encoding="utf-8") as f:
548
+ stderr = f.read()
549
+ _unlink_command_output_files(stdout_path, stderr_path)
550
+ return _interpret_browser_command_output(command, stdout, stderr, proc.returncode)
551
+
552
+
553
+ def _run_browser_command(
554
+ task_id: str,
555
+ command: str,
556
+ args: List[str] = None,
557
+ timeout: Optional[int] = None,
558
+ _engine_override: Optional[str] = None,
559
+ ) -> Dict[str, Any]:
560
+ """Run one agent-browser CLI command against the task's session; returns its parsed JSON.
561
+ ``timeout=None`` reads ``browser.command_timeout``; ``_engine_override`` forces an engine
562
+ for this call only (Lightpanda fallback retries with Chrome without touching global state)."""
563
+ if timeout is None:
564
+ timeout = _bt._safe_command_timeout()
565
+ args = args or []
566
+
567
+ preflight = _browser_command_preflight()
568
+ if "browser_cmd" not in preflight:
569
+ return preflight
570
+ browser_cmd = preflight["browser_cmd"]
571
+
572
+ try:
573
+ session_info = _get_session_info(task_id)
574
+ except Exception as e:
575
+ _bt.logger.warning("Failed to create browser session for task=%s: %s", task_id, e)
576
+ return {"success": False, "error": f"Failed to create browser session: {str(e)}"}
577
+ # Cleanup stops the supervisor before closing the backend; keep it stopped.
578
+ if command != "close" and session_info.get("cdp_url"):
579
+ _cdp._ensure_cdp_supervisor(task_id)
580
+
581
+ # Cloud/CDP: ``--cdp <ws_url>`` (NEVER with --session: agent-browser >=0.13
582
+ # would create a local browser and silently ignore --cdp). Local: ``--session <name>``.
583
+ # Engine injection keys off the resolved session backend, not global provider
584
+ # state: hybrid routing can create a local sidecar while a cloud provider stays configured.
585
+ engine = _engine_override or _cloud._get_browser_engine()
586
+ if session_info.get("cdp_url"):
587
+ backend_args = ["--cdp", session_info["cdp_url"]]
588
+ else:
589
+ backend_args = ["--session", session_info["session_name"]]
590
+ if _cloud._is_headed_mode():
591
+ backend_args.append("--headed")
592
+ if engine != "auto" and not _bt._is_camofox_mode():
593
+ backend_args += ["--engine", engine]
594
+
595
+ cmd_parts = _agent_browser_argv(browser_cmd) + backend_args + ["--json", command] + args
596
+
597
+ try:
598
+ result = _spawn_and_collect(task_id, session_info, cmd_parts, command, engine, timeout)
599
+ except Exception as e:
600
+ _bt.logger.warning("browser '%s' exception: %s", command, e, exc_info=True)
601
+ result = {"success": False, "error": str(e)}
602
+
603
+ # Lightpanda automatic Chrome fallback — runs for ALL exit paths (timeout,
604
+ # empty, non-JSON, nonzero rc, parsed).
605
+ fallback_reason = _lp._lightpanda_fallback_reason(engine, command, result)
606
+ if fallback_reason:
607
+ _bt.logger.info("Lightpanda fallback: retrying '%s' with Chrome (task=%s): %s", command, task_id, fallback_reason)
608
+ if command == "screenshot": # separate Chrome session to the same URL
609
+ fallback_result = _lp._chrome_fallback_screenshot(task_id, args or [], timeout)
610
+ else:
611
+ fallback_result = _lp._run_chrome_fallback_command(task_id, command, args, timeout)
612
+ return _lp._annotate_lightpanda_fallback(fallback_result, fallback_reason)
613
+
614
+ return result
tools/browser_tool_snapshot.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Snapshot post-processing for the browser tools: truncate-and-store of oversized
2
+ accessibility trees, model-boundary secret redaction, screenshot-path recovery.
3
+
4
+ Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle.
5
+ """
6
+
7
+ import re
8
+ from typing import Any, Optional
9
+ from tools.browser_tool_origin import origin as _bt
10
+
11
+
12
+ _SCREENSHOT_PATH_PATTERNS = (
13
+ r"Screenshot saved to ['\"](?P<path>/[^'\"]+?\.png)['\"]",
14
+ r"Screenshot saved to (?P<path>/\S+?\.png)(?:\s|$)",
15
+ r"(?P<path>/\S+?\.png)(?:\s|$)",
16
+ )
17
+
18
+
19
+ def _extract_screenshot_path_from_text(text: str) -> Optional[str]:
20
+ """Extract a screenshot file path from agent-browser human-readable output."""
21
+ if not text:
22
+ return None
23
+
24
+ for pattern in _SCREENSHOT_PATH_PATTERNS:
25
+ match = re.search(pattern, text)
26
+ if match:
27
+ path = match.group("path").strip().strip("'\"")
28
+ if path:
29
+ return path
30
+ return None
31
+
32
+
33
+ def _store_full_snapshot(snapshot_text: str) -> Optional[str]:
34
+ """Write a full snapshot to cache/web and return its path (None on failure — best-effort).
35
+
36
+ Mirrors ``web_tools._store_full_text``: cache/web is mounted read-only into
37
+ remote backends, so read_file can page through the complete tree on any
38
+ backend. The stored copy is force-redacted (page-rendered secrets must not
39
+ hit disk unmasked) and named by content hash so identical snapshots dedupe.
40
+ """
41
+ try:
42
+ import hashlib
43
+ from hermes_constants import get_hermes_dir
44
+ from agent.redact import redact_sensitive_text
45
+
46
+ content = redact_sensitive_text(snapshot_text, force=True)
47
+ if len(content) > _bt.MAX_STORED_SNAPSHOT_CHARS:
48
+ content = (
49
+ content[:_bt.MAX_STORED_SNAPSHOT_CHARS]
50
+ + f"\n\n[... stored copy truncated at {_bt.MAX_STORED_SNAPSHOT_CHARS:,} chars "
51
+ f"of {len(content):,} ...]"
52
+ )
53
+ from tools.spill_safety import ensure_spill_dir, write_text_exclusive
54
+
55
+ cache_dir = get_hermes_dir("cache/web", "web_cache")
56
+ ensure_spill_dir(cache_dir, private=False)
57
+ digest = hashlib.sha256(content.encode("utf-8")).hexdigest()[:10]
58
+ path = cache_dir / f"browser-snapshot-{digest}.txt"
59
+ # Deterministic filename in a well-known dir: refuse symlinks (lstat-unlink +
60
+ # exclusive create); same-content re-snapshots legitimately overwrite. Not
61
+ # private: cache/web is bind-mounted into remote backends' container UID.
62
+ write_text_exclusive(path, content, private=False, overwrite=True)
63
+ return str(path)
64
+ except Exception as exc: # noqa: BLE001
65
+ _bt.logger.debug("Failed to store full browser snapshot: %s", exc)
66
+ return None
67
+
68
+
69
+ def _truncate_snapshot(snapshot_text: str, max_chars: Optional[int] = None) -> str:
70
+ """Truncate a snapshot at line boundaries (never mid-element) to ``max_chars``.
71
+
72
+ Defaults to ``browser.snapshot_threshold``. The full snapshot is stored to
73
+ cache/web and the appended note tells the agent how to page through it
74
+ with read_file — element refs beyond the cut are in the file, not lost.
75
+ """
76
+ if max_chars is None:
77
+ max_chars = _bt.get_browser_snapshot_threshold()
78
+ if len(snapshot_text) <= max_chars:
79
+ return snapshot_text
80
+
81
+ stored_path = _store_full_snapshot(snapshot_text)
82
+ if stored_path:
83
+ # Agent-visible path: read_file runs inside the active backend (#72389).
84
+ from tools.credential_files import to_agent_visible_cache_path
85
+ stored_path = to_agent_visible_cache_path(stored_path)
86
+
87
+ lines = snapshot_text.split('\n')
88
+ result: list[str] = []
89
+ chars = 0
90
+ # Reserve space for the truncation note (the stored-path variant is the
91
+ # longer of the two). Clamp so tiny max_chars values still keep content.
92
+ reserve = min(110 + len(stored_path or ""), max_chars // 2)
93
+ for line in lines:
94
+ if chars + len(line) + 1 > max_chars - reserve:
95
+ break
96
+ result.append(line)
97
+ chars += len(line) + 1
98
+ remaining = len(lines) - len(result)
99
+ if remaining > 0:
100
+ if stored_path:
101
+ next_line = len(result) + 1
102
+ result.append(
103
+ f'\n[... {remaining} more lines truncated — full snapshot: '
104
+ f'read_file path="{stored_path}" offset={next_line} limit=200]'
105
+ )
106
+ else:
107
+ result.append(f'\n[... {remaining} more lines truncated, use browser_snapshot for full content]')
108
+ return '\n'.join(result)
109
+
110
+
111
+ def _redact_browser_output(value: Any) -> Any:
112
+ """Force-redact secrets in browser-originated data (snapshots, console, eval
113
+ results can carry page-rendered keys/cookies/tokens). Tool output is a model
114
+ boundary, so this applies even when global log redaction is disabled."""
115
+ from agent.redact import redact_sensitive_text
116
+
117
+ if isinstance(value, str):
118
+ return redact_sensitive_text(value, force=True)
119
+ if isinstance(value, list):
120
+ return [_redact_browser_output(item) for item in value]
121
+ if isinstance(value, tuple):
122
+ return tuple(_redact_browser_output(item) for item in value)
123
+ if isinstance(value, dict):
124
+ return {_redact_browser_output(key): _redact_browser_output(item) for key, item in value.items()}
125
+ return value
tools/browser_tool_vision.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """browser_vision helpers: Lightpanda pre-route, native provider vision, auxiliary-LLM screenshot analysis.
2
+
3
+ Split out of ``tools/browser_tool.py``. Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle.
4
+ """
5
+
6
+ import os
7
+ import shutil
8
+ from pathlib import Path
9
+ from typing import Any, Dict, Optional, Tuple
10
+
11
+ from hermes_cli.config import cfg_get
12
+ from tools.browser_tool_origin import origin as _bt
13
+ from tools import browser_tool_cloud as _cloud
14
+ from tools import browser_tool_lightpanda_fallback as _lp
15
+
16
+
17
+ def _vision_mode_label() -> str:
18
+ _cp = _cloud._get_cloud_provider()
19
+ return "local" if _cp is None else f"cloud ({_cp.display_name})"
20
+
21
+
22
+ def _lightpanda_vision_preroute(
23
+ effective_task_id: str, annotate: bool, screenshot_path: Path,
24
+ ) -> Tuple[bool, Optional[str], Path]:
25
+ """Capture the vision screenshot via the Chrome fallback when Lightpanda is the engine
26
+ (it has no graphical renderer). Returns ``(prerouted, fallback_warning, path)``;
27
+ on fallback failure ``prerouted`` is False and the caller takes the normal
28
+ screenshot path (forcing Chrome) so the standard fallback metadata still applies."""
29
+ engine = _cloud._get_browser_engine()
30
+ if engine != "lightpanda" or not _cloud._should_inject_engine(engine):
31
+ return False, None, screenshot_path
32
+ _bt.logger.debug("browser_vision: pre-routing screenshot to Chrome (engine=lightpanda)")
33
+ screenshot_args = ["--annotate"] if annotate else []
34
+ fb_result = _lp._chrome_fallback_screenshot(effective_task_id, screenshot_args, _bt._get_command_timeout())
35
+ fb_result = _lp._annotate_lightpanda_fallback(fb_result, _bt._LP_VISION_FALLBACK_REASON)
36
+ if not fb_result.get("success"):
37
+ _bt.logger.warning("Lightpanda Chrome fallback vision screenshot failed: %s", fb_result.get("error"))
38
+ return False, None, screenshot_path
39
+ fb_path = fb_result.get("data", {}).get("path", "")
40
+ if fb_path and os.path.exists(fb_path):
41
+ import uuid as uuid_mod
42
+ from hermes_constants import get_hermes_dir
43
+
44
+ screenshots_dir = get_hermes_dir("cache/screenshots", "browser_screenshots")
45
+ screenshots_dir.mkdir(parents=True, exist_ok=True)
46
+ persistent_path = screenshots_dir / f"browser_screenshot_{uuid_mod.uuid4().hex}.png"
47
+ shutil.copy2(fb_path, persistent_path)
48
+ screenshot_path = persistent_path
49
+ return True, fb_result.get("fallback_warning"), screenshot_path
50
+
51
+
52
+ def _native_vision_result(
53
+ screenshot_path: Path, question: str, annotate: bool,
54
+ result: Dict[str, Any], lp_fallback_warning: Optional[str],
55
+ ) -> Dict[str, Any]:
56
+ """Multimodal tool-result envelope: the main model inspects the pixels itself.
57
+
58
+ The embed is baked into history and re-sent every later turn, so apply the same
59
+ proactive resize as vision_analyze's native path (skipped when already under
60
+ both caps; without Pillow it fails open to the raw bytes).
61
+ """
62
+ from tools.vision_tools import (
63
+ _EMBED_MAX_DIMENSION,
64
+ _EMBED_TARGET_BYTES,
65
+ _build_native_vision_tool_result,
66
+ _resize_image_for_vision,
67
+ )
68
+
69
+ data_url = _resize_image_for_vision(screenshot_path, mime_type="image/png", max_base64_bytes=_EMBED_TARGET_BYTES,
70
+ max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True)
71
+ native_result = _build_native_vision_tool_result(image_url=str(screenshot_path), question=question,
72
+ image_data_url=data_url,
73
+ image_size_bytes=screenshot_path.stat().st_size)
74
+ meta = native_result.setdefault("meta", {})
75
+ meta["screenshot_path"] = str(screenshot_path)
76
+ if lp_fallback_warning:
77
+ meta["fallback_warning"] = lp_fallback_warning
78
+ if annotate and result.get("data", {}).get("annotations"):
79
+ meta["annotations"] = result["data"]["annotations"]
80
+ native_result["text_summary"] = f"{native_result.get('text_summary', '')} Screenshot path: {screenshot_path}".strip()
81
+ return native_result
82
+
83
+
84
+ def _analyze_screenshot_with_aux_llm(screenshot_path: Path, question: str) -> str:
85
+ """One-shot aux vision-LLM analysis (not baked into history), secret-redacted.
86
+
87
+ Full resolution first; on a size-related provider rejection the image is
88
+ downscaled once and retried. ``auxiliary.vision.timeout/temperature`` — local
89
+ vision models can take well over 30s, so the default timeout is generous.
90
+ """
91
+ import base64
92
+
93
+ vision_prompt = (
94
+ f"You are analyzing a screenshot of a web browser.\n\n"
95
+ f"User's question: {question}\n\n"
96
+ f"Provide a detailed and helpful answer based on what you see in the screenshot. "
97
+ f"If there are interactive elements, describe them. If there are verification challenges "
98
+ f"or CAPTCHAs, describe what type they are and what action might be needed. "
99
+ f"Focus on answering the user's specific question."
100
+ )
101
+ _screenshot_bytes = screenshot_path.read_bytes()
102
+ _screenshot_b64 = base64.b64encode(_screenshot_bytes).decode("ascii")
103
+ data_url = f"data:image/png;base64,{_screenshot_b64}"
104
+ vision_model = _bt._get_vision_model()
105
+ _bt.logger.debug("browser_vision: analysing screenshot (%d bytes)", len(_screenshot_bytes))
106
+
107
+ vision_timeout = 120.0
108
+ vision_temperature = 0.1
109
+ try:
110
+ from hermes_cli.config import load_config
111
+ _vision_cfg = cfg_get(load_config(), "auxiliary", "vision", default={})
112
+ if _vision_cfg.get("timeout") is not None:
113
+ vision_timeout = float(_vision_cfg["timeout"])
114
+ if _vision_cfg.get("temperature") is not None:
115
+ vision_temperature = float(_vision_cfg["temperature"])
116
+ except Exception:
117
+ pass
118
+
119
+ from agent.auxiliary_client import call_llm # lazy: heavy client, only needed on the vision path
120
+
121
+ call_kwargs = {
122
+ "task": "vision", "temperature": vision_temperature, "timeout": vision_timeout,
123
+ "messages": [{"role": "user", "content": [
124
+ {"type": "text", "text": vision_prompt},
125
+ {"type": "image_url", "image_url": {"url": data_url}},
126
+ ]}],
127
+ }
128
+ if vision_model:
129
+ call_kwargs["model"] = vision_model
130
+ try:
131
+ response = call_llm(**call_kwargs)
132
+ except Exception as _api_err:
133
+ from tools.vision_tools import _is_image_size_error, _resize_image_for_vision, _RESIZE_TARGET_BYTES
134
+ if not (_is_image_size_error(_api_err) and len(data_url) > _RESIZE_TARGET_BYTES):
135
+ raise
136
+ _bt.logger.info("Vision API rejected screenshot (%.1f MB); auto-resizing to ~%.0f MB and retrying...",
137
+ len(data_url) / (1024 * 1024), _RESIZE_TARGET_BYTES / (1024 * 1024))
138
+ data_url = _resize_image_for_vision(screenshot_path, mime_type="image/png")
139
+ call_kwargs["messages"][0]["content"][1]["image_url"]["url"] = data_url
140
+ response = call_llm(**call_kwargs)
141
+
142
+ from agent.redact import redact_sensitive_text # the LLM may have read secrets off the screenshot
143
+ return redact_sensitive_text((response.choices[0].message.content or "").strip())
tools/browser_use_cli.py ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Use the Browser Use CLI 3.0 (https://browser-use.com) for browser automation
2
+
3
+ When browser.backend is "browser-use", the model gets ``browser_exec`` tool
4
+ instead of default browser tools
5
+ """
6
+
7
+ import contextlib
8
+ import importlib
9
+ import json
10
+ import logging
11
+ import os
12
+ import re
13
+ import shutil
14
+ import signal
15
+ import subprocess
16
+ import time
17
+ from pathlib import Path
18
+ from typing import Any, Callable, Dict, List, Optional, Tuple
19
+
20
+ from hermes_constants import get_hermes_home
21
+ from utils import is_truthy_value
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ _BACKEND_KEY = "browser-use"
26
+ BACKEND_DISABLED = "off"
27
+
28
+ # Cloud daemon names become the BU_NAME env var
29
+ _SESSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
30
+
31
+ # Set on the env dict by the CDP resolvers when the resolved browser is EXCLUSIVE to this named session
32
+ # (per-name provider / named BU cloud / Lightpanda). Popped before the subprocess launches — never exported.
33
+ _PRIVATE_BROWSER_SENTINEL = "_HERMES_BU_PRIVATE_BROWSER"
34
+
35
+ # Prepended to the model's code for named sessions on SHARED browsers (a /browser connect CDP override): the
36
+ # harness daemon attaches to the first existing page at startup, so two fresh named daemons can land on the
37
+ # SAME tab. Steering each onto a tab it created prevents clobbering. Runs once per daemon (marker keyed by
38
+ # BU_NAME + daemon pid).
39
+ _OWN_TAB_PREAMBLE = """\
40
+ # hermes: pin this named session to its own tab (once per daemon process)
41
+ def _hermes_ensure_own_tab():
42
+ import os as _os, tempfile as _tf
43
+ _name = _os.environ.get("BU_NAME", "default")
44
+ try:
45
+ # Key the marker by the daemon's pid so a daemon restart (which
46
+ # re-attaches to the first shared page) re-pins automatically,
47
+ # while agent-driven tab switches mid-session are left alone.
48
+ from browser_harness import _ipc as _bipc
49
+ _dpid = _bipc.pid_path(_name).read_text().strip() or "0"
50
+ except Exception:
51
+ _dpid = "0"
52
+ _uid = _os.getuid() if hasattr(_os, "getuid") else 0
53
+ _marker = _os.path.join(
54
+ _tf.gettempdir(), "hermes-bu-owntab-%s-%s-%s" % (_uid, _name, _dpid)
55
+ )
56
+ if _os.path.exists(_marker):
57
+ return
58
+ try:
59
+ # Force a fresh target: new_tab() would REUSE a blank current tab,
60
+ # which is exactly the tab a sibling daemon may also hold.
61
+ _tid = cdp("Target.createTarget", url="about:blank").get("targetId")
62
+ if _tid:
63
+ switch_tab(_tid)
64
+ except Exception:
65
+ pass # best-effort: worst case is pre-fix behavior
66
+ try:
67
+ open(_marker, "w").close()
68
+ except OSError:
69
+ pass
70
+ _hermes_ensure_own_tab()
71
+ del _hermes_ensure_own_tab
72
+ """
73
+
74
+ _DEFAULT_TIMEOUT_S = 300
75
+ _MIN_TIMEOUT_S = 5
76
+ _MAX_TIMEOUT_S = 1800
77
+ _STDERR_CAP_CHARS = 4000
78
+
79
+ _TASK_ID_SAFE_RE = re.compile(r"[^A-Za-z0-9._-]+") # filesystem-safe task ids
80
+ # Screenshot paths printed by capture_screenshot(): POSIX or Windows drive-letter absolute.
81
+ _IMAGE_PATH_RE = re.compile(r"((?:[A-Za-z]:[\\/]|/)[^\s\"']+?\.(?:png|jpe?g|webp))", re.IGNORECASE)
82
+ # http(s) URL literals in exec code checked against browser_navigate's policy
83
+ _URL_RE = re.compile(r"https?://[^\s'\"\\)]+", re.IGNORECASE)
84
+ _FHS_BIN_DIRS = ("/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin")
85
+
86
+
87
+ def _quiet(fn: Callable[[], Any], default: Any, log_prefix: str = "") -> Any:
88
+ """``fn()``, or ``default`` on any exception (debug-logged when ``log_prefix`` is set)."""
89
+ try:
90
+ return fn()
91
+ except Exception as e:
92
+ if log_prefix:
93
+ logger.debug("%s: %s", log_prefix, e)
94
+ return default
95
+
96
+
97
+ def _lazy_call(module: str, name: str, default: Any, log_prefix: str) -> Any:
98
+ """Call ``module.name()`` resolved at call time (tests stub the module / patch the
99
+ attribute); on any failure log ``log_prefix`` and return ``default``."""
100
+ return _quiet(lambda: getattr(importlib.import_module(module), name)(), default, log_prefix)
101
+
102
+
103
+ def _camofox_active(context: str = "") -> bool:
104
+ return _lazy_call("tools.browser_camofox", "is_camofox_mode", False, f"Camofox activity check failed{context}")
105
+
106
+
107
+ def _real_profile_consented() -> bool:
108
+ return _lazy_call("tools.browser_tool_cloud", "_use_real_profile", False, "real-profile consent lookup failed")
109
+
110
+
111
+ def _set_cdp_env(env: dict, cdp: str) -> None:
112
+ """Export a CDP endpoint under the BU_CDP_* contract (http(s) → URL, else WS)."""
113
+ env["BU_CDP_URL" if cdp.startswith(("http://", "https://")) else "BU_CDP_WS"] = cdp
114
+
115
+
116
+ def _has_cdp_env(env: dict) -> bool:
117
+ return bool(env.get("BU_CDP_WS") or env.get("BU_CDP_URL"))
118
+
119
+
120
+ def _export_session_cdp(env: dict, get_session_info: Callable[[str], Any], cache_key: str,
121
+ fail_msg: Callable[[Exception], str], no_cdp_msg: str) -> Optional[str]:
122
+ """Export the CDP endpoint from ``get_session_info(cache_key)``; error string on failure / no CDP."""
123
+ try:
124
+ cdp = str((get_session_info(cache_key) or {}).get("cdp_url") or "")
125
+ except Exception as e:
126
+ return fail_msg(e)
127
+ if not cdp:
128
+ return no_cdp_msg
129
+ _set_cdp_env(env, cdp)
130
+ return None
131
+
132
+
133
+ def _blocked_url_in_code(code: str) -> Optional[str]:
134
+ """Return an error if a URL literal fails the built-in navigation checks."""
135
+ from tools.browser_tool import evaluate_url_safety
136
+ return next((err.get("error", "Blocked: unsafe URL") for err in map(evaluate_url_safety, _URL_RE.findall(code or "")) if err), None)
137
+
138
+
139
+ def _base_subprocess_env() -> dict:
140
+ from tools.browser_tool import _build_browser_env
141
+ env = _build_browser_env()
142
+ # The CLI runs under its own Python (uv tool / uvx); an inherited PYTHONPATH/PYTHONHOME
143
+ # (Hermes's venv) wins over its site-packages → wrong-ABI C-extensions and a crash.
144
+ # PYTHONPATH/PYTHONHOME inherited from the agent process point at Hermes's venv site-packages, and a
145
+ # child interpreter honors them ahead of its own site-packages — so the CLI imports compiled
146
+ # C-extensions (e.g. pydantic_core) built for the wrong interpreter and crashes on ABI mismatch (#83427,
147
+ # #84841, #86006, #86104). Strip both — the CLI manages its own environment and never needs Hermes's
148
+ # import path.
149
+ env.pop("PYTHONPATH", None)
150
+ env.pop("PYTHONHOME", None)
151
+ env["PATH"] = _floor_subprocess_path(env.get("PATH", ""))
152
+ env.setdefault("ANONYMIZED_TELEMETRY", "false")
153
+ return env
154
+
155
+
156
+ def _floor_subprocess_path(path: str) -> str:
157
+ """Guarantee core system dirs on the CLI subprocess PATH: profile workers (kanban bots, cron) can inherit
158
+ a PATH of only version-manager dirs, and the uv binary's POSIX sh trampoline resolves ``dirname``/``realpath``
159
+ via PATH (exit 127 without /usr/bin). Reuses browser_tool's ``_merge_browser_path`` floor, else appends
160
+ FHS bin dirs. Windows .cmd shims don't trampoline: no-op there."""
161
+ if os.name == "nt":
162
+ return path
163
+ with contextlib.suppress(Exception):
164
+ from tools.browser_tool_install import _merge_browser_path
165
+ return _merge_browser_path(path or "")
166
+ parts = [p for p in (path or "").split(os.pathsep) if p]
167
+ return os.pathsep.join(parts + [d for d in _FHS_BIN_DIRS if d not in set(parts) and os.path.isdir(d)])
168
+
169
+
170
+ def _read_browser_cfg() -> dict:
171
+ """Return the ``browser:`` config section, or {} on any failure."""
172
+ try:
173
+ from hermes_cli.config import cfg_get, read_raw_config
174
+ cfg = cfg_get(read_raw_config(), "browser", default={})
175
+ return cfg if isinstance(cfg, dict) else {}
176
+ except Exception as e:
177
+ logger.debug("Could not read browser config section: %s", e)
178
+ return {}
179
+
180
+
181
+ def _use_gateway(browser_cfg: dict) -> bool:
182
+ """True when the browser section selects the Nous Tool Gateway — by the current ``hermes tools``
183
+ picker row (``cloud_provider: nous``) or the pre-picker ``use_gateway: true`` flag. Reading only
184
+ the legacy flag missed every picker-configured gateway, and the direct-API branch it fell into
185
+ holds no credentials in managed mode (#108310)."""
186
+ if is_truthy_value(browser_cfg.get("use_gateway"), default=False):
187
+ return True
188
+ try:
189
+ from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER
190
+ except Exception: # pragma: no cover — helper ships with the package
191
+ return False
192
+ return str(browser_cfg.get("cloud_provider") or "").strip().lower() == NOUS_MANAGED_PROVIDER
193
+
194
+
195
+ def get_browser_backend() -> str:
196
+ """Configured browser backend key ("" = unset → default). YAML 1.1 parses an
197
+ unquoted ``off`` as False — that must mean BACKEND_DISABLED, not "unset"."""
198
+ raw = _read_browser_cfg().get("backend")
199
+ return (BACKEND_DISABLED if raw is False else "") if isinstance(raw, bool) else str(raw or "").strip().lower()
200
+
201
+
202
+ def is_legacy_browser_use_cloud_config(browser_cfg: dict) -> bool:
203
+ """True for pre-CLI direct-API Browser Use cloud configs. An explicit backend or
204
+ a non-Browser-Use cloud_provider wins; Camofox is selected via env var, not
205
+ cloud_provider, so a Camofox user with a stray BROWSER_USE_API_KEY keeps it."""
206
+ if not isinstance(browser_cfg, dict) or browser_cfg.get("backend"):
207
+ return False
208
+ provider = str(browser_cfg.get("cloud_provider") or "").strip().lower()
209
+ if provider not in {"browser-use", ""} or _use_gateway(browser_cfg) or _camofox_active(" during migration"):
210
+ return False
211
+ # Profile credential: a multiplexed secondary must not inherit the default's cloud mode.
212
+ from agent.secret_scope import get_secret
213
+ return bool(get_secret("BROWSER_USE_API_KEY", ""))
214
+
215
+
216
+ def is_browser_use_cli_mode() -> bool:
217
+ """True when the Browser Use CLI replaces the built-in browser stack. Browser Use mode is the DEFAULT:
218
+ unset ``browser.backend`` ("") enables it whenever the CLI is runnable (installed binary or uvx);
219
+ ``browser.backend: off`` keeps the built-in browser_* tools. Camofox always falls back to the built-in
220
+ tools (Firefox, custom HTTP API, no CDP surface for the harness)."""
221
+ if _camofox_active():
222
+ return False
223
+ backend = get_browser_backend()
224
+ return backend == _BACKEND_KEY if backend else (is_legacy_browser_use_cloud_config(_read_browser_cfg()) or _find_cli() is not None)
225
+
226
+
227
+ def default_downgrade_notice() -> Optional[str]:
228
+ """One-line notice when ``browser.backend`` is unset but the CLI is not runnable, so
229
+ the session fell back to the built-in tools. Rate-limited to once per 24h via a stamp file."""
230
+ try:
231
+ if get_browser_backend() or _camofox_active() or _find_cli() is not None:
232
+ return None # explicit choice / Camofox / CLI present — nothing downgraded
233
+ stamp = Path(get_hermes_home()) / "cache" / ".browser_use_default_notice"
234
+ with contextlib.suppress(OSError):
235
+ if 0 <= time.time() - stamp.stat().st_mtime < 24 * 3600:
236
+ return None
237
+ with contextlib.suppress(OSError):
238
+ stamp.parent.mkdir(parents=True, exist_ok=True)
239
+ stamp.touch()
240
+ return ("Browser Use CLI not found — using the built-in browser tools. Run `hermes tools` "
241
+ "(Browser Automation → Browser Use) to install it, or `browser.backend: off` in config.yaml to silence this.")
242
+ except Exception as e: # pragma: no cover — a notice must never break startup
243
+ logger.debug("browser-use downgrade notice failed: %s", e)
244
+ return None
245
+
246
+
247
+ def _managed_bin_dir() -> str:
248
+ """$HERMES_HOME/bin — where install.sh puts uv/uvx and install_cli() links browser-use."""
249
+ return str(Path(get_hermes_home()) / "bin")
250
+
251
+
252
+ def _find_cli() -> Optional[List[str]]:
253
+ """Locate the browser-use CLI, or None when it can't be run. MANAGED-FIRST: Hermes' own ``$HERMES_HOME/bin``
254
+ copy always wins so every session drives one Hermes-controlled binary; PATH and the user-level tool dir
255
+ (~/.local/bin, or uv's %APPDATA%/uv/bin on Windows — Desktop/TUI workers may start with a minimal PATH
256
+ that omits it) are fallbacks; uvx zero-install (same probe order) is last."""
257
+ if os.name == "nt":
258
+ appdata = os.environ.get("APPDATA")
259
+ user_bin = str(Path(appdata) / "uv" / "bin") if appdata else None
260
+ else:
261
+ user_bin = str(Path(os.path.expanduser("~")) / ".local" / "bin")
262
+ probe_paths = [p for p in (_managed_bin_dir(), None, user_bin) if p is None or p] # None = PATH
263
+ for name, argv in (("browser-use", lambda b: [b]), ("uvx", lambda b: [b, "browser-use"])):
264
+ for probe_path in probe_paths:
265
+ found = shutil.which(name, path=probe_path)
266
+ if found:
267
+ return argv(found)
268
+ return None
269
+
270
+
271
+ def install_cli(timeout_s: int = 600) -> Tuple[bool, str]:
272
+ """Install the browser-use CLI via ``uv tool install`` (managed uv via ``ensure_uv`` → uv on PATH), linking
273
+ the binary into ``$HERMES_HOME/bin`` (``UV_TOOL_BIN_DIR``) so ``_find_cli()`` resolves it for every profile.
274
+ Returns ``(ok, message)``; never raises. MANAGED-FIRST: only the managed copy short-circuits — a browser-use
275
+ on PATH is a user-level side install and must not block provisioning the canonical copy (version drift)."""
276
+ bin_dir = _managed_bin_dir()
277
+ managed = shutil.which("browser-use", path=bin_dir)
278
+ if managed:
279
+ return True, f"browser-use CLI already installed ({managed})"
280
+
281
+ def _managed_uv() -> Optional[str]:
282
+ from hermes_cli.managed_uv import ensure_uv
283
+ return str(ensure_uv() or "") or None
284
+ uv_bin = _quiet(_managed_uv, None, "Managed uv bootstrap unavailable") or shutil.which("uv")
285
+ if not uv_bin:
286
+ return False, ("uv is not available and could not be bootstrapped. Install uv "
287
+ "(https://docs.astral.sh/uv/) and run `uv tool install browser-use`.")
288
+ env = {**os.environ, "UV_NO_CONFIG": "1"}
289
+ try:
290
+ Path(bin_dir).mkdir(parents=True, exist_ok=True)
291
+ env["UV_TOOL_BIN_DIR"] = bin_dir
292
+ except OSError as e:
293
+ logger.debug("Could not prepare %s: %s", bin_dir, e)
294
+
295
+ try:
296
+ result = subprocess.run([uv_bin, "tool", "install", "browser-use"], capture_output=True, text=True, encoding="utf-8",
297
+ errors="replace", env=env, timeout=timeout_s, stdin=subprocess.DEVNULL)
298
+ except subprocess.TimeoutExpired:
299
+ return False, f"`uv tool install browser-use` timed out after {timeout_s}s"
300
+ except Exception as e:
301
+ return False, f"Failed to run `uv tool install browser-use`: {e}"
302
+
303
+ if result.returncode != 0:
304
+ tail = "\n".join((result.stderr or result.stdout or "").strip().splitlines()[-3:])
305
+ return False, f"`uv tool install browser-use` failed:\n{tail}"
306
+ found = _find_cli()
307
+ if not found or len(found) != 1:
308
+ return False, ("install reported success but the browser-use binary is still not resolvable — "
309
+ "run `uv tool install browser-use` manually")
310
+ return True, f"browser-use CLI installed ({found[0]})"
311
+
312
+
313
+ def _workspace_dir(task_id: Optional[str]) -> Optional[str]:
314
+ """Stable per-task scratch dir that persists across browser_exec calls"""
315
+ if os.environ.get("BH_AGENT_WORKSPACE"):
316
+ return os.environ["BH_AGENT_WORKSPACE"]
317
+ try:
318
+ safe = _TASK_ID_SAFE_RE.sub("_", str(task_id or "default"))[:80] or "default"
319
+ path = Path(get_hermes_home()) / "cache" / "browser-use" / "workspace" / safe
320
+ path.mkdir(parents=True, exist_ok=True)
321
+ return str(path)
322
+ except Exception as e:
323
+ logger.debug("browser_exec workspace unavailable: %s", e)
324
+ return None
325
+
326
+
327
+ def _find_screenshot(stdout: str, since: float) -> Optional[str]:
328
+ """Last screenshot path printed during this exec that exists and was written after
329
+ the exec started, or None."""
330
+ for path in reversed(_IMAGE_PATH_RE.findall(stdout or "")):
331
+ try:
332
+ if os.path.isfile(path) and os.path.getmtime(path) >= since - 1:
333
+ return path
334
+ except OSError:
335
+ continue
336
+ return None
337
+
338
+
339
+ def _native_screenshot_result(result: Dict[str, Any], path: str) -> Optional[Dict[str, Any]]:
340
+ """Build a multimodal tool result attaching path for vision models"""
341
+ try:
342
+ from tools.vision_tools import (_EMBED_MAX_DIMENSION, _EMBED_TARGET_BYTES,
343
+ _resize_image_for_vision, _should_use_native_vision_fast_path)
344
+ if not _should_use_native_vision_fast_path():
345
+ return None
346
+ # History-reuse cap: this data URL bakes into the tool result and is re-sent every later turn —
347
+ # same policy as the vision_analyze / browser_vision native embeds.
348
+ data_url = _resize_image_for_vision(Path(path), mime_type="image/png", max_base64_bytes=_EMBED_TARGET_BYTES,
349
+ max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True)
350
+ text = json.dumps(result, ensure_ascii=False)
351
+ attached = text + "\n\nThe screenshot from this call is attached — inspect it with your native vision."
352
+ return {"_multimodal": True, "text_summary": text, "meta": {"screenshot_path": path, "native_vision": True},
353
+ "content": [{"type": "text", "text": attached}, {"type": "image_url", "image_url": {"url": data_url}}]}
354
+ except Exception as e:
355
+ logger.debug("Native screenshot attach failed (falling back to text): %s", e)
356
+ return None
357
+
358
+
359
+ def _served_profile_tag() -> str:
360
+ """``""`` outside a served-profile scope (every legacy key stays byte-identical); under a
361
+ multiplexed turn, the routed profile's home key — one profile's browser must never be handed
362
+ to another that happens to use the same session name or task id (#110032)."""
363
+ from hermes_constants import get_hermes_home_override, hermes_home_key
364
+ return "" if get_hermes_home_override() is None else hermes_home_key()
365
+
366
+
367
+ def _backend_cache_key(task_id: Optional[str], session_name: str = "") -> str:
368
+ """Session-cache key for a backend browser: named sessions get their own; served profiles get their own."""
369
+ key = f"bu-named-{session_name}" if session_name else (task_id or "browser-exec-default")
370
+ tag = _served_profile_tag()
371
+ return f"{key}@{tag}" if tag else key
372
+
373
+
374
+ def _resolve_lightpanda_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]:
375
+ """Point the harness at a Hermes-spawned ``lightpanda serve`` (``browser.engine: lightpanda`` and
376
+ nothing of higher precedence claimed the session). Each cache key gets its own process via the
377
+ legacy ``_get_session_info()`` (cache, reaper, atexit): private browser, own-tab preamble skipped."""
378
+ try:
379
+ from tools.browser_tool_session import _get_session_info
380
+ from tools.browser_tool_lightpanda_fallback import _using_lightpanda_engine
381
+ if not _using_lightpanda_engine():
382
+ return None
383
+ except Exception as e: # stubbed browser_tool in tests / engine lookup failure
384
+ logger.debug("browser engine lookup failed: %s", e)
385
+ return None
386
+ err = _export_session_cdp(
387
+ env, _get_session_info, _backend_cache_key(task_id, session_name),
388
+ lambda e: (f"Lightpanda could not be started: {e} Set browser.engine to auto "
389
+ "to use local Chrome, or switch backends via `hermes tools` → Browser Automation."),
390
+ "Lightpanda session returned no CDP endpoint. Set browser.engine to auto to use local Chrome.",
391
+ )
392
+ if err is None:
393
+ env[_PRIVATE_BROWSER_SENTINEL] = "1"
394
+ return err
395
+
396
+
397
+ def _resolve_managed_chromium_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]:
398
+ """Point the harness at Hermes' packaged Chromium, launched through agent-browser for this cache key —
399
+ the same browser the built-in tools drive. Left alone, the harness discovers the user's INSTALLED
400
+ Chrome on its default profile, which needs the chrome://inspect toggle + an Allow popup per run and
401
+ is blocked outright on Chrome >=136; on a headless box it just reports ``chrome-not-running``.
402
+ ``get cdp-url`` runs through ``_run_browser_command`` (legacy cache, inactivity reaper, atexit, Chromium
403
+ preflight/auto-install) on EVERY call: it launches the browser cold, follows a relaunch, and refreshes
404
+ the agent-browser daemon's idle timer, which never sees the harness's direct CDP traffic."""
405
+ try:
406
+ from tools.browser_tool_session import _run_browser_command
407
+ from tools.browser_tool import _get_open_command_timeout
408
+ except Exception as e: # pragma: no cover — stubbed browser_tool in tests
409
+ logger.debug("managed chromium resolution unavailable: %s", e)
410
+ return None
411
+ res = _run_browser_command(_backend_cache_key(task_id, session_name), "get", ["cdp-url"],
412
+ timeout=_get_open_command_timeout(first_open=True))
413
+ cdp = str(((res or {}).get("data") or {}).get("cdpUrl") or "") if (res or {}).get("success") else ""
414
+ if not cdp:
415
+ return (f"The local browser could not be started: {(res or {}).get('error') or 'agent-browser returned no CDP endpoint'} "
416
+ "Run `hermes tools` → Browser Automation to (re)install Chromium, or switch backends.")
417
+ _set_cdp_env(env, cdp)
418
+ env[_PRIVATE_BROWSER_SENTINEL] = "1" # one Chromium per cache key: nothing to share a tab with
419
+ return None
420
+
421
+
422
+ def _resolve_local_engine_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]:
423
+ """Local engine (no provider / override): ``browser.engine: lightpanda`` or the packaged Chromium."""
424
+ err = _resolve_lightpanda_cdp(env, task_id, session_name)
425
+ if err or _has_cdp_env(env):
426
+ return err
427
+ return _resolve_managed_chromium_cdp(env, task_id, session_name)
428
+
429
+
430
+ def _resolve_backend_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]:
431
+ """Point the harness at the configured backend's CDP endpoint; error string on failure.
432
+
433
+ Precedence: (1) ``BU_CDP_WS``/``BU_CDP_URL`` already in env (operator override); (2) ``BROWSER_CDP_URL``
434
+ env / ``browser.cdp_url`` (``/browser connect``); (3) a cloud provider via the legacy ``_get_session_info()``
435
+ so browser_exec shares the SAME session machinery (per-task cache, expiry, reaper, atexit);
436
+ (4) the local engine — ``browser.engine: lightpanda`` or Hermes' packaged Chromium via agent-browser
437
+ (never the harness's own discovery of the user's installed Chrome); (5) BU direct-API configs → None:
438
+ the CLI reaches BU cloud natively (BU_AUTOSPAWN). ``session_name`` (BU_NAME) keys the session cache so
439
+ each name gets its OWN browser — what makes named sessions concurrent-safe.
440
+ """
441
+ if _has_cdp_env(env):
442
+ return None
443
+ try:
444
+ from tools.browser_tool_cloud import _get_cloud_provider
445
+ from tools.browser_tool_session import _get_session_info
446
+ from tools.browser_tool_cdp import _get_cdp_override
447
+ except Exception as e: # pragma: no cover — stubbed browser_tool in tests
448
+ logger.debug("browser_tool backend resolution unavailable: %s", e)
449
+ return None
450
+ override = _quiet(_get_cdp_override, "")
451
+ if override:
452
+ _set_cdp_env(env, override)
453
+ return None
454
+ provider = _quiet(_get_cloud_provider, None, "Cloud provider lookup failed")
455
+ if provider is None:
456
+ return _resolve_local_engine_cdp(env, task_id, session_name)
457
+
458
+ # Browser Use direct-API configs: the CLI talks to BU cloud natively (BU_AUTOSPAWN / auth login) — the
459
+ # legacy provider would create a second, redundant session. Nous-gateway configs (cloud_provider: nous
460
+ # from the picker, or the pre-picker use_gateway: true) DO resolve through the provider: the gateway
461
+ # provisions the browser server-side and returns its CDP URL.
462
+ provider_key = str(getattr(provider, "name", "") or "").strip().lower()
463
+ if provider_key == _BACKEND_KEY and not _use_gateway(_read_browser_cfg()):
464
+ env[_PRIVATE_BROWSER_SENTINEL] = "1" # named BU cloud browsers are exclusive to their daemon
465
+ return None
466
+
467
+ provider_name = type(provider).__name__
468
+ err = _export_session_cdp(
469
+ env, _get_session_info, _backend_cache_key(task_id, session_name),
470
+ lambda e: (f"Cloud browser provider {provider_name} failed to provide a session: {e}. "
471
+ "Fix the provider configuration or switch backends via `hermes tools` → Browser Automation."),
472
+ f"Cloud browser provider {provider_name} returned no CDP endpoint, so Browser Use mode "
473
+ "cannot drive it. Switch to the built-in browser tools for this provider.",
474
+ )
475
+ # A provider browser keyed bu-named-<name> is exclusive to this session — the
476
+ # own-tab preamble would just leak a blank tab into it.
477
+ if err is None and session_name:
478
+ env[_PRIVATE_BROWSER_SENTINEL] = "1"
479
+ return err
480
+
481
+
482
+ def _resolve_real_profile_cdp(env: dict, force_local: bool) -> Optional[str]:
483
+ """Point the harness at the user's real-profile copy-browser (a SNAPSHOT of their default Chromium
484
+ profile, hermes_cli.browser_connect) when consented. Two ways in: the effective backend is already local
485
+ (no provider, CDP override, or legacy BU cloud config) → silent upgrade; or ``force_local`` (consent-gated
486
+ ``local`` arg) → the user's browser even under a cloud backend. Operator overrides (BU_CDP_* env,
487
+ /browser connect, ``browser.cdp_url``) own the session either way. Fail closed: a launch error is
488
+ returned so a consented user is never silently downgraded."""
489
+ if not _real_profile_consented() or _has_cdp_env(env):
490
+ return None
491
+ try:
492
+ from tools.browser_tool_cdp import _get_cdp_override_raw
493
+ from tools.browser_tool_cloud import _get_cloud_provider
494
+ from tools.browser_tool_real_profile import _real_profile_cdp
495
+ except Exception as e: # pragma: no cover — stubbed browser_tool in tests
496
+ logger.debug("real-profile backend resolution unavailable: %s", e)
497
+ return None
498
+ if _quiet(_get_cdp_override_raw, ""):
499
+ return None
500
+ # Only auto-upgrade genuinely-local attaches; any cloud path (provider, provider lookup failure, or
501
+ # legacy BU cloud config) stays on its backend unless the model passes local=true.
502
+ if not force_local and (_quiet(_get_cloud_provider, object()) is not None
503
+ or is_legacy_browser_use_cloud_config(_read_browser_cfg())):
504
+ return None
505
+ cdp, err = _real_profile_cdp()
506
+ if cdp and not err:
507
+ _set_cdp_env(env, cdp)
508
+ return err or None
509
+
510
+
511
+ def _attach_vault_supervisor(env: dict, task_id: Optional[str]) -> None:
512
+ """Attach the per-task CDP supervisor to the browser this exec drives so ``browser_vault_fill`` has
513
+ a secret-capable WebSocket (never argv) into the SAME browser. Only CDP-routed backends expose an
514
+ endpoint; BU direct-cloud (BU_AUTOSPAWN) does not, and the vault tools report ``supervisor_required``."""
515
+ cdp = env.get("BU_CDP_WS") or env.get("BU_CDP_URL")
516
+ if not cdp:
517
+ return
518
+ try:
519
+ from tools.browser_supervisor import SUPERVISOR_REGISTRY
520
+ from tools.browser_tool_cdp import _get_dialog_policy_config, _resolve_cdp_override
521
+ policy, timeout_s = _get_dialog_policy_config()
522
+ SUPERVISOR_REGISTRY.get_or_start(task_id=task_id or "default", cdp_url=_resolve_cdp_override(cdp),
523
+ dialog_policy=policy, dialog_timeout_s=timeout_s)
524
+ except Exception as exc:
525
+ logger.debug("browser_exec: CDP supervisor attach failed (non-fatal): %s", exc)
526
+
527
+
528
+ def _route_backend(env: dict, session: str, task_id: Optional[str], local: bool) -> Optional[str]:
529
+ """Resolve where the harness connects; returns an error string or None. Real-profile consent runs
530
+ BEFORE provider resolution so a hit short-circuits the cloud path via the BU_CDP_* env contract. Named
531
+ sessions compose with the backend: BU_NAME namespaces the harness daemon (IPC socket, log, pid) and on
532
+ provider backends additionally keys its own cloud browser."""
533
+ rp_err = _resolve_real_profile_cdp(env, force_local=local)
534
+ if rp_err:
535
+ return rp_err
536
+ # local=True is only served by the real-profile route; consent off must not pretend.
537
+ if local and not _has_cdp_env(env) and not _real_profile_consented():
538
+ return ("local=true was requested but browser.use_real_profile is off. Enable it in config.yaml "
539
+ "(browser.use_real_profile: true) or the desktop Settings → Browser section, then retry.")
540
+ return _resolve_backend_cdp(env, task_id, session_name=session)
541
+
542
+
543
+ def _group_popen_kwargs() -> dict:
544
+ """Popen kwargs starting the CLI in its own process group (a new session on POSIX) so a
545
+ timeout can take down every process that inherited the capture pipes, not just the CLI
546
+ child. Windows also hides the console the .cmd shim would flash (as browser_tool does)."""
547
+ def _flags() -> dict:
548
+ from hermes_cli._subprocess_compat import windows_hide_flags
549
+ si = subprocess.STARTUPINFO()
550
+ si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
551
+ return {"creationflags": windows_hide_flags() | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
552
+ "startupinfo": si}
553
+ return _quiet(_flags, {}, "Windows hide-flags unavailable") if os.name == "nt" else {"start_new_session": True}
554
+
555
+
556
+ def _clamp_timeout(timeout_s: Any) -> int:
557
+ try:
558
+ return max(_MIN_TIMEOUT_S, min(int(timeout_s), _MAX_TIMEOUT_S))
559
+ except (TypeError, ValueError):
560
+ return _DEFAULT_TIMEOUT_S
561
+
562
+
563
+ # After a whole-group SIGKILL, every pipe holder is dead, so the drain below is normally
564
+ # instant; the deadline only guards against a process outside the group still holding a pipe.
565
+ _POST_KILL_DRAIN_S = 10.0
566
+
567
+
568
+ def _kill_cli_process_group(proc) -> None:
569
+ """SIGKILL the CLI's whole process group (POSIX; ``start_new_session`` made pgid == pid) or,
570
+ on Windows, its process tree via ``taskkill /T /F`` — the only group-wide kill it offers."""
571
+ if os.name == "nt":
572
+ from hermes_cli._subprocess_compat import windows_hide_flags
573
+ with contextlib.suppress(OSError, subprocess.SubprocessError):
574
+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], stdin=subprocess.DEVNULL,
575
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10,
576
+ check=False, creationflags=windows_hide_flags())
577
+ return
578
+ with contextlib.suppress(ProcessLookupError, PermissionError):
579
+ os.killpg(proc.pid, signal.SIGKILL) # windows-footgun: ok — POSIX only, the nt branch returned above
580
+
581
+
582
+ def _run_cli_killing_process_group(cmd, code, env, timeout):
583
+ """Run the CLI in its own process group and kill the whole group on timeout.
584
+
585
+ ``subprocess.run`` only kills the direct child on ``TimeoutExpired``; a grandchild that
586
+ inherited the stdout/stderr pipes (browser_harness daemon / Chrome helper) is orphaned
587
+ still holding them, and on Windows ``run()``'s unbounded post-kill ``communicate()`` then
588
+ blocks on pipe EOF forever — so the tool call, plus its activity heartbeat, wedges (#106244).
589
+ """
590
+ proc = subprocess.Popen(
591
+ cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
592
+ text=True, encoding="utf-8", errors="replace", env=env, **_group_popen_kwargs(),
593
+ )
594
+ try:
595
+ stdout, stderr = proc.communicate(input=code, timeout=timeout)
596
+ except subprocess.TimeoutExpired:
597
+ _kill_cli_process_group(proc)
598
+ with contextlib.suppress(subprocess.TimeoutExpired):
599
+ proc.communicate(timeout=_POST_KILL_DRAIN_S)
600
+ raise
601
+ return subprocess.CompletedProcess(cmd, proc.returncode, stdout, stderr)
602
+
603
+
604
+ def browser_exec(code: str, session: str = "", timeout_s: int = _DEFAULT_TIMEOUT_S,
605
+ task_id: Optional[str] = None, local: bool = False):
606
+ """Run Python code through the browser-use CLI, and return its output"""
607
+ from tools.registry import tool_error, tool_result
608
+ if not code or not code.strip():
609
+ return tool_error("No code provided. Pass Python that uses the pre-imported helpers, e.g. new_tab(\"https://example.com\") then print(page_info()).")
610
+
611
+ blocked = _blocked_url_in_code(code)
612
+ if blocked:
613
+ return tool_error(blocked)
614
+
615
+ cmd = _find_cli()
616
+ if not cmd:
617
+ return tool_error("browser-use CLI not found on PATH, and uvx is unavailable for a zero-install run. "
618
+ "Install it with `uv tool install browser-use` (or `pipx install browser-use`), "
619
+ "then run `browser-use --doctor` to verify the setup.")
620
+
621
+ env = _base_subprocess_env()
622
+ if session:
623
+ if not _SESSION_RE.match(session):
624
+ return tool_error(f"Invalid session name {session!r}: use 1-64 letters, digits, "
625
+ "dashes, or underscores (e.g. 'r7k2').")
626
+ env["BU_NAME"] = session
627
+ route_err = _route_backend(env, session, task_id, bool(local))
628
+ if route_err:
629
+ return tool_error(route_err)
630
+ _attach_vault_supervisor(env, task_id)
631
+
632
+ # SHARED browser (/browser connect CDP override): pin each named session to its own tab (see
633
+ # _OWN_TAB_PREAMBLE). Private per-name browsers skip this — nothing to collide with.
634
+ private_browser = env.pop(_PRIVATE_BROWSER_SENTINEL, None) # always pop: never exported to the CLI
635
+ if session and not private_browser:
636
+ code = _OWN_TAB_PREAMBLE + code
637
+
638
+ workspace = _workspace_dir(task_id)
639
+ if workspace:
640
+ env["BH_AGENT_WORKSPACE"] = workspace
641
+
642
+ # BU_AUTOSPAWN makes the CLI start a Browser Use cloud browser when no local
643
+ # Chrome/CDP endpoint is reachable (their API key authenticates it)
644
+ if "BU_AUTOSPAWN" not in env and is_legacy_browser_use_cloud_config(_read_browser_cfg()):
645
+ env["BU_AUTOSPAWN"] = "1"
646
+
647
+ timeout = _clamp_timeout(timeout_s)
648
+ started = time.time()
649
+ try:
650
+ proc = _run_cli_killing_process_group(cmd, code, env, timeout)
651
+ except subprocess.TimeoutExpired:
652
+ return tool_error(f"browser-use exec timed out after {timeout}s. The daemon may still be working; retry "
653
+ f"with a larger timeout_s (max {_MAX_TIMEOUT_S}), or split the work into several calls that "
654
+ "append to workspace files — anything already written to the workspace is preserved.")
655
+ except OSError as e:
656
+ return tool_error(f"Failed to launch browser-use CLI: {e}")
657
+
658
+ result = {"success": proc.returncode == 0, "exit_code": proc.returncode, "output": proc.stdout}
659
+ if workspace:
660
+ result["workspace"] = workspace
661
+ if session:
662
+ result["session"] = session
663
+ stderr = (proc.stderr or "").strip()
664
+ if len(stderr) > _STDERR_CAP_CHARS:
665
+ stderr = stderr[:_STDERR_CAP_CHARS] + "\n… (stderr truncated)"
666
+ if stderr:
667
+ result["stderr"] = stderr
668
+ screenshot = _find_screenshot(proc.stdout, started)
669
+ if screenshot:
670
+ result["screenshot_path"] = screenshot
671
+ native = _native_screenshot_result(result, screenshot)
672
+ if native is not None:
673
+ return native
674
+ return tool_result(result)
675
+
676
+
677
+ _HEADER_BASE = (
678
+ "Drive a real web browser via the Browser Use CLI: `code` runs as full Python (stdlib available) "
679
+ "with pre-imported browser helpers; stdout comes back in the result. Start `code` with a one-line "
680
+ "comment describing the step for the user in plain language, max 60 chars "
681
+ "(e.g. `# Searching Amazon for paper towels`) — the UI shows it as the step label.\n\n"
682
+ "STATE: the browser session and workspace persist across calls; Python variables do NOT (fresh "
683
+ "interpreter each call). The workspace dir is $BH_AGENT_WORKSPACE (also `workspace` in every result); "
684
+ "functions defined in agent_helpers.py there are auto-imported into every call. For multi-item tasks "
685
+ "('all N products / every entry'), append each batch to a JSON/CSV file in the workspace, then read it "
686
+ "back and aggregate in code — dedupe/count/sort with Python, not in your head — and verify the "
687
+ "collected count against what was asked before answering.\n\n"
688
+ "Batch each sub-procedure (navigate, wait, extract, act) into one call — do not spend a call per "
689
+ "action — but for long extractions prefer several medium calls that append to workspace files over "
690
+ "one giant call, so progress survives timeouts."
691
+ )
692
+
693
+ _HEADER_VISION = (
694
+ " Screenshots are attached to your context automatically: when the exec output contains a "
695
+ "capture_screenshot() path, the image arrives with this tool's result and you inspect it directly "
696
+ "with your own vision — never send browser screenshots to a separate vision tool."
697
+ )
698
+
699
+ _HEADER_TEXT_ONLY = (
700
+ " Your model cannot view images, so work text-first: page_info() for state, js() for "
701
+ "reading/extracting DOM text, fill_input(selector, text) for inputs, and "
702
+ "js(\"document.querySelector('…').click()\") for clicks — skip the screenshot-driven workflow described below."
703
+ )
704
+
705
+ # Appended when the local engine is Lightpanda: no graphical renderer, and one CDP
706
+ # connection holds one page — a second Target.createTarget fails with
707
+ # TargetAlreadyLoaded (drop the new_tab() sentence once lightpanda-io/browser#1962 lands).
708
+ _HEADER_LIGHTPANDA = (
709
+ " The local engine is Lightpanda (no graphical renderer, one page per session): capture_screenshot() "
710
+ "is unavailable, so work text-first; navigate with new_tab(url) exactly once, then goto_url(url) for "
711
+ "every later navigation — a second new_tab() fails with TargetAlreadyLoaded."
712
+ )
713
+
714
+ # Pinned quick-reference for the CLI's pre-imported helpers, replacing the live
715
+ # ``browser-use skill`` fetch (uncontrolled third-party text in every schema: version
716
+ # drift, supply-chain exposure, byte-unstable prompt). A/B benchmarked ~equal.
717
+ _HELPERS_DIGEST = (
718
+ "\n\nHELPERS (pre-imported): new_tab(url) opens/navigates (use for the FIRST navigation), goto_url(url) "
719
+ "navigates the current tab, wait_for_load() after navigation, page_info() summarizes the current page "
720
+ "state, js(expr) evaluates a JS expression and returns its value (js('document.title'); wrap function "
721
+ "bodies as js('(() => {...})()') — a bare '() => {...}' returns the function itself, uncalled), "
722
+ "fill_input(selector, text) types into inputs, click_at_xy(x, y) clicks viewport coordinates, "
723
+ "capture_screenshot() saves and prints a screenshot path, cdp('Domain.method', **kwargs) is raw CDP — "
724
+ "cdp('Accessibility.getFullAXTree')['nodes'] lists every element's role/name/backendDOMNodeId (filter "
725
+ "in Python before printing; it is thousands of nodes), then cdp('DOM.getBoxModel', backendNodeId=n) "
726
+ "gives click coordinates. ensure_real_tab() recovers from a stale/internal tab. Login walls: never guess "
727
+ "credentials; see the vault note below if present, otherwise stop and ask the user."
728
+ )
729
+
730
+
731
+ def _description_header() -> str:
732
+ """Header tailored to whether the active model can see images natively"""
733
+ if _lazy_call("tools.browser_tool_lightpanda_fallback", "lightpanda_engine_status", (False, ""),
734
+ "lightpanda engine status unavailable")[0]: # no screenshots, whatever the model sees
735
+ return _HEADER_BASE + _HEADER_TEXT_ONLY + _HEADER_LIGHTPANDA
736
+ vision = _lazy_call("tools.vision_tools", "_should_use_native_vision_fast_path", False, "")
737
+ return _HEADER_BASE + (_HEADER_VISION if vision else _HEADER_TEXT_ONLY)
738
+
739
+
740
+ def _dynamic_schema_overrides() -> dict:
741
+ overrides: dict = {"description": _description_header() + _HELPERS_DIGEST}
742
+ # ``local`` exists ONLY when the user consented to real-profile browsing — everyone
743
+ # else's schema carries zero extra surface. The caller memoizes on config.yaml mtime,
744
+ # so toggling consent applies next session, not mid-chat.
745
+ if _real_profile_consented():
746
+ props = dict(BROWSER_EXEC_SCHEMA["parameters"]["properties"])
747
+ props["local"] = {
748
+ "type": "boolean", "default": False,
749
+ "description": ("Drive the user's own local browser (a Hermes-managed copy of their real "
750
+ "default-Chromium profile, logins/cookies included) instead of the configured "
751
+ "cloud browser backend. Use when the user asks to act as themselves — their "
752
+ "accounts, their sessions. No-op when the backend is already local. Default false."),
753
+ }
754
+ overrides["parameters"] = {**BROWSER_EXEC_SCHEMA["parameters"], "properties": props}
755
+ return overrides
756
+
757
+
758
+ BROWSER_EXEC_SCHEMA = {
759
+ "name": "browser_exec",
760
+ # Static fallback description, used only when the CLI (and uvx) is unavailable
761
+ "description": (_HEADER_BASE + _HELPERS_DIGEST
762
+ + "\n\n(The browser-use CLI is not installed yet. Install it with `uv tool install browser-use`.)"),
763
+ "parameters": {
764
+ "type": "object",
765
+ "properties": {
766
+ "code": {"type": "string", "description": "Python code to execute using the pre-imported browser helpers. Use print(...) for any data you need back."},
767
+ "session": {"type": "string", "description": "Named isolated browser session — its own daemon and (on cloud backends) own browser, so concurrent tasks don't share tabs. Reuse the same name on every related call; omit for the shared default session."},
768
+ "timeout_s": {"type": "integer", "default": _DEFAULT_TIMEOUT_S,
769
+ "description": f"Max seconds to wait for the code to finish (default {_DEFAULT_TIMEOUT_S}, max {_MAX_TIMEOUT_S})."},
770
+ },
771
+ "required": ["code"],
772
+ },
773
+ }
774
+
775
+
776
+ # browser_exec is additionally gated at tool-definition time — sessions whose toolsets
777
+ # lack ``terminal`` never see it (model_tools._compute_tool_definitions). check_fn only
778
+ # answers "is Browser Use mode configured"; surface policy lives with the session.
779
+ from tools.registry import registry
780
+
781
+ registry.register(
782
+ name="browser_exec",
783
+ toolset="browser-use",
784
+ schema=BROWSER_EXEC_SCHEMA,
785
+ handler=lambda args, **kw: browser_exec(
786
+ code=args.get("code", ""), session=args.get("session", "") or "",
787
+ timeout_s=args.get("timeout_s", _DEFAULT_TIMEOUT_S), task_id=kw.get("task_id"),
788
+ local=bool(args.get("local", False)),
789
+ ),
790
+ check_fn=is_browser_use_cli_mode,
791
+ dynamic_schema_overrides=_dynamic_schema_overrides,
792
+ emoji="🌐",
793
+ )
tools/clarify_gateway.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gateway-side clarify primitive (blocking event-based queue). The agent runs on a worker
2
+ thread while the event loop handles the user's reply, so a pending clarify is stored
3
+ module-level (same shape as ``tools.approval``) and the agent thread blocks on an ``Event``
4
+ until an adapter button callback or the gateway text-intercept resolves it, or the timeout
5
+ fires. Adapters render inline buttons (an "Other" row flips the entry into text-capture
6
+ mode) or a numbered-list text fallback."""
7
+
8
+ from __future__ import annotations
9
+ import json
10
+ import logging
11
+ import threading
12
+ import time
13
+ from dataclasses import dataclass, field
14
+ from typing import Callable, Dict, List, Optional
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ @dataclass
20
+ class _ClarifyEntry:
21
+ """One pending clarify request inside a gateway session."""
22
+ clarify_id: str
23
+ session_key: str
24
+ question: str
25
+ choices: Optional[List[str]]
26
+ multi_select: bool = False
27
+ event: threading.Event = field(default_factory=threading.Event)
28
+ response: Optional[str] = None
29
+ awaiting_text: bool = False # set when user picked "Other" or clarify is open-ended
30
+
31
+
32
+ _lock = threading.RLock()
33
+ _entries: Dict[str, _ClarifyEntry] = {} # clarify_id -> entry (button callbacks)
34
+ _session_index: Dict[str, List[str]] = {} # session_key -> [clarify_id] FIFO (text intercept, cleanup)
35
+ # Per-session notify callbacks (gateway -> adapter bridge); mirrors tools.approval. Tests clear it.
36
+ _notify_cbs: Dict[str, Callable[[_ClarifyEntry], None]] = {}
37
+
38
+ # Outcomes for typed clarify replies. Gateway cancels the pending prompt on
39
+ # free prose (deadlock break) but keeps it armed for a retryable bad selection.
40
+ TEXT_RESOLVED = "resolved"
41
+ TEXT_REJECTED_PROSE = "rejected_prose"
42
+ TEXT_REJECTED_SELECTION = "rejected_selection"
43
+ TEXT_NO_PENDING = "no_pending"
44
+
45
+
46
+ def register(clarify_id: str, session_key: str, question: str, choices: Optional[List[str]],
47
+ multi_select: bool = False) -> _ClarifyEntry:
48
+ """Register a pending clarify request; caller then blocks on ``wait_for_response``.
49
+ Open-ended (no choices) entries start in text mode: the next message IS the response."""
50
+ entry = _ClarifyEntry(clarify_id, session_key, question, list(choices) if choices else None,
51
+ bool(multi_select) and bool(choices), awaiting_text=not bool(choices))
52
+ with _lock:
53
+ _entries[clarify_id] = entry
54
+ _session_index.setdefault(session_key, []).append(clarify_id)
55
+ return entry
56
+
57
+
58
+ def wait_for_response(clarify_id: str, timeout: float) -> Optional[str]:
59
+ """Block until the entry resolves or ``timeout`` (``<= 0`` = unlimited) elapses; None on
60
+ timeout/unknown id. Polls in 1s slices so the inactivity heartbeat keeps firing (a
61
+ single long ``Event.wait`` would let the gateway watchdog kill a live prompt)."""
62
+ with _lock:
63
+ entry = _entries.get(clarify_id)
64
+ if entry is None:
65
+ return None
66
+ try:
67
+ from tools.environments.base import touch_activity_if_due
68
+ except Exception: # pragma: no cover - optional
69
+ touch_activity_if_due = None
70
+ deadline = None if timeout is None or float(timeout) <= 0.0 else time.monotonic() + float(timeout)
71
+ activity_state = {"last_touch": time.monotonic(), "start": time.monotonic()}
72
+ while True:
73
+ remaining = 1.0 if deadline is None else deadline - time.monotonic()
74
+ if remaining <= 0 or entry.event.wait(timeout=min(1.0, remaining)):
75
+ break
76
+ # Periodic activity touch so the gateway's inactivity timeout doesn't kill the agent during long
77
+ # code execution (#10807).
78
+ if touch_activity_if_due is not None:
79
+ touch_activity_if_due(activity_state, "waiting for user clarify response")
80
+ with _lock:
81
+ _entries.pop(clarify_id, None) # regardless of outcome
82
+ ids = _session_index.get(entry.session_key) or []
83
+ if clarify_id in ids:
84
+ ids.remove(clarify_id)
85
+ if not ids:
86
+ _session_index.pop(entry.session_key, None)
87
+ return entry.response
88
+
89
+
90
+ def resolve_gateway_clarify(clarify_id: str, response: str) -> bool:
91
+ """Unblock the waiter on ``clarify_id``; False if already resolved/expired/unknown."""
92
+ with _lock:
93
+ entry = _entries.get(clarify_id)
94
+ if entry is None or entry.event.is_set():
95
+ return False
96
+ entry.response = str(response) if response is not None else ""
97
+ entry.event.set()
98
+ return True
99
+
100
+
101
+ def get_pending_for_session(session_key: str, *, include_choice_prompts: bool = False) -> Optional[_ClarifyEntry]:
102
+ """Oldest pending entry awaiting free text (open-ended, or after "Other");
103
+ ``include_choice_prompts=True`` returns the oldest unresolved entry of any kind (user
104
+ typed at an active choice prompt: resolve it rather than queue a follow-up turn)."""
105
+ with _lock:
106
+ for cid in _session_index.get(session_key) or []:
107
+ entry = _entries.get(cid)
108
+ if entry is not None and (include_choice_prompts or entry.awaiting_text):
109
+ return entry
110
+ return None
111
+
112
+
113
+ def _match_label(text: str, choices: List[str]) -> Optional[str]:
114
+ """Stripped choice text matching ``text`` case-insensitively, ignoring the '(Recommended)'
115
+ suffix the first choice carries by the time it reaches adapters; None if no match."""
116
+ from tools.clarify_tool import strip_recommended
117
+ wanted = strip_recommended(text).casefold()
118
+ for choice in choices:
119
+ if strip_recommended(str(choice)).casefold() == wanted:
120
+ return str(choice).strip()
121
+ return None
122
+
123
+
124
+ def _split_tokens(text: str) -> Optional[List[str]]:
125
+ """Comma-separated tokens, or space-separated all-numeric tokens ("1 3"); else None."""
126
+ if "," in text:
127
+ return [t.strip() for t in text.split(",") if t.strip()]
128
+ parts = text.split()
129
+ return parts if len(parts) > 1 and all(p.isdigit() for p in parts) else None
130
+
131
+
132
+ def _is_int(text: str) -> bool:
133
+ try:
134
+ int(text)
135
+ return True
136
+ except ValueError:
137
+ return False
138
+
139
+
140
+ def _selection_attempt_tokens(text: str, choices: Optional[List[str]] = None) -> Optional[List[str]]:
141
+ """Tokens when ``text`` looks like a typed selection (bare int, comma list,
142
+ all-numeric space list); None for free prose so the gateway can release the
143
+ clarify. Comma-list labels may span up to the longest choice's word count."""
144
+ stripped = str(text).strip()
145
+ if not stripped:
146
+ return None
147
+ tokens = _split_tokens(stripped)
148
+ if tokens is None:
149
+ digits = stripped[1:] if stripped.startswith("-") else stripped
150
+ return [stripped] if digits.isdigit() or _is_int(stripped) else None
151
+ if "," not in stripped or not tokens:
152
+ return tokens or None
153
+ max_words = max(1, max((len(str(c).split()) for c in choices or []), default=1))
154
+ return tokens if all(t.isdigit() or len(t.split()) <= max_words for t in tokens) else None
155
+
156
+
157
+ def _coerce_text_response(entry: _ClarifyEntry, response: str) -> Optional[str]:
158
+ """Accepted value for a typed reply, or None on any rejection."""
159
+ return _coerce_text_response_detailed(entry, response)[0]
160
+
161
+
162
+ def _coerce_text_response_detailed(entry: _ClarifyEntry, response: str) -> tuple[Optional[str], Optional[str]]:
163
+ """Map a typed reply to ``(value, None)`` or ``(None, reason)``: ``"invalid_selection"``
164
+ (selection-shaped but out of range/unrecognised — keep the clarify armed for a retry) or
165
+ ``"prose"`` (free text on a native choice prompt — the gateway may cancel and route normally
166
+ so a redirect-to-steer path cannot deadlock behind the waiting tool). Open-ended entries and
167
+ ``awaiting_text`` accept any text; numeric picks and exact labels always resolve; multi-select
168
+ returns a JSON array string (decoded tool-side); one bad token rejects the whole reply."""
169
+ text = str(response).strip()
170
+ if not entry.choices:
171
+ return text, None
172
+ if entry.multi_select:
173
+ coerced = _coerce_multi_select_text(entry, text)
174
+ selection_shaped = _selection_attempt_tokens(text, entry.choices) is not None
175
+ else:
176
+ # Out-of-range / non-canonical integer is a failed selection, not prose.
177
+ selection_shaped = _is_int(text)
178
+ idx = int(text) - 1 if selection_shaped else -1
179
+ coerced = entry.choices[idx] if 0 <= idx < len(entry.choices) else _match_label(text, entry.choices)
180
+ if coerced is not None:
181
+ return coerced, None
182
+ if entry.awaiting_text:
183
+ return text, None
184
+ return None, "invalid_selection" if selection_shaped else "prose"
185
+
186
+
187
+ def _coerce_multi_select_text(entry: _ClarifyEntry, text: str) -> Optional[str]:
188
+ """Parse "1,3" / "1 3" / "staging, prod" into a JSON array of choice labels;
189
+ None when any token is out of range or unrecognised (reject the whole reply)."""
190
+ choices, selected = entry.choices or [], []
191
+ if not text:
192
+ return None
193
+ tokens = _split_tokens(text)
194
+ for token in [text] if tokens is None else tokens:
195
+ if token.isdigit():
196
+ idx = int(token) - 1
197
+ label = str(choices[idx]).strip() if 0 <= idx < len(choices) else None
198
+ else:
199
+ label = _match_label(token, choices)
200
+ if label is None:
201
+ return None
202
+ if label not in selected:
203
+ selected.append(label)
204
+ return json.dumps(selected, ensure_ascii=False) if selected else None
205
+
206
+
207
+ def attempt_text_response_for_session(session_key: str, response: str) -> str:
208
+ """Try to resolve the oldest pending clarify from typed text; returns a TEXT_* outcome."""
209
+ entry = get_pending_for_session(session_key, include_choice_prompts=True)
210
+ if entry is None:
211
+ return TEXT_NO_PENDING
212
+ coerced, reason = _coerce_text_response_detailed(entry, response)
213
+ if coerced is None:
214
+ return TEXT_REJECTED_SELECTION if reason == "invalid_selection" else TEXT_REJECTED_PROSE
215
+ if resolve_gateway_clarify(entry.clarify_id, coerced):
216
+ return TEXT_RESOLVED
217
+ return TEXT_NO_PENDING # lost a race with a button/callback resolution — no work left
218
+
219
+
220
+ def resolve_text_response_for_session(session_key: str, response: str) -> bool:
221
+ """True only when the typed reply was accepted and the waiter unblocked."""
222
+ return attempt_text_response_for_session(session_key, response) == TEXT_RESOLVED
223
+
224
+
225
+ def mark_awaiting_text(clarify_id: str) -> bool:
226
+ """Flip an entry into text-capture mode (user picked 'Other'); False if unknown."""
227
+ with _lock:
228
+ entry = _entries.get(clarify_id)
229
+ if entry is not None:
230
+ entry.awaiting_text = True
231
+ return entry is not None
232
+
233
+
234
+ def has_pending(session_key: str) -> bool:
235
+ """True when this session has at least one pending clarify entry."""
236
+ with _lock:
237
+ return any(_entries.get(cid) is not None for cid in _session_index.get(session_key) or [])
238
+
239
+
240
+ def clear_session(session_key: str) -> int:
241
+ """Drop every pending clarify for a session (``/new``, shutdown, cached-agent eviction) so
242
+ blocked agent threads don't outlive it; returns how many were cancelled. Cancelled waiters
243
+ see "" (callers tell it from a real reply only via their own timeout bookkeeping; most treat
244
+ any falsy result as no response). First-writer-wins: an already-set entry was answered for
245
+ real, so it is dropped but its response preserved. The loop stays inside the lock so a button
246
+ callback cannot slip between pop and check; entries go regardless of state so a cleared
247
+ session is never resurrected by late callbacks."""
248
+ with _lock:
249
+ cancelled = 0
250
+ for entry in (_entries.pop(cid, None) for cid in list(_session_index.pop(session_key, []) or [])):
251
+ if entry is None or entry.event.is_set():
252
+ continue
253
+ entry.response = ""
254
+ entry.event.set()
255
+ cancelled += 1
256
+ return cancelled
257
+
258
+
259
+ def resolve_clarify_timeout(config: dict) -> int:
260
+ """Clarify timeout (seconds): legacy ``clarify.timeout`` if explicitly set, else
261
+ ``agent.clarify_timeout``, else 3600 — the single source of truth for every surface
262
+ (gateway, CLI, TUI). ``<= 0`` is kept verbatim (unlimited); non-numeric -> 3600."""
263
+ raw = (config.get("clarify") or {}).get("timeout")
264
+ if raw is None:
265
+ raw = (config.get("agent") or {}).get("clarify_timeout", 3600)
266
+ try:
267
+ return int(raw)
268
+ except (TypeError, ValueError):
269
+ return 3600
270
+
271
+
272
+ def get_clarify_timeout() -> int:
273
+ """Clarify timeout from config.yaml; 0/negative = unlimited. Default 3600: long enough
274
+ that a user who stepped away still finds a live entry when they tap, short enough that
275
+ an abandoned prompt eventually unblocks the agent thread instead of pinning the guard.
276
+
277
+ The old 600s default evicted the entry mid-think, so a late tap landed on a dead entry and the agent
278
+ hung on ``running: clarify`` (#32762).
279
+ """
280
+ try:
281
+ from hermes_cli.config import load_config
282
+ return resolve_clarify_timeout(load_config() or {})
283
+ except Exception:
284
+ return 3600
285
+
286
+
287
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
288
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
289
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
290
+ # The whole block is removed by reverting the commit that added it.
291
+
292
+ def get_notify(session_key: str) -> Optional[Callable[[_ClarifyEntry], None]]:
293
+ with _lock:
294
+ return _notify_cbs.get(session_key)
295
+
296
+ def register_notify(session_key: str, cb: Callable[[_ClarifyEntry], None]) -> None:
297
+ """Register a per-session notify callback used by ``clarify_callback``."""
298
+ with _lock:
299
+ _notify_cbs[session_key] = cb
300
+
301
+ def unregister_notify(session_key: str) -> None:
302
+ """Drop the per-session notify callback and cancel any pending clarify entries."""
303
+ with _lock:
304
+ _notify_cbs.pop(session_key, None)
305
+ # Cancel any pending entries so blocked threads unwind when the run
306
+ # ends (interrupt, completion, gateway shutdown).
307
+ clear_session(session_key)
308
+ # ---- END PLUGIN-COMPAT ----
tools/clarify_tool.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Clarify tool: structured multiple-choice / open-ended questions to the user.
2
+ Schema, validation and a thin dispatcher; the UI lives in a platform-provided
3
+ callback (cli.py, gateway/run.py, tui_gateway)."""
4
+
5
+ import inspect
6
+ import json
7
+ from typing import Dict, List, Optional, Callable
8
+
9
+ MAX_CHOICES = 4 # the UI always appends an "Other (type your answer)" row
10
+ MAX_QUESTIONS = 5 # independent questions per batch call
11
+ # Canonical timeout sentinel. The CLI returns this exact text; the batch loop
12
+ # treats it (like ``None``) as "the user walked away" and aborts remaining questions.
13
+ TIMEOUT_RESPONSE = ("The user did not provide a response within the time limit. "
14
+ "Use your best judgement to make the choice and proceed.")
15
+ # Applied to the first choice here (not per-surface) so every adapter renders it identically.
16
+ RECOMMENDED_LABEL = "(Recommended)"
17
+ _UNAVAILABLE = "Clarify tool is not available in this execution context."
18
+
19
+
20
+ def _flatten_choice(c) -> str:
21
+ """Coerce one choice to display text. LLMs sometimes emit dict-shaped choices and ``str(c)``
22
+ would leak the repr onto every surface and back as the answer; unwrap order ``label`` >
23
+ ``description`` > ``text`` > ``title`` (``name``/``value`` excluded: raw component enums,
24
+ not labels). No match -> "" and dropped: no choice beats a garbage label."""
25
+ if isinstance(c, str):
26
+ return c.strip()
27
+ if isinstance(c, dict):
28
+ return next((v.strip() for k in ("label", "description", "text", "title")
29
+ if isinstance(v := c.get(k), str) and v.strip()), "")
30
+ if isinstance(c, (list, tuple)):
31
+ return " ".join(_flatten_choice(x) for x in c).strip()
32
+ return "" if c is None else str(c).strip()
33
+
34
+
35
+ def mark_recommended(choices: List[str]) -> List[str]:
36
+ """Suffix the first choice (schema says best-first) with RECOMMENDED_LABEL; idempotent,
37
+ and a lone choice is left untouched (nothing to prefer it over)."""
38
+ first = str(choices[0]).strip() if choices else ""
39
+ if len(choices) < 2 or first != strip_recommended(first):
40
+ return choices
41
+ return [f"{first} {RECOMMENDED_LABEL}"] + list(choices[1:])
42
+
43
+
44
+ def strip_recommended(text: str) -> str:
45
+ """Remove the recommendation label so presentation never leaks into ``user_response``."""
46
+ stripped = str(text).strip()
47
+ if stripped.casefold().endswith(RECOMMENDED_LABEL.casefold()):
48
+ return stripped[: -len(RECOMMENDED_LABEL)].strip()
49
+ return stripped
50
+
51
+
52
+ def _accepts_kwarg(callback, name: str) -> bool:
53
+ """Signature-inspect (never a TypeError retry, which could re-prompt the user) whether
54
+ ``callback`` takes ``name`` or ``**kwargs``; non-introspectable callables are legacy."""
55
+ try:
56
+ params = inspect.signature(callback).parameters
57
+ except (TypeError, ValueError):
58
+ return False
59
+ return name in params or any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
60
+
61
+
62
+ def _invoke_callback(callback, question, choices, multi_select):
63
+ """Invoke the platform callback, passing multi_select if supported."""
64
+ if _accepts_kwarg(callback, "multi_select"):
65
+ return callback(question, choices, multi_select=multi_select)
66
+ return callback(question, choices)
67
+
68
+
69
+ def _json_as(raw: str, kind):
70
+ """``json.loads(raw)`` when it decodes to an instance of ``kind``, else None."""
71
+ try:
72
+ parsed = json.loads(raw)
73
+ except json.JSONDecodeError:
74
+ return None
75
+ return parsed if isinstance(parsed, kind) else None
76
+
77
+
78
+ def _parse_multi_select_response(raw_response) -> List[str]:
79
+ """Parse a list / JSON array / comma-separated reply into stripped non-empty strings."""
80
+ items = raw_response
81
+ if not isinstance(items, list):
82
+ raw = str(items).strip()
83
+ items = _json_as(raw, list) if raw.startswith("[") else None
84
+ if items is None:
85
+ items = raw.split(",")
86
+ return [str(r).strip() for r in items if str(r).strip()]
87
+
88
+
89
+ def _clean_answer(raw, multi: bool):
90
+ """Strip presentation (the label, multi-select JSON) from a locked answer."""
91
+ return [strip_recommended(r) for r in _parse_multi_select_response(raw)] if multi else strip_recommended(raw)
92
+
93
+
94
+ def _clean_choices(choices: list) -> Optional[List[str]]:
95
+ """Flatten, drop empties, cap at MAX_CHOICES; None when nothing survives (open-ended)."""
96
+ cleaned = [s for s in (_flatten_choice(c) for c in choices) if s]
97
+ return cleaned[:MAX_CHOICES] or None
98
+
99
+
100
+ def _is_timeout(raw) -> bool:
101
+ return raw is None or (isinstance(raw, str) and raw.strip() == TIMEOUT_RESPONSE)
102
+
103
+
104
+ # ============================================================================= Batch (multi-question)
105
+ # support — issue #18450 =============================================================================
106
+ def _normalize_questions(questions) -> tuple:
107
+ """Validate the ``questions`` batch param -> ``(normalized, error)``; an empty list gives
108
+ ``(None, None)`` (fall back to the single-question path). Entries carry ``qid`` (stable
109
+ wire id ``q<index>`` surfaces key answers by; the model's ``id`` is unvalidated text, only
110
+ echoed), ``question``, decorated ``choices``, bare ``choices_offered``, ``multi_select``."""
111
+ if not isinstance(questions, list):
112
+ return None, "questions must be an array of question objects."
113
+ if not questions:
114
+ return None, None
115
+ if len(questions) > MAX_QUESTIONS:
116
+ return None, f"questions supports at most {MAX_QUESTIONS} items."
117
+ normalized = []
118
+ for index, item in enumerate(questions):
119
+ if isinstance(item, str): # tolerate bare-string items: LLMs sometimes send ["Q1?", "Q2?"]
120
+ item = {"question": item}
121
+ if not isinstance(item, dict):
122
+ return None, f"questions[{index}] must be an object with a 'question'."
123
+ text = str(item.get("question") or "").strip()
124
+ if not text:
125
+ return None, f"questions[{index}].question must be non-empty text."
126
+ choices = item.get("choices")
127
+ if choices is not None:
128
+ if not isinstance(choices, list):
129
+ return None, f"questions[{index}].choices must be a list."
130
+ choices = _clean_choices(choices)
131
+ normalized.append({
132
+ "qid": f"q{index}", "id": str(item.get("id") or "").strip() or None, "question": text,
133
+ "choices": mark_recommended(list(choices)) if choices else None,
134
+ "choices_offered": list(choices) if choices else None,
135
+ "multi_select": bool(item.get("multi_select")) and bool(choices)})
136
+ return normalized, None
137
+
138
+
139
+ def _batch_result(normalized: List[dict], answers: dict, timed_out: bool) -> str:
140
+ """Batch result JSON; unanswered -> "". The top-level ``timed_out`` flag (present only when
141
+ true) tells the agent whether blanks are deliberate skips or the user walking away."""
142
+ responses = []
143
+ for entry in normalized:
144
+ raw = answers.get(entry["qid"])
145
+ responses.append({
146
+ **({"id": entry["id"]} if entry["id"] else {}),
147
+ "question": entry["question"], "choices_offered": entry["choices_offered"],
148
+ "user_response": _clean_answer(raw, entry["multi_select"]) if raw else ""})
149
+ result: Dict[str, object] = {"responses": responses}
150
+ if timed_out:
151
+ result["timed_out"] = True
152
+ return json.dumps(result, ensure_ascii=False)
153
+
154
+
155
+ def _run_batch(normalized: List[dict], callback, question: str) -> str:
156
+ """Dispatch a validated batch. Batch-capable callbacks (``questions`` kwarg) get the
157
+ whole list once and reply ``{"answers": {qid: raw}, "timed_out"?}`` as a dict or JSON
158
+ string (the tui_gateway bridge only carries strings); any other falsy/unparseable reply
159
+ is a cancel-all (mirrors the single-question skip). Legacy callbacks are looped per
160
+ question: an empty answer is a skip, a timeout (``None`` or the sentinel) means the user
161
+ walked away so the loop aborts instead of pestering them; earlier answers are kept."""
162
+ answers: dict = {}
163
+ timed_out = False
164
+ if _accepts_kwarg(callback, "questions"):
165
+ raw = callback(question, None, questions=normalized)
166
+ timed_out = _is_timeout(raw)
167
+ if isinstance(raw, str):
168
+ raw = _json_as(raw, dict) # the sentinel is not JSON -> None, timed_out stays True
169
+ if isinstance(raw, dict):
170
+ answers = dict(raw.get("answers") or {})
171
+ timed_out = bool(raw.get("timed_out"))
172
+ return _batch_result(normalized, answers, timed_out)
173
+ for entry in normalized:
174
+ raw = _invoke_callback(callback, entry["question"], entry["choices"], entry["multi_select"])
175
+ if _is_timeout(raw):
176
+ timed_out = True
177
+ break
178
+ answers[entry["qid"]] = raw
179
+ return _batch_result(normalized, answers, timed_out)
180
+
181
+
182
+ def clarify_tool(question: str, choices: Optional[List[str]] = None, multi_select: bool = False,
183
+ questions: Optional[List[dict]] = None, callback: Optional[Callable] = None) -> str:
184
+ """Ask one question (``question``/``choices``/``multi_select``) or a batch (``questions``
185
+ wins when non-empty). ``callback(question, choices, multi_select=False) -> str`` is
186
+ platform injected (batch-capable ones also take ``questions=``). Returns result JSON.
187
+
188
+ Args: question: The question text to present. choices: Up to 4 predefined answer choices. When
189
+ omitted the question is purely open-ended. multi_select: When True, the user can select multiple choices
190
+ (checkboxes). The ``user_response`` in the output JSON will be a list of strings instead of a single
191
+ string. Has no effect when ``choices`` is omitted. questions: Up to 5 independent questions asked as
192
+ one batch (issue #18450). When present (non-empty), the single ``question``/``choices``/``multi_select``
193
+ parameters are ignored and the result JSON is ``{"responses": [...]}`` (plus ``"timed_out": true`` when
194
+ the user stopped answering partway). callback: Platform-provided function that handles the actual UI
195
+ interaction. Batch-capable platforms additionally accept a ``questions`` keyword and receive the
196
+ normalized list in one call; platforms without it are looped one question at a time. Injected by the
197
+ agent runner (cli.py / gateway).
198
+ """
199
+ if questions is not None:
200
+ normalized, error = _normalize_questions(questions)
201
+ if error:
202
+ return tool_error(error)
203
+ if normalized:
204
+ if callback is None:
205
+ return tool_error(_UNAVAILABLE)
206
+ try:
207
+ return _run_batch(normalized, callback, str(question or "").strip())
208
+ except Exception as exc:
209
+ return tool_error(f"Failed to get user input: {exc}")
210
+ # Empty questions array → fall through to the single-question path.
211
+ if not question or not question.strip():
212
+ return tool_error("No question provided. Pass questions=[{question: '...', "
213
+ "choices?: [...], multi_select?: bool}, ...] — a single question "
214
+ "is a one-entry array.")
215
+ question = question.strip()
216
+ if choices is not None:
217
+ if not isinstance(choices, list):
218
+ return tool_error("choices must be a list of strings.")
219
+ choices = _clean_choices(choices)
220
+ if callback is None:
221
+ return tool_error(_UNAVAILABLE)
222
+ # The bare list goes back to the agent; the "(Recommended)" label is presentation only.
223
+ shown = mark_recommended(choices) if choices is not None else None
224
+ try:
225
+ raw_response = _invoke_callback(callback, question, shown, multi_select)
226
+ except Exception as exc:
227
+ return tool_error(f"Failed to get user input: {exc}")
228
+ return json.dumps({"question": question, "choices_offered": choices,
229
+ "user_response": _clean_answer(raw_response, multi_select and choices is not None)},
230
+ ensure_ascii=False)
231
+
232
+
233
+ def check_clarify_requirements() -> bool:
234
+ """Clarify tool has no external requirements -- always available."""
235
+ return True
236
+
237
+
238
+ CLARIFY_SCHEMA = {
239
+ "name": "clarify",
240
+ "description": (
241
+ "Ask the user one or more questions when you need a decision, "
242
+ "clarification, or feedback before proceeding. Pass every question "
243
+ f"in `questions` (1-{MAX_QUESTIONS} entries) — a single question is a "
244
+ "one-entry array, and several INDEPENDENT questions belong in ONE "
245
+ "call (one form beats a chain of clarify calls; if one answer would "
246
+ "change another question, ask separately). Per question: "
247
+ f"single-select (up to {MAX_CHOICES} choices — put your recommended "
248
+ "option FIRST, the UI marks it '(Recommended)' and auto-appends an "
249
+ "'Other' free-text row), multi-select (multi_select=true), or "
250
+ "open-ended (omit choices). Options go ONLY in `choices`, never "
251
+ "enumerated inside the question text (choices render as pickable "
252
+ "rows; options written into the question are dead prose the user "
253
+ "can't click). Result: {responses: [...]} in question order (plus "
254
+ "timed_out=true if the user stopped part-way). Prefer deciding "
255
+ "low-stakes questions yourself; don't use this for dangerous-command "
256
+ "confirmation (the terminal tool handles that)."
257
+ ),
258
+ "parameters": {
259
+ "type": "object",
260
+ "properties": {
261
+ "questions": {
262
+ "type": "array",
263
+ "minItems": 1,
264
+ "maxItems": MAX_QUESTIONS,
265
+ "description": (
266
+ "The question(s). Each: question text (options excluded), "
267
+ "optional choices (recommended first; omit for free-text), "
268
+ "optional multi_select. Responses come back in question "
269
+ "order with the question text echoed."
270
+ ),
271
+ "items": {
272
+ "type": "object",
273
+ "properties": {
274
+ "question": {"type": "string"},
275
+ "choices": {
276
+ "type": "array",
277
+ "items": {"type": "string"},
278
+ "maxItems": MAX_CHOICES,
279
+ },
280
+ "multi_select": {"type": "boolean"},
281
+ },
282
+ "required": ["question"],
283
+ },
284
+ },
285
+ # NOTE: the handler also accepts (unadvertised): a per-question
286
+ # `id` (echoed in the matching response — redundant since rows
287
+ # carry the question text and preserve order), and the legacy
288
+ # single-question shape (`question` + `choices` + `multi_select`
289
+ # at top level; a top-level `question` beside `questions` is the
290
+ # batch form's title). One documented way to call.
291
+ },
292
+ "required": ["questions"],
293
+ },
294
+ }
295
+
296
+ # --- Registry ---
297
+ from tools.registry import registry, tool_error
298
+
299
+ registry.register(
300
+ name="clarify",
301
+ toolset="clarify",
302
+ schema=CLARIFY_SCHEMA,
303
+ handler=lambda args, **kw: clarify_tool(
304
+ question=args.get("question", ""),
305
+ choices=args.get("choices"),
306
+ multi_select=args.get("multi_select", False),
307
+ questions=args.get("questions"),
308
+ callback=kw.get("callback")),
309
+ check_fn=check_clarify_requirements,
310
+ emoji="❓",
311
+ )
tools/close_preview_tool.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Close the Hermes desktop GUI's preview pane, or one tab (``preview.close``).
2
+ Registration lives in `desktop_preview`. The renderer drops the matching tab — or
3
+ the whole pane when no url is given — only for the window that asked."""
4
+
5
+ from tools import desktop_ui
6
+ from tools.open_preview_tool import _normalize_target
7
+
8
+
9
+ def close_preview_tool(url: str = "") -> str:
10
+ """Ask the desktop GUI to close the preview pane, or the tab for ``url``."""
11
+ target = _normalize_target(url or "")
12
+ return desktop_ui.emit_or_error(
13
+ "preview.close", {"url": target}, "Failed to close the preview pane: ",
14
+ "The preview pane is only available in the Hermes desktop app.", {"success": True, "url": target},
15
+ )
16
+
17
+
18
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
19
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
20
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
21
+ # The whole block is removed by reverting the commit that added it.
22
+ import json # noqa: F401,E402
23
+
24
+ CLOSE_PREVIEW_SCHEMA = {
25
+ "name": "close_preview",
26
+ "description": (
27
+ "Close the preview pane beside the chat in the Hermes desktop app, or one "
28
+ "tab inside it. Use this when the user asks to close, hide, or dismiss the "
29
+ "preview — e.g. \"close the preview pane\", \"close cnn.com\", \"hide the "
30
+ "preview\". Omit url to close the whole pane (every tab). Pass a web URL, "
31
+ "localhost address, or file path to close only that tab. Counterpart of "
32
+ "open_preview."
33
+ ),
34
+ "parameters": {
35
+ "type": "object",
36
+ "properties": {
37
+ "url": {
38
+ "type": "string",
39
+ "description": (
40
+ "Optional. The tab to close: a web URL (https://… or a bare "
41
+ "domain), a localhost URL, or a file path. Omit to close the "
42
+ "whole preview pane."
43
+ ),
44
+ },
45
+ },
46
+ },
47
+ }
48
+
49
+
50
+ _PLUGIN_COMPAT_LAZY = {
51
+ 'registry': ('tools.registry', 'registry'),
52
+ 'tool_error': ('tools.registry', 'tool_error'),
53
+ }
54
+
55
+
56
+ def __getattr__(name): # PEP 562 — lazy so no import cycles
57
+ target = _PLUGIN_COMPAT_LAZY.get(name)
58
+ if target is None:
59
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
60
+ import importlib
61
+ from hermes_cli.plugin_compat import warn_once
62
+ warn_once(__name__, name, *target)
63
+ return getattr(importlib.import_module(target[0]), target[1])
64
+ # ---- END PLUGIN-COMPAT ----
tools/code_execution_rpc.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Host-side RPC servers for execute_code sandboxes.
2
+
3
+ Two transports share one request pipeline (token check → allow-list → call
4
+ budget → dispatch under output silence → log): ``_rpc_server_loop`` serves the
5
+ local UDS/TCP socket, ``_rpc_poll_loop`` polls a remote filesystem for request
6
+ files via ``env.execute()``.
7
+ """
8
+
9
+ import base64
10
+ import json
11
+ import logging
12
+ import secrets
13
+ import shlex
14
+ import socket
15
+ import threading
16
+ import time
17
+
18
+ from agent.thread_scoped_output import thread_scoped_silence
19
+ from tools.registry import tool_error
20
+
21
+ # Logger name kept as the origin module's so existing log expectations hold.
22
+ logger = logging.getLogger("tools.code_execution_tool")
23
+
24
+ # Terminal parameters that must not be used from ephemeral sandbox scripts.
25
+ _TERMINAL_BLOCKED_PARAMS = {"background", "pty", "notify", "notify_on_complete", "watch_patterns"}
26
+
27
+
28
+ def _default_dispatch(task_id):
29
+ from model_tools import handle_function_call
30
+ return lambda tool_name, tool_args: handle_function_call(tool_name, tool_args, task_id=task_id)
31
+
32
+
33
+ def _rpc_token_ok(request: dict, rpc_token: str) -> bool:
34
+ """Constant-time token check; an empty server token fails closed. Compared as bytes:
35
+ compare_digest raises TypeError on a non-ASCII str, and the token is script-supplied JSON."""
36
+ return bool(rpc_token) and secrets.compare_digest(
37
+ str(request.get("token") or "").encode(), rpc_token.encode()
38
+ )
39
+
40
+
41
+ def _handle_rpc_request(request: dict, *, allowed_tools: frozenset, tool_call_counter: list,
42
+ max_tool_calls: int, dispatch, tool_call_log: list, call_start: float,
43
+ where: str) -> str:
44
+ """Enforce allow-list + budget, then dispatch one authenticated request. Only a dispatched
45
+ call consumes budget and is logged; refusals are free."""
46
+ tool_name = request.get("tool", "")
47
+ tool_args = request.get("args", {})
48
+ if tool_name not in allowed_tools:
49
+ return tool_error(f"Tool '{tool_name}' is not available in execute_code. "
50
+ f"Available: {', '.join(sorted(allowed_tools))}")
51
+ if tool_call_counter[0] >= max_tool_calls:
52
+ return tool_error(f"Tool call limit reached ({max_tool_calls}). "
53
+ "No more tool calls allowed in this execution.")
54
+ if tool_name == "terminal" and isinstance(tool_args, dict):
55
+ for param in _TERMINAL_BLOCKED_PARAMS:
56
+ tool_args.pop(param, None)
57
+ # Silence handler status prints so they don't leak into the CLI spinner.
58
+ try:
59
+ with thread_scoped_silence():
60
+ result = dispatch(tool_name, tool_args)
61
+ except Exception as exc:
62
+ logger.error("Tool call failed in %s: %s", where, exc, exc_info=True)
63
+ result = tool_error(str(exc))
64
+ tool_call_counter[0] += 1
65
+ tool_call_log.append({"tool": tool_name, "args_preview": str(tool_args)[:80],
66
+ "duration": round(time.monotonic() - call_start, 2)})
67
+ return result
68
+
69
+
70
+ def _rpc_server_loop(server_sock: socket.socket, task_id: str, tool_call_log: list,
71
+ tool_call_counter: list, max_tool_calls: int, allowed_tools: frozenset,
72
+ stop_event: threading.Event, rpc_token: str, dispatch=None):
73
+ """Accept one client and serve newline-delimited JSON requests until it disconnects, idles
74
+ 300s, or the call limit is reached. ``tool_call_counter`` is a mutable ``[int]``. ``dispatch``
75
+ overrides how an allowed, budgeted call runs: per-call sandboxes use the default (the thread
76
+ carries the cell's context); session kernels rebind each call to the CURRENT cell's authority.
77
+ """
78
+ if dispatch is None:
79
+ dispatch = _default_dispatch(task_id)
80
+ conn = None
81
+ try:
82
+ server_sock.settimeout(0.05)
83
+ while not stop_event.is_set():
84
+ try:
85
+ conn, _ = server_sock.accept()
86
+ break
87
+ except socket.timeout:
88
+ continue
89
+ if conn is None:
90
+ return
91
+ conn.settimeout(300)
92
+ buf = b""
93
+ while True:
94
+ try:
95
+ chunk = conn.recv(65536)
96
+ except socket.timeout:
97
+ break
98
+ if not chunk:
99
+ break
100
+ buf += chunk
101
+ while b"\n" in buf:
102
+ line, buf = buf.split(b"\n", 1)
103
+ line = line.strip()
104
+ if not line:
105
+ continue
106
+ call_start = time.monotonic()
107
+ try:
108
+ request = json.loads(line.decode())
109
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
110
+ resp = tool_error(f"Invalid RPC request: {exc}")
111
+ else:
112
+ resp = _handle_rpc_request(
113
+ request, allowed_tools=allowed_tools, tool_call_counter=tool_call_counter,
114
+ max_tool_calls=max_tool_calls, dispatch=dispatch, tool_call_log=tool_call_log,
115
+ call_start=call_start, where="sandbox",
116
+ ) if _rpc_token_ok(request, rpc_token) else tool_error("Unauthorized RPC request")
117
+ conn.sendall((resp + "\n").encode())
118
+ except socket.timeout:
119
+ logger.debug("RPC listener socket timeout")
120
+ except OSError as e:
121
+ logger.debug("RPC listener socket error: %s", e, exc_info=True)
122
+ finally:
123
+ if conn:
124
+ try:
125
+ conn.close()
126
+ except OSError as e:
127
+ logger.debug("RPC conn close error: %s", e)
128
+
129
+
130
+ def _rpc_poll_loop(env, rpc_dir: str, task_id: str, tool_call_log: list, tool_call_counter: list,
131
+ max_tool_calls: int, allowed_tools: frozenset, stop_event: threading.Event,
132
+ rpc_token: str):
133
+ """Poll the remote filesystem for request files and answer them. Background thread; each
134
+ ``env.execute()`` is an independent process, so this is safe alongside the script-execution
135
+ thread. Malformed or unauthorized requests are removed without a response."""
136
+ dispatch = _default_dispatch(task_id)
137
+ poll_interval = 0.1
138
+ quoted_rpc_dir = shlex.quote(rpc_dir)
139
+ while not stop_event.is_set():
140
+ try:
141
+ ls_result = env.execute(f"ls -1 {quoted_rpc_dir}/req_* 2>/dev/null || true", cwd="/", timeout=10)
142
+ output = ls_result.get("output", "").strip()
143
+ if not output:
144
+ stop_event.wait(poll_interval)
145
+ continue
146
+ req_files = sorted(f for f in (line.strip() for line in output.split("\n"))
147
+ if f and not f.endswith(".tmp") and "/req_" in f)
148
+ for req_file in req_files:
149
+ if stop_event.is_set():
150
+ break
151
+ call_start = time.monotonic()
152
+ quoted_req_file = shlex.quote(req_file)
153
+ read_result = env.execute(f"cat {quoted_req_file}", cwd="/", timeout=10)
154
+ try:
155
+ request = json.loads(read_result.get("output", ""))
156
+ except (json.JSONDecodeError, ValueError):
157
+ logger.debug("Malformed RPC request in %s", req_file)
158
+ env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5)
159
+ continue
160
+ if not _rpc_token_ok(request, rpc_token):
161
+ logger.debug("Unauthorized RPC request in %s", req_file)
162
+ env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5)
163
+ continue
164
+ tool_result = _handle_rpc_request(
165
+ request, allowed_tools=allowed_tools, tool_call_counter=tool_call_counter,
166
+ max_tool_calls=max_tool_calls, dispatch=dispatch, tool_call_log=tool_call_log,
167
+ call_start=call_start, where="remote sandbox",
168
+ )
169
+ # Write the response atomically (tmp + rename) via echo piping —
170
+ # Modal doesn't reliably deliver stdin_data to chained commands.
171
+ quoted_res_file = shlex.quote(f"{rpc_dir}/res_{request.get('seq', 0):06d}")
172
+ encoded_result = base64.b64encode(tool_result.encode("utf-8")).decode("ascii")
173
+ env.execute(
174
+ f"echo '{encoded_result}' | base64 -d > {quoted_res_file}.tmp"
175
+ f" && mv {quoted_res_file}.tmp {quoted_res_file}",
176
+ cwd="/", timeout=60,
177
+ )
178
+ env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5)
179
+ except Exception as e:
180
+ if not stop_event.is_set():
181
+ logger.debug("RPC poll error: %s", e, exc_info=True)
182
+ if not stop_event.is_set():
183
+ stop_event.wait(poll_interval)
tools/cronjob_job_args.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cron job argument normalization, validation and result shaping (re-exported by
2
+ tools/cronjob_tools.py)."""
3
+
4
+ import logging
5
+ from typing import Any, Dict, List, Optional, Union
6
+
7
+ from cron.jobs import effective_job_state
8
+
9
+ # Logger parity with the origin module.
10
+ logger = logging.getLogger("tools.cronjob_tools")
11
+
12
+
13
+ def _origin_from_env() -> Optional[Dict[str, str]]:
14
+ from gateway.session_context import get_session_env
15
+ origin_platform = get_session_env("HERMES_SESSION_PLATFORM")
16
+ origin_chat_id = get_session_env("HERMES_SESSION_CHAT_ID")
17
+ if not (origin_platform and origin_chat_id):
18
+ return None
19
+ thread_id = get_session_env("HERMES_SESSION_THREAD_ID") or None
20
+ # Slack stamps every TOP-LEVEL message's own id as the session thread (a per-message
21
+ # KEY, not a location); persisting it would pin all future deliveries inside an
22
+ # ephemeral thread, so thread == creating message id is synthetic and dropped.
23
+ if thread_id and origin_platform == "slack":
24
+ message_id = get_session_env("HERMES_SESSION_MESSAGE_ID") or None
25
+ if message_id and str(thread_id) == str(message_id):
26
+ logger.debug(
27
+ "Cron origin: dropping synthetic per-message Slack "
28
+ "thread_id=%s (== creation message id)", thread_id)
29
+ thread_id = None
30
+ if thread_id:
31
+ logger.debug(
32
+ "Cron origin captured thread_id=%s for %s:%s",
33
+ thread_id, origin_platform, origin_chat_id)
34
+ return {
35
+ "platform": origin_platform, "chat_id": origin_chat_id,
36
+ "chat_name": get_session_env("HERMES_SESSION_CHAT_NAME") or None, "thread_id": thread_id,
37
+ # Lets a delivery mirror resolve the participant's session in per-user-isolated groups.
38
+ "user_id": get_session_env("HERMES_SESSION_USER_ID") or None,
39
+ # Workspace/server scope (Slack team, Discord guild...): Slack session keys embed it,
40
+ # so a continuable cron seed built without it would never resolve a scoped reply.
41
+ "scope_id": get_session_env("HERMES_SESSION_SCOPE_ID") or None,
42
+ }
43
+
44
+
45
+ def _local_delivery_notice(job: Dict[str, Any], user_deliver: Optional[str]) -> Optional[str]:
46
+ """Notice when a created job won't deliver anywhere: CLI/TUI sessions have no capturable
47
+ origin, so deliver='origin' (or omitted) saves output but never delivers it. None when the
48
+ user explicitly asked for ``local`` or the job resolves to a real target.
49
+
50
+ TUI/CLI sessions cannot be captured as a cron ``origin`` (no ``HERMES_SESSION_PLATFORM``/``CHAT_ID`` is
51
+ set for them), so a ``deliver="origin"`` request — or an omitted ``deliver`` that defaults to
52
+ origin-or-local — produces a job that runs and saves output to ``last_output`` but is never delivered
53
+ back into the session. This is by design (there is no live-delivery channel for local sessions), but
54
+ silently dropping the user's "tell me when it runs" intent is the trap reported in 51568. Surface it at
55
+ create time so the agent can relay it instead of promising a delivery that never happens. See #51568.
56
+ """
57
+ if (user_deliver or "").strip().lower() == "local":
58
+ return None
59
+ try:
60
+ from cron.scheduler import _resolve_delivery_targets
61
+ if _resolve_delivery_targets(job):
62
+ return None
63
+ except Exception: # resolution unavailable — fall back to the origin signal
64
+ if job.get("origin"):
65
+ return None
66
+ return (
67
+ "This is a local-only cron job: its output is saved (view it with "
68
+ "cronjob(action='list')) but will NOT be delivered back into this "
69
+ "session — CLI/TUI sessions have no live-delivery channel. To be "
70
+ "notified when it runs, recreate or update the job with deliver set to "
71
+ "a gateway-connected platform, e.g. deliver='telegram' or deliver='all'.")
72
+
73
+
74
+ def _mode_guidance_notes(job: Dict[str, Any], user_deliver: Optional[str]) -> List[str]:
75
+ """Mode guidance echoed once in the create/update response (not in the schema, which is
76
+ paid for on every API call)."""
77
+ notes: List[str] = []
78
+ if job.get("monitor_script") or job.get("monitor_url"):
79
+ notes.append(
80
+ "Monitor mode: the source runs first each tick and its output is "
81
+ "hashed as exact bytes — unchanged output suppresses the agent run "
82
+ "(silent no_change tick), changed output injects a MONITOR CHANGE "
83
+ "DETECTED diff into the prompt. The first tick always runs as "
84
+ "baseline. The source must emit STABLE output (no timestamps, no "
85
+ "random ordering) or every tick will look changed.")
86
+ if job.get("no_agent"):
87
+ notes.append(
88
+ "no_agent mode: stdout is delivered verbatim; EMPTY stdout sends "
89
+ "nothing at all (watchdog pattern — script should stay quiet when "
90
+ "there is nothing to report). Non-zero exit or timeout sends an "
91
+ "error alert. prompt/skills are ignored.")
92
+ _deliver = (user_deliver or "").strip().lower()
93
+ if _deliver:
94
+ if "all" in _deliver.split(","):
95
+ notes.append(
96
+ "deliver='all' resolves at fire time and never includes "
97
+ "bot-chat targets — channels connected later are picked up "
98
+ "automatically.")
99
+ if _deliver.startswith("bot-chat:"):
100
+ notes.append("Targeting another profile's Bot Chat costs that bot an agent turn per run.")
101
+ # platform:chat_id with no thread segment loses topic targeting.
102
+ for target in _deliver.split(","):
103
+ parts = target.strip().split(":")
104
+ if (
105
+ len(parts) == 2
106
+ and parts[0] not in ("bot-chat", "sms")
107
+ and parts[1]
108
+ and not parts[1].startswith("#")):
109
+ notes.append(
110
+ f"deliver target '{target.strip()}' has no :thread_id "
111
+ "segment — on thread/topic platforms the delivery lands in "
112
+ "the main chat, not a topic.")
113
+ break
114
+ return notes
115
+
116
+
117
+ def _split_monitor_arg(
118
+ monitor: Optional[str],
119
+ monitor_script: Optional[str],
120
+ monitor_url: Optional[str]) -> tuple:
121
+ """Resolve the model-facing ``monitor`` field into the stored ``(monitor_script,
122
+ monitor_url)`` pair. http(s):// is a URL, anything else a script path (a legal script path
123
+ never starts with a URL scheme). None = unchanged, '' = clear; setting one source clears
124
+ the other so switching transports never trips mutual exclusion; an explicit ``monitor``
125
+ wins over the legacy alias fields."""
126
+ if monitor is None:
127
+ return monitor_script, monitor_url
128
+ value = monitor.strip()
129
+ if not value:
130
+ return "", ""
131
+ if value.lower().startswith(("http://", "https://")):
132
+ return "", value
133
+ return value, ""
134
+
135
+
136
+ def _repeat_display(job: Dict[str, Any]) -> str:
137
+ rep = job.get("repeat") or {}
138
+ times, completed = rep.get("times"), rep.get("completed", 0)
139
+ if times is None:
140
+ return "forever"
141
+ if times == 1:
142
+ return "once" if completed == 0 else "1/1"
143
+ return f"{completed}/{times}" if completed else f"{times} times"
144
+
145
+
146
+ def _clean_str_list(items: Any) -> List[str]:
147
+ """Stripped, non-empty ``str(item)`` values from a str-or-iterable (order kept)."""
148
+ if items is None:
149
+ return []
150
+ if isinstance(items, str):
151
+ items = [items]
152
+ return [s for s in (str(i).strip() for i in items) if s]
153
+
154
+
155
+ def _canonical_skills(skill: Optional[str] = None, skills: Optional[Any] = None) -> List[str]:
156
+ if skills is None:
157
+ skills = [skill] if skill else []
158
+ elif isinstance(skills, str):
159
+ skills = [skills]
160
+ # `item or ""`: a None entry must drop out, not stringify to "None".
161
+ return list(dict.fromkeys(_clean_str_list(item or "" for item in skills)))
162
+
163
+
164
+ def _normalize_optional_job_value(value: Optional[Any], *, strip_trailing_slash: bool = False) -> Optional[str]:
165
+ if value is None:
166
+ return None
167
+ text = str(value).strip()
168
+ if strip_trailing_slash:
169
+ text = text.rstrip("/")
170
+ return text or None
171
+
172
+
173
+ def _normalize_deliver_param(value: Any) -> Optional[str]:
174
+ """Canonical string form of ``deliver``; None for None/empty. MCP clients may pass a list
175
+ (``["telegram"]``) which the scheduler's ``str(deliver).split(",")`` would mangle."""
176
+ if value is None:
177
+ return None
178
+ if isinstance(value, (list, tuple)):
179
+ return ",".join(_clean_str_list(value)) or None
180
+ return str(value).strip() or None
181
+
182
+
183
+ def _validate_bot_chat_deliver(deliver: Optional[str]) -> Optional[str]:
184
+ """Validate ``bot-chat[:<profile>]`` deliver elements at create time: Bot Chat delivery is
185
+ machine-local, so the profile must exist where the scheduler fires (Desktop rosters may
186
+ show same-named profiles from other machines). Returns an error string or None."""
187
+ if not deliver:
188
+ return None
189
+ try:
190
+ from cron.scheduler_delivery import parse_bot_chat_deliver_token
191
+ from hermes_cli.profiles import normalize_profile_name, profile_exists
192
+ except Exception:
193
+ return None # best-effort; resolution re-checks at fire time
194
+ for part in str(deliver).split(","):
195
+ profile_arg = parse_bot_chat_deliver_token(part.strip())
196
+ if not profile_arg:
197
+ continue # not a bot-chat token, or bare token (own profile)
198
+ try:
199
+ canon = normalize_profile_name(profile_arg)
200
+ except Exception:
201
+ return f"invalid bot-chat profile name '{profile_arg}'"
202
+ if not profile_exists(canon):
203
+ return (
204
+ f"bot-chat delivery profile '{profile_arg}' not found on this "
205
+ "gateway's machine. Bot Chat delivery is machine-local — use a "
206
+ "profile that exists here (hermes profile list), or omit the "
207
+ "name (deliver='bot-chat') for the job's own profile.")
208
+ return None
209
+
210
+
211
+ def _resolve_cron_context_deliver(deliver: Optional[str]) -> Optional[str]:
212
+ """Resolve ``origin`` to a concrete target for creates made FROM a cron run (the creating
213
+ session is ephemeral, so by fire time there is no origin). Non-cron sessions: unchanged.
214
+ Cron sessions: ``origin`` (or omitted) becomes the creating run's ``platform:chat_id[:thread]``
215
+ from HERMES_CRON_AUTO_DELIVER_*, or ``local`` when it has no concrete target; other
216
+ elements pass through. Otherwise the scheduler would guess a home channel."""
217
+ from gateway.session_context import get_session_env
218
+ from utils import is_truthy_value
219
+ if not is_truthy_value(get_session_env("HERMES_CRON_SESSION", "")):
220
+ return deliver
221
+
222
+ def _creator_target() -> str:
223
+ platform = get_session_env("HERMES_CRON_AUTO_DELIVER_PLATFORM", "").strip()
224
+ chat_id = get_session_env("HERMES_CRON_AUTO_DELIVER_CHAT_ID", "").strip()
225
+ if not platform or not chat_id:
226
+ return "local"
227
+ thread_id = get_session_env("HERMES_CRON_AUTO_DELIVER_THREAD_ID", "").strip()
228
+ return f"{platform}:{chat_id}:{thread_id}" if thread_id else f"{platform}:{chat_id}"
229
+
230
+ if deliver is None:
231
+ return _creator_target()
232
+ resolved = [_creator_target() if p.lower() == "origin" else p for p in _clean_str_list(str(deliver).split(","))]
233
+ # Order-preserving de-dup: 'origin,local' with a local creator -> 'local'.
234
+ return ",".join(dict.fromkeys(resolved)) or None
235
+
236
+
237
+ def _validate_cron_base_url(
238
+ provider: Optional[Any], base_url: Optional[Any]) -> Optional[str]:
239
+ """Reject pairing a named provider's stored credential with an off-host base_url (a
240
+ prompt-injected job could exfil the key). Allowed: no override; bare 'custom' (pure BYOK,
241
+ key derived from the base_url); an override whose host matches the named provider's own
242
+ endpoint. Everything else fails closed. Returns an error string if blocked, else None."""
243
+ bu = _normalize_optional_job_value(base_url, strip_trailing_slash=True)
244
+ if not bu:
245
+ return None
246
+ prov = _normalize_optional_job_value(provider)
247
+ if not prov: # no provider inherits the default provider's stored key — same primitive
248
+ return (
249
+ "base_url override requires an explicit provider. Set provider to a "
250
+ "configured custom provider to use a custom endpoint.")
251
+ try:
252
+ from hermes_cli.runtime_provider import (
253
+ has_named_custom_provider,
254
+ resolve_requested_provider,
255
+ _get_named_custom_provider)
256
+ from hermes_cli.auth import PROVIDER_REGISTRY
257
+ from utils import base_url_host_matches, base_url_hostname
258
+ except Exception:
259
+ return f"Unable to validate base_url override for provider {prov!r}; refused."
260
+
261
+ if prov.lower() == "custom": # pure BYOK: key keyed by THIS base_url, never a stored secret
262
+ return None
263
+ if has_named_custom_provider(prov):
264
+ # A NAMED custom provider's STORED key is still sent to an override base_url.
265
+ try:
266
+ cp = _get_named_custom_provider(prov)
267
+ except Exception:
268
+ cp = None
269
+ cfg_host = base_url_hostname((cp or {}).get("base_url", "")) if cp else ""
270
+ if cfg_host and base_url_host_matches(bu, cfg_host):
271
+ return None
272
+ return (
273
+ f"base_url {bu!r} is not allowed for provider {prov!r}. A named "
274
+ f"custom provider's stored credential may only be sent to its own "
275
+ f"configured endpoint ({cfg_host or 'unknown'}).")
276
+ try:
277
+ resolved = resolve_requested_provider(prov)
278
+ except Exception:
279
+ resolved = prov
280
+ pconfig = PROVIDER_REGISTRY.get(resolved) if isinstance(resolved, str) else None
281
+ known_host = base_url_hostname(getattr(pconfig, "inference_base_url", "") if pconfig else "")
282
+ if known_host and base_url_host_matches(bu, known_host):
283
+ return None
284
+ # Fail closed: named providers with stored credentials AND unknown names we cannot host-match.
285
+ return (
286
+ f"base_url {bu!r} is not allowed for provider {prov!r}. A named "
287
+ f"provider's stored credential may only be sent to its own endpoint; "
288
+ f'use a configured custom provider (provider="custom") for a custom base_url.')
289
+
290
+
291
+ def _validate_cron_script_path(script: Optional[str]) -> Optional[str]:
292
+ """Scripts must be relative paths within HERMES_HOME/scripts/ (absolute / ~ / drive-letter
293
+ rejected — prompt-injection guard). Error string if blocked, else None; empty = clear."""
294
+ if not script or not script.strip():
295
+ return None
296
+
297
+ from hermes_constants import get_hermes_home
298
+ raw = script.strip()
299
+ if raw.startswith(("/", "~")) or (len(raw) >= 2 and raw[1] == ":"):
300
+ return (
301
+ f"Script path must be relative to ~/.hermes/scripts/. "
302
+ f"Got absolute or home-relative path: {raw!r}. "
303
+ f"Place scripts in ~/.hermes/scripts/ and use just the filename.")
304
+
305
+ from tools.path_security import validate_within_dir
306
+ scripts_dir = get_hermes_home() / "scripts"
307
+ scripts_dir.mkdir(parents=True, exist_ok=True)
308
+ if validate_within_dir(scripts_dir / raw, scripts_dir):
309
+ return f"Script path escapes the scripts directory via traversal: {raw!r}"
310
+ return None
311
+
312
+
313
+ def _apply_continuity(
314
+ context_from: Optional[Union[str, List[str]]],
315
+ continuity: bool) -> Optional[List[str]]:
316
+ """continuity=True ensures "self" is in context_from; False removes it; others untouched."""
317
+ refs = _clean_str_list(context_from)
318
+ has_self = any(r.lower() == "self" for r in refs)
319
+ if continuity and not has_self:
320
+ refs.append("self")
321
+ elif not continuity and has_self:
322
+ refs = [r for r in refs if r.lower() != "self"]
323
+ return refs or None
324
+
325
+
326
+ def _validate_context_from_refs(refs: List[Any]) -> Optional[str]:
327
+ """Error string if any non-"self" ref names a missing job ("self" resolves to the job's
328
+ own id at run time, so it can't be checked — the job doesn't exist yet at create)."""
329
+ from cron.jobs import get_job as _get_job
330
+ for ref_id in refs:
331
+ if isinstance(ref_id, str) and ref_id.strip().lower() == "self":
332
+ continue
333
+ if not _get_job(ref_id):
334
+ return (
335
+ f"context_from job '{ref_id}' not found. "
336
+ "Use cronjob(action='list') to see available jobs.")
337
+ return None
338
+
339
+
340
+ # Optional fields echoed by _format_job only when truthy (order = JSON key order).
341
+ _FORMAT_JOB_OPTIONAL_KEYS = (
342
+ "script", "reasoning_effort", "monitor_script", "monitor_url",
343
+ "monitor_state", "no_agent", "enabled_toolsets", "workdir")
344
+
345
+
346
+ def _format_job(job: Dict[str, Any]) -> Dict[str, Any]:
347
+ from agent.redact import redact_sensitive_text
348
+
349
+ prompt = str(job.get("prompt") or "")
350
+ skills = _canonical_skills(job.get("skill"), job.get("skills"))
351
+ job_id = str(job.get("id") or "unknown")
352
+ name = str(job.get("name") or prompt[:50] or (skills[0] if skills else "") or job_id or "cron job")
353
+ result = {
354
+ "job_id": job_id,
355
+ "name": name,
356
+ "skill": skills[0] if skills else None,
357
+ "skills": skills,
358
+ "prompt_preview": prompt[:100] + "..." if len(prompt) > 100 else prompt,
359
+ "model": job.get("model"),
360
+ "provider": job.get("provider"),
361
+ "base_url": job.get("base_url"),
362
+ "schedule": job.get("schedule_display") or "?",
363
+ "repeat": _repeat_display(job),
364
+ "deliver": job.get("deliver", "local"),
365
+ "next_run_at": job.get("next_run_at"),
366
+ "last_run_at": job.get("last_run_at"),
367
+ "last_status": job.get("last_status"),
368
+ "last_delivery_error": job.get("last_delivery_error"),
369
+ "last_delivery_unverified": job.get("last_delivery_unverified"),
370
+ "last_fire_error": job.get("last_fire_error"),
371
+ "last_error": redact_sensitive_text(
372
+ job["last_error"], force=True, redact_url_credentials=True,
373
+ ) if job.get("last_error") else job.get("last_error"),
374
+ "enabled": job.get("enabled", True),
375
+ # Derive from enabled so half-paused records never render as paused.
376
+ "state": effective_job_state(job),
377
+ "paused_at": job.get("paused_at"),
378
+ "paused_reason": job.get("paused_reason"),
379
+ }
380
+ for key in _FORMAT_JOB_OPTIONAL_KEYS:
381
+ if job.get(key):
382
+ result[key] = True if key == "no_agent" else job[key]
383
+ stored_refs = job.get("context_from") or []
384
+ if isinstance(stored_refs, str):
385
+ stored_refs = [stored_refs]
386
+ is_self = lambda r: str(r).strip().lower() == "self" or r == job.get("id") # noqa: E731
387
+ if any(is_self(r) for r in stored_refs):
388
+ result["continuity"] = True
389
+ external_refs = [r for r in stored_refs if not is_self(r)]
390
+ if external_refs:
391
+ result["context_from"] = external_refs
392
+ if isinstance(job.get("attach_to_session"), bool):
393
+ result["attach_to_session"] = job["attach_to_session"]
394
+ return result
395
+
396
+
397
+ def _gateway_liveness_notice(plural: bool = False) -> dict:
398
+ """``gateway_running``/``warning`` payload via the shared CLI helper so CLI and tool agree
399
+ on "scheduler active". False -> warning (no gateway process), None -> probe failed.
400
+
401
+ Thin adapter over the shared CLI helper ``hermes_cli.cron._builtin_gateway_liveness`` (#87033) so the
402
+ CLI and this tool can never disagree about what "scheduler active" means. ``plural`` rewords the warning
403
+ for multi-job results (the ``list`` action).
404
+ """
405
+ try:
406
+ from hermes_cli.cron import _builtin_gateway_liveness
407
+ _gw = _builtin_gateway_liveness()
408
+ except Exception:
409
+ return {"gateway_running": None}
410
+ if _gw is False:
411
+ subject = "these jobs are saved" if plural else "this job is saved"
412
+ return {
413
+ "gateway_running": False,
414
+ "warning": (
415
+ f"The Hermes gateway is not running — {subject} "
416
+ "but will NOT fire until the gateway is started "
417
+ "(hermes gateway install / hermes gateway start). "
418
+ "Tell the user the task is scheduled but not active yet."),
419
+ }
420
+ return {"gateway_running": None if _gw is None else True}
tools/daemon_pool.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared daemon-thread ThreadPoolExecutor.
2
+
3
+ Stdlib workers are non-daemon AND registered in ``_threads_queues``, whose atexit
4
+ hook joins every worker even after ``shutdown(wait=False)`` — one wedged worker
5
+ (tool blocked on network I/O, hung provider, stuck subagent) blocks interpreter
6
+ exit forever. This variant spawns daemon workers and skips that registration.
7
+ Use it for best-effort/interruptible work that must never hold the process open;
8
+ NOT for work that must complete before exit (durable writes belong on foreground
9
+ threads with explicit bounded joins).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import threading
15
+ import weakref
16
+ from concurrent.futures import ThreadPoolExecutor
17
+ from concurrent.futures.thread import _worker
18
+ from contextvars import copy_context
19
+
20
+ __all__ = ["DaemonThreadPoolExecutor"]
21
+
22
+
23
+ class DaemonThreadPoolExecutor(ThreadPoolExecutor):
24
+ """ThreadPoolExecutor variant whose workers do not block process exit."""
25
+
26
+ def submit(self, fn, /, *args, **kwargs):
27
+ """Submit a callable, propagating the caller's contextvars. Stdlib only does
28
+ this from 3.14; on 3.11-3.13 a bare worker starts with an EMPTY Context and
29
+ drops profile secret scope / HERMES_HOME override — under the multiplexed
30
+ gateway a credential read then fails closed with ``UnscopedSecretError``.
31
+ Unconditional: on 3.14+ ``ctx.run`` re-applies the same context (no-op)."""
32
+ ctx = copy_context()
33
+
34
+ def _run_with_context(*call_args, **call_kwargs):
35
+ return ctx.run(fn, *call_args, **call_kwargs)
36
+ return super().submit(_run_with_context, *args, **kwargs)
37
+
38
+ def _adjust_thread_count(self) -> None:
39
+ # Mirrors CPython's implementation (3.8–3.13) with two changes:
40
+ # daemon=True and no _threads_queues registration.
41
+ if self._idle_semaphore.acquire(timeout=0):
42
+ return
43
+
44
+ def weakref_cb(_, q=self._work_queue):
45
+ q.put(None)
46
+ num_threads = len(self._threads)
47
+ if num_threads < self._max_workers:
48
+ thread_name = "%s_%d" % (self._thread_name_prefix or self, num_threads)
49
+ # Carry the active profile into the review thread so MEMORY.md / skill review writes land in the
50
+ # right profile (#54937).
51
+ t = threading.Thread(
52
+ name=thread_name, target=_worker, daemon=True,
53
+ args=(weakref.ref(self, weakref_cb), self._work_queue, self._initializer, self._initargs),
54
+ )
55
+ t.start()
56
+ self._threads.add(t)
tools/delegate_tool_progress.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Child progress relay, console formatting and child system-prompt construction for delegate_task."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import enum
7
+ import os
8
+ import threading
9
+ from contextlib import contextmanager
10
+ from typing import Any, Dict, List, Optional
11
+ from tools.delegate_tool_registry import _active_subagents, _active_subagents_lock
12
+
13
+ logger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module
14
+
15
+ # Terminal child statuses that mean "the subagent did NOT deliver a usable result". Shared by the CLI spinner echo,
16
+ # the gateway failure notice, and the parent-facing failure summary so every surface agrees.
17
+ SUBAGENT_FAILURE_STATUSES = frozenset({"failed", "error", "timeout"})
18
+
19
+ @contextmanager
20
+ def _quiet(log_message: Optional[str], *log_args: Any, exc_info: bool = False):
21
+ """Best-effort block: any Exception is swallowed (never reaches the run) and, when ``log_message`` is given,
22
+ logged at debug — the exception fills a trailing unsatisfied ``%s``."""
23
+ try:
24
+ yield
25
+ except Exception as exc:
26
+ if log_message is None:
27
+ return
28
+ if log_message.count("%") > len(log_args):
29
+ log_args = log_args + (exc,)
30
+ logger.debug(log_message, *log_args, exc_info=exc_info)
31
+
32
+ def _safe_progress(cb: Any, event_type: Any, *args: Any, **kwargs: Any) -> None:
33
+ """Invoke a child progress callback; relay failures never reach the run."""
34
+ if cb:
35
+ with _quiet("Progress callback %s failed: %s", event_type):
36
+ cb(event_type, *args, **kwargs)
37
+
38
+ def _clean_error_text(error: Any, max_chars: int = 200) -> str:
39
+ """Reduce an error payload (traceback / JSON wall) to one clean line: the exception message (last line of a
40
+ traceback) or the first non-empty line, hard-capped in length."""
41
+ lines = [ln.strip() for ln in str(error or "").strip().splitlines() if ln.strip()]
42
+ if not lines:
43
+ return ""
44
+ line = lines[-1] if lines[0].startswith("Traceback") else lines[0]
45
+ return line[: max_chars - 3] + "..." if len(line) > max_chars else line
46
+
47
+ def format_subagent_failure_line(
48
+ goal: Optional[str], status: Optional[str], error: Any = None, duration_seconds: Any = None,
49
+ ) -> str:
50
+ """One clean, human-readable line describing a failed subagent, rendered
51
+ directly to the user (CLI spinner echo, gateway platform notice), e.g.
52
+ ``⚠️ Subagent failed — "research competitor pricing": Error code: 404 (after 12s)``."""
53
+ goal_label = (goal or "").strip().replace("\n", " ")
54
+ if len(goal_label) > 60:
55
+ goal_label = goal_label[:57] + "..."
56
+ line = f"⚠️ Subagent {'timed out' if status == 'timeout' else 'failed'}"
57
+ if goal_label:
58
+ line += f' — "{goal_label}"'
59
+ err = _clean_error_text(error)
60
+ if err:
61
+ line += f": {err}"
62
+ if isinstance(duration_seconds, (int, float)) and duration_seconds > 0:
63
+ line += f" (after {round(duration_seconds)}s)"
64
+ return line
65
+
66
+
67
+ class DelegateEvent(str, enum.Enum):
68
+ """Formal delegation progress event types. The relay normalises incoming legacy strings (``tool.started``,
69
+ ``_thinking``, …) to these via ``_LEGACY_EVENT_MAP``; external consumers (gateway SSE, ACP adapter, CLI) still
70
+ receive the legacy strings during the deprecation window. TASK_SPAWNED / TASK_COMPLETED / TASK_FAILED are
71
+ reserved for future orchestrator lifecycle events, not emitted yet."""
72
+
73
+ TASK_SPAWNED = "delegate.task_spawned"
74
+ TASK_PROGRESS = "delegate.task_progress"
75
+ TASK_COMPLETED = "delegate.task_completed"
76
+ TASK_FAILED = "delegate.task_failed"
77
+ TASK_THINKING = "delegate.task_thinking"
78
+ TASK_TOOL_STARTED = "delegate.tool_started"
79
+ TASK_TOOL_COMPLETED = "delegate.tool_completed"
80
+
81
+ # Legacy child-agent event strings → DelegateEvent.
82
+ _LEGACY_EVENT_MAP: Dict[str, DelegateEvent] = {
83
+ "_thinking": DelegateEvent.TASK_THINKING,
84
+ "reasoning.available": DelegateEvent.TASK_THINKING,
85
+ "tool.started": DelegateEvent.TASK_TOOL_STARTED,
86
+ "tool.completed": DelegateEvent.TASK_TOOL_COMPLETED,
87
+ "subagent_progress": DelegateEvent.TASK_PROGRESS,
88
+ }
89
+
90
+ # Event → _ChildProgressRelay method name. Lifecycle strings are emitted by the orchestrator itself (not
91
+ # DelegateEvent). Any other DelegateEvent (TASK_TOOL_STARTED and the reserved TASK_* values) takes the tool-started
92
+ # path; None means "recognised but ignored".
93
+ _LIFECYCLE_EVENTS = frozenset({"subagent.start", "subagent.complete", "subagent.text"})
94
+ _EVENT_HANDLERS: Dict[Any, Optional[str]] = {
95
+ "subagent.start": "_on_start",
96
+ "subagent.complete": "_on_complete",
97
+ "subagent.text": "_on_text",
98
+ DelegateEvent.TASK_THINKING: "_on_thinking",
99
+ DelegateEvent.TASK_PROGRESS: "_on_progress",
100
+ DelegateEvent.TASK_TOOL_COMPLETED: None,
101
+ }
102
+
103
+ def _normalize_event(event_type: Any) -> Any:
104
+ """Lifecycle string / DelegateEvent / legacy string / ``delegate.*`` string
105
+ → dispatch key; None for unknown events."""
106
+ if isinstance(event_type, DelegateEvent) or (isinstance(event_type, str) and event_type in _LIFECYCLE_EVENTS):
107
+ return event_type
108
+ try:
109
+ return _LEGACY_EVENT_MAP.get(event_type) or DelegateEvent(event_type)
110
+ except (ValueError, TypeError):
111
+ return None
112
+
113
+ _CONTEXT_FILES_INTRO = (
114
+ "\nThe workspace's project context files are reproduced below. Their conventions and invariants are binding for "
115
+ "your work in this workspace.\n\n"
116
+ )
117
+ _COMPLETION_INSTRUCTIONS = (
118
+ "\nComplete this task using the tools available to you. When finished, provide a clear, concise summary of:\n"
119
+ "- What you did\n- What you found or accomplished\n- Any files you created or modified\n- Any issues encountered\n\n"
120
+ "Important workspace rule: Never assume a repository lives at /workspace/... or any other container-style path "
121
+ "unless the task/context explicitly gives that path. If no exact local path is provided, discover it first before "
122
+ "issuing git/workdir-specific commands.\n\n"
123
+ "Keep your final summary tight: lead with outcomes, prefer bullet points over paragraphs, and don't replay your "
124
+ "whole process. Your response is returned to the parent agent as a summary, and overlong summaries crowd out the "
125
+ "parent's context window."
126
+ )
127
+ _ORCHESTRATOR_BLOCK = (
128
+ "\n## Subagent Spawning (Orchestrator Role)\n"
129
+ "You have access to the `delegate_task` tool and CAN spawn your own subagents to parallelize independent work.\n\n"
130
+ "WHEN to delegate:\n"
131
+ "- The goal decomposes into 2+ independent subtasks that can run in parallel (e.g. research A and B simultaneously).\n"
132
+ "- A subtask is reasoning-heavy and would flood your context with intermediate data.\n\n"
133
+ "WHEN NOT to delegate:\n"
134
+ "- Single-step mechanical work — do it directly.\n"
135
+ "- Trivial tasks you can execute in one or two tool calls.\n"
136
+ "- Re-delegating your entire assigned goal to one worker (that's just pass-through with no value added).\n\n"
137
+ "Coordinate your workers' results and synthesize them before reporting back to your parent. You are responsible "
138
+ "for the final summary, not your workers.\n\n"
139
+ )
140
+ _LEAF_CHILDREN_NOTE = (
141
+ "Your own children MUST be leaves (cannot delegate further) because they would be at the depth floor — you cannot "
142
+ "pass role='orchestrator' to your own delegate_task calls."
143
+ )
144
+ _NESTED_CHILDREN_NOTE = (
145
+ "Your own children can themselves be orchestrators or leaves, depending on the `role` you pass to delegate_task. "
146
+ "Default is 'leaf'; pass role='orchestrator' explicitly when a child needs to further decompose its work."
147
+ )
148
+
149
+ def _build_child_system_prompt(
150
+ goal: str, context: Optional[str] = None, *, workspace_path: Optional[str] = None, role: str = "leaf",
151
+ max_spawn_depth: int = 2, child_depth: int = 1,
152
+ ) -> str:
153
+ """Focused system prompt for a child agent. role='orchestrator' appends a delegation-capability block (modeled on
154
+ OpenClaw's buildSubagentSystemPrompt); its depth note is literal truth grounded in the passed config so the LLM
155
+ can't confabulate nesting."""
156
+ parts = ["You are a focused subagent working on a specific delegated task.", "", f"YOUR TASK:\n{goal}"]
157
+ if context and context.strip():
158
+ parts.append(f"\nCONTEXT:\n{context}")
159
+ if workspace_path and str(workspace_path).strip():
160
+ parts.append(
161
+ "\nWORKSPACE PATH:\n"
162
+ f"{workspace_path}\n"
163
+ "Use this exact path for local repository/workdir operations unless the task explicitly says otherwise."
164
+ )
165
+ # Project context files (AGENTS.md / CLAUDE.md / .cursorrules ...) via the SAME discovery/priority/cap logic
166
+ # as the main agent's prompt: children are built with skip_context_files=True, so without this a subagent
167
+ # works in a repo blind to its conventions. SOUL.md is skipped (identity belongs to the parent).
168
+ # workspace_path comes only from explicit sources (_resolve_workspace_hint, never bare getcwd), so the
169
+ # install-tree-fallback leak doesn't apply. Best-effort.
170
+ _ctx_files = ""
171
+ with _quiet("subagent: workspace context-files load failed", exc_info=True):
172
+ # See #64590.
173
+ from agent.prompt_builder import build_context_files_prompt
174
+ _ctx_files = build_context_files_prompt(cwd=str(workspace_path), skip_soul=True)
175
+ if _ctx_files.strip():
176
+ parts.append(_CONTEXT_FILES_INTRO + _ctx_files.strip())
177
+ parts.append(_COMPLETION_INSTRUCTIONS)
178
+ if role == "orchestrator":
179
+ child_note = _LEAF_CHILDREN_NOTE if child_depth + 1 >= max_spawn_depth else _NESTED_CHILDREN_NOTE
180
+ parts.append(
181
+ _ORCHESTRATOR_BLOCK
182
+ + f"NOTE: You are at depth {child_depth}. The delegation tree is capped at max_spawn_depth={max_spawn_depth}. "
183
+ + child_note
184
+ )
185
+ return "\n".join(parts)
186
+
187
+ def _resolve_workspace_hint(parent_agent) -> Optional[str]:
188
+ """Best-effort local workspace hint for child prompts: only a concrete
189
+ absolute directory is ever injected (never a fake container path)."""
190
+ from agent.runtime_cwd import scope_terminal_cwd
191
+ candidates = [
192
+ scope_terminal_cwd(), getattr(getattr(parent_agent, "_subdirectory_hints", None), "working_dir", None),
193
+ getattr(parent_agent, "terminal_cwd", None), getattr(parent_agent, "cwd", None),
194
+ ]
195
+ for candidate in filter(None, candidates):
196
+ with _quiet(None):
197
+ text = os.path.abspath(os.path.expanduser(str(candidate)))
198
+ if os.path.isabs(text) and os.path.isdir(text):
199
+ return text
200
+ return None
201
+
202
+ _BATCH_ORDINALS: Dict[str, Dict[str, int]] = {}
203
+ _BATCH_ORDINALS_LOCK = threading.Lock()
204
+
205
+ def format_batch_tag(delegation_id: Optional[str], parent_agent: Any = None) -> str:
206
+ """Short human tag for a delegation batch: the parent's first fan-out is ``set 1``, its next distinct
207
+ delegation id ``set 2``. Several batches (a parent's fan-out plus a child's nested fan-out, or two
208
+ concurrent tools) print interleaved ``[n/N]`` lines to one console; without a tag ``✓ [3/3]`` and ``✓ [3/9]``
209
+ are indistinguishable, and a raw hex slice is unreadable. Ordinals are scoped per parent conversation
210
+ (``parent_agent.session_id``): one process hosts many conversations and every child's own fan-out, so a
211
+ process-wide counter showed a user's second wave as ``set 20``. Empty string when no id is known so callers
212
+ can concatenate unconditionally."""
213
+ if not isinstance(delegation_id, str) or not delegation_id:
214
+ return ""
215
+ scope = str(getattr(parent_agent, "session_id", None) or "")
216
+ with _BATCH_ORDINALS_LOCK:
217
+ ordinals = _BATCH_ORDINALS.setdefault(scope, {})
218
+ n = ordinals.setdefault(delegation_id, len(ordinals) + 1)
219
+ return f"set {n}"
220
+
221
+ def _batch_prefix(delegation_id: Optional[str], task_index: int, task_count: int, parent_agent: Any = None) -> str:
222
+ """``[set 2 · 3/9] `` for batch children, ``[set 2] `` for a lone child,
223
+ ``[3/9] `` / ``""`` when the batch id is unknown."""
224
+ tag = format_batch_tag(delegation_id, parent_agent)
225
+ if task_count > 1:
226
+ inner = f"{tag} · {task_index + 1}/{task_count}" if tag else f"{task_index + 1}/{task_count}"
227
+ return f"[{inner}] "
228
+ return f"[{tag}] " if tag else ""
229
+
230
+ def _emit_parent_console(parent_agent, line: str) -> None:
231
+ """Emit a progress line through ``parent_agent._safe_print`` when available so headless stdio hosts (ACP, gateway
232
+ API) can redirect it to stderr; a bare ``print()`` would land on stdout and corrupt JSON-RPC framing."""
233
+ printer = getattr(parent_agent, "_safe_print", None)
234
+ if callable(printer):
235
+ with _quiet(None):
236
+ printer(line)
237
+ return
238
+ print(line)
239
+
240
+ def _print_completion_line(parent_agent: Any, spinner_ref: Any, line: str, console_line: Optional[str] = None) -> None:
241
+ """Above-spinner line when a spinner exists (console fallback if it raises), else console
242
+ (``console_line`` when given, else the line indented two spaces)."""
243
+ if spinner_ref:
244
+ with _quiet(None):
245
+ spinner_ref.print_above(line)
246
+ return
247
+ _emit_parent_console(parent_agent, f" {line}" if console_line is None else console_line)
248
+
249
+ def _short(text: str, n: int) -> str:
250
+ return (text[:n] + "...") if len(text) > n else text
251
+
252
+
253
+ class _ChildProgressRelay:
254
+ """Callable relaying one child's events to the parent display. CLI: prints tree-view lines above the parent's
255
+ delegation spinner. Gateway: batches tool names (``_BATCH_SIZE``) and relays to the parent's progress callback,
256
+ threading the identity kwargs (subagent_id, parent_id, depth, model, toolsets) into every event so the TUI can
257
+ rebuild the live spawn tree and route per-branch controls back by ``subagent_id``."""
258
+
259
+ _BATCH_SIZE = 5
260
+
261
+ def __init__(
262
+ self, task_index: int, goal: str, spinner: Any, parent_cb: Any, task_count: int,
263
+ subagent_id, parent_id, depth, model, toolsets, session_ref,
264
+ ) -> None:
265
+ self.task_index, self.task_count, self.goal_label = task_index, task_count, (goal or "").strip()
266
+ # session_ref is a SHARED dict filled in later by the caller — keep the identity.
267
+ self.spinner, self.parent_cb, self.session_ref = spinner, parent_cb, session_ref if session_ref is not None else {}
268
+ self.subagent_id, self.parent_id, self.depth, self.model, self.toolsets = (
269
+ subagent_id, parent_id, depth, model, toolsets
270
+ )
271
+ self.batch: List[str] = []
272
+ self.tool_count = 0 # per-subagent running counter
273
+
274
+ def _prefix(self) -> str:
275
+ # The batch tag is resolved lazily from session_ref: the relay is built
276
+ # before delegate_task stamps ``_delegation_id`` on the child. The parent
277
+ # scope rides in the same ref so ordinals match the parent's own lines.
278
+ return _batch_prefix(
279
+ self.session_ref.get("delegation_id"), self.task_index, self.task_count,
280
+ parent_agent=self.session_ref.get("_parent_scope"),
281
+ )
282
+
283
+ def _identity_kwargs(self) -> Dict[str, Any]:
284
+ kw: Dict[str, Any] = {"task_index": self.task_index, "task_count": self.task_count, "goal": self.goal_label}
285
+ kw.update({k: getattr(self, k) for k in ("subagent_id", "parent_id", "depth", "model") if getattr(self, k) is not None})
286
+ if self.toolsets is not None:
287
+ kw["toolsets"] = list(self.toolsets)
288
+ # child_session_id / delegation_id are filled into the shared ref once
289
+ # the child exists, so every relayed event lets UIs open its session.
290
+ for src, dst in (("session_id", "child_session_id"), ("delegation_id", "delegation_id")):
291
+ if self.session_ref.get(src):
292
+ kw[dst] = str(self.session_ref[src])
293
+ kw["tool_count"] = self.tool_count
294
+ return kw
295
+
296
+ def _relay(self, event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs):
297
+ if self.parent_cb:
298
+ # kwargs override identity (e.g. status, duration_seconds).
299
+ with _quiet("Parent callback failed: %s"):
300
+ self.parent_cb(event_type, tool_name, preview, args, **{**self._identity_kwargs(), **kwargs})
301
+
302
+ def _tree_line(self, text: str) -> None:
303
+ """Print one tree-view line above the CLI spinner (no-op without a spinner)."""
304
+ if self.spinner:
305
+ with _quiet("Spinner print_above failed: %s"):
306
+ self.spinner.print_above(f" {self._prefix()}├─ {text}")
307
+
308
+ def _flush(self) -> None:
309
+ """Flush remaining batched tool names to the gateway."""
310
+ if self.parent_cb and self.batch:
311
+ self._relay("subagent.progress", preview=f"🔀 {self._prefix()}{', '.join(self.batch)}")
312
+ self.batch.clear()
313
+
314
+ # ── Lifecycle events emitted by the orchestrator itself ──
315
+ def _on_start(self, tool_name, preview, args, kwargs):
316
+ if self.goal_label:
317
+ self._tree_line(f"🔀 {_short(self.goal_label, 55)}")
318
+ self._relay("subagent.start", preview=preview or self.goal_label or "", **kwargs)
319
+
320
+ def _on_complete(self, tool_name, preview, args, kwargs):
321
+ # Failed child: echo one clean reason line into the CLI tree so the human
322
+ # sees WHY, not just a vanished branch (gateway renders off the relayed event).
323
+ if kwargs.get("status") in SUBAGENT_FAILURE_STATUSES:
324
+ self._tree_line(format_subagent_failure_line(
325
+ self.goal_label, kwargs.get("status"), error=kwargs.get("summary") or preview,
326
+ duration_seconds=kwargs.get("duration_seconds"),
327
+ ))
328
+ self._relay("subagent.complete", preview=preview, **kwargs)
329
+
330
+ def _on_text(self, tool_name, preview, args, kwargs):
331
+ # Streamed child reply text, relayed verbatim for gateway watch windows;
332
+ # inert on CLI/TUI (their progress handlers ignore non-tool events).
333
+ self._relay("subagent.text", preview=preview)
334
+
335
+ # ── DelegateEvent handlers ──
336
+ def _on_thinking(self, tool_name, preview, args, kwargs):
337
+ text = preview or tool_name or ""
338
+ self._tree_line(f'💭 "{_short(text, 55)}"')
339
+ self._relay("subagent.thinking", preview=text)
340
+
341
+ def _on_progress(self, tool_name, preview, args, kwargs):
342
+ # Pre-batched summary from a nested orchestrator's grandchild arrives in the tool_name slot: render distinctly
343
+ # (no tool-emoji lookup) and relay upward without re-batching.
344
+ summary_text = tool_name or preview or ""
345
+ if summary_text:
346
+ self._tree_line(f"🔀 {summary_text}")
347
+ if self.parent_cb:
348
+ with _quiet("Parent callback relay failed: %s"):
349
+ self.parent_cb("subagent_progress", f"{self._prefix()}{summary_text}")
350
+
351
+ def _on_tool_started(self, tool_name, preview, args, kwargs):
352
+ self.tool_count += 1
353
+ if self.subagent_id is not None:
354
+ with _active_subagents_lock:
355
+ rec = _active_subagents.get(self.subagent_id)
356
+ if rec is not None:
357
+ rec["tool_count"] = self.tool_count
358
+ rec["last_tool"] = tool_name or ""
359
+ if self.spinner:
360
+ from agent.display import get_tool_emoji
361
+ line = f"{get_tool_emoji(tool_name or '')} {tool_name}"
362
+ short = _short(preview, 35) if preview else ""
363
+ self._tree_line(f'{line} "{short}"' if short else line)
364
+ if self.parent_cb:
365
+ self._relay("subagent.tool", tool_name, preview, args)
366
+ self.batch.append(tool_name or "")
367
+ if len(self.batch) >= self._BATCH_SIZE:
368
+ self._flush()
369
+
370
+ def __call__(self, event_type, tool_name: str = None, preview: str = None, args=None, **kwargs):
371
+ key = _normalize_event(event_type)
372
+ method = None if key is None else _EVENT_HANDLERS.get(key, "_on_tool_started")
373
+ if method is not None:
374
+ getattr(self, method)(tool_name, preview, args, kwargs)
375
+
376
+ def _build_child_progress_callback(
377
+ task_index: int, goal: str, parent_agent, task_count: int = 1, *, subagent_id: Optional[str] = None,
378
+ parent_id: Optional[str] = None, depth: Optional[int] = None, model: Optional[str] = None,
379
+ toolsets: Optional[List[str]] = None, session_ref: Optional[Dict[str, Any]] = None,
380
+ ) -> Optional[callable]:
381
+ """Relay for one child's events (see ``_ChildProgressRelay``), or None when the parent has neither a spinner nor a
382
+ progress callback — the child then runs with no progress callback at all (zero behavior change)."""
383
+ spinner = getattr(parent_agent, "_delegate_spinner", None)
384
+ parent_cb = getattr(parent_agent, "tool_progress_callback", None)
385
+ if not spinner and not parent_cb:
386
+ return None
387
+ if session_ref is not None:
388
+ # Not an identity kwarg (underscore-prefixed, never relayed); only scopes the batch ordinal.
389
+ session_ref["_parent_scope"] = parent_agent
390
+ return _ChildProgressRelay(
391
+ task_index, goal, spinner, parent_cb, task_count, subagent_id, parent_id, depth, model, toolsets, session_ref,
392
+ )
tools/delegate_tool_tasks.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """delegate_task input validation: tasks=[...] / legacy goal normalisation, per-task output schemas and images."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ # Placeholder shapes for batch goal validation: bare 'TODO' / 'task N' labels, or unexpanded template markers. The
10
+ # marker regex is deliberately NARROW — only snake_case / space-separated placeholder identifiers (`<feature_name>`,
11
+ # `{file path}`, `<FEATURE-NAME>`), the shape LLM templates leave behind. Bare single-word brackets must never be
12
+ # rejected: legitimate goals are full of generics (`Vec<T>`), HTML tags (`<div>`), dict snippets (`{"key": 1}`), glob
13
+ # braces (`{a,b}`) and f-string style (`{i}`).
14
+ # See #81141.
15
+ _PLACEHOLDER_GOAL_RE = re.compile(r"^(todo|task\s*\d+)$", re.IGNORECASE)
16
+ _TEMPLATE_MARKER_RE = re.compile(
17
+ r"<[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)+>|\{[A-Za-z][A-Za-z0-9]*(?:[ _-][A-Za-z0-9]+)+\}"
18
+ )
19
+ _MIN_BATCH_GOAL_LEN = 10
20
+
21
+ def _recover_tasks_from_json_string(tasks: Any) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]:
22
+ """``(parsed_list, None)`` for a JSON-array string, ``(None, error)`` for a bad string, ``(None, None)`` otherwise."""
23
+ if not isinstance(tasks, str):
24
+ return None, None
25
+ raw = tasks.strip()
26
+ if not raw:
27
+ return None, "Provide either 'goal' (single task) or 'tasks' (batch)."
28
+ try:
29
+ parsed = json.loads(raw)
30
+ except json.JSONDecodeError as exc:
31
+ return None, f"tasks must be a JSON array of task objects; received a string that could not be parsed as JSON ({exc.msg})."
32
+ if not isinstance(parsed, list):
33
+ return None, f"tasks must be a JSON array of task objects; parsed {type(parsed).__name__} instead."
34
+ return parsed, None
35
+
36
+ def _validate_batch_tasks(task_list: List[Dict[str, Any]]) -> Optional[str]:
37
+ """Batch-only quality gate beyond per-task goal presence; actionable error or None. No minimum count: a one-entry
38
+ array is the canonical single-task shape (legacy top-level `goal` is wrapped into one). Duplicate goals are
39
+ deliberately NOT rejected — identical-goal fan-outs (best-of-N / ensemble sampling) are legitimate and blocking
40
+ them broke real workflows. The too-short check applies only to multi-task fan-outs (terse goals there are
41
+ usually unexpanded templates); a SINGLE task legitimately uses short goals ("Fix the tests").
42
+
43
+ See #81141.
44
+ """
45
+ for i, task in enumerate(task_list):
46
+ goal = str(task.get("goal", "")).strip()
47
+ if _PLACEHOLDER_GOAL_RE.match(" ".join(goal.lower().split())):
48
+ return (
49
+ f"Task {i} has a placeholder goal ({goal!r}). Replace it "
50
+ "with a specific, self-contained description of what the subagent should accomplish."
51
+ )
52
+ marker = _TEMPLATE_MARKER_RE.search(goal)
53
+ if marker:
54
+ return (
55
+ f"Task {i} goal contains an unexpanded template marker "
56
+ f"({marker.group(0)!r}). Substitute the real value before "
57
+ "calling delegate_task — subagents cannot resolve placeholders."
58
+ )
59
+ if len(goal) < _MIN_BATCH_GOAL_LEN and len(task_list) >= 2:
60
+ return (
61
+ f"Task {i} goal is too short ({goal!r}). Write a specific, "
62
+ f"self-contained goal of at least {_MIN_BATCH_GOAL_LEN} characters so the subagent knows "
63
+ "exactly what to do."
64
+ )
65
+ return None
66
+
67
+ def _normalize_task_list(
68
+ goal, context, tasks, output_schema, top_role: str, max_children: int
69
+ ) -> tuple[Optional[List[Dict[str, Any]]], Optional[str]]:
70
+ """``(task_list, None)`` from ``tasks=[...]`` or the legacy single ``goal``, else ``(None, error)``."""
71
+ recovered_tasks, tasks_error = _recover_tasks_from_json_string(tasks)
72
+ if tasks_error:
73
+ return None, tasks_error
74
+ if recovered_tasks is not None:
75
+ tasks = recovered_tasks
76
+ # Small models emit tasks=[] alongside a single goal: treat as "no batch".
77
+ if isinstance(tasks, list) and not tasks:
78
+ tasks = None
79
+
80
+ if tasks and isinstance(tasks, list):
81
+ if len(tasks) > max_children:
82
+ return None, (
83
+ f"Too many tasks: {len(tasks)} provided, but max_concurrent_children is {max_children}. "
84
+ f"Either reduce the task count, split into multiple delegate_task calls, or increase "
85
+ f"delegation.max_concurrent_children in config.yaml."
86
+ )
87
+ task_list = tasks
88
+ elif goal and isinstance(goal, str) and goal.strip():
89
+ task_list = [{"goal": goal, "context": context, "role": top_role}]
90
+ if output_schema is not None:
91
+ task_list[0]["output_schema"] = output_schema
92
+ else:
93
+ return None, (
94
+ "No tasks provided. Pass tasks=[{goal: '...', context: '...'}, "
95
+ "...] — one entry per subagent (a single task is a one-entry array)."
96
+ )
97
+
98
+ for i, task in enumerate(task_list):
99
+ if not isinstance(task, dict):
100
+ return None, f"Task {i} must be an object, got {type(task).__name__}."
101
+ if not task.get("goal", "").strip():
102
+ return None, f"Task {i} is missing a 'goal'."
103
+ # The single-goal form is exempt from the batch gate (short goals are valid there).
104
+ batch_error = _validate_batch_tasks(task_list) if isinstance(tasks, list) else None
105
+ return (None, batch_error) if batch_error else (task_list, None)
106
+
107
+ def _coerce_task_schemas(
108
+ task_list: List[Dict[str, Any]], output_schema: Optional[Dict[str, Any]]
109
+ ) -> tuple[List[Optional[Dict[str, Any]]], Optional[str]]:
110
+ """Per-task coerced output schemas. A malformed output_schema fails the whole call before any child spawns;
111
+ schema-less tasks resolve to None and take no new code paths downstream."""
112
+ from tools.delegation_output_schema import coerce_output_schema
113
+ task_schemas: List[Optional[Dict[str, Any]]] = []
114
+ for i, task in enumerate(task_list):
115
+ raw_schema = task.get("output_schema")
116
+ if raw_schema is None and len(task_list) == 1 and output_schema is not None:
117
+ raw_schema = output_schema
118
+ coerced_schema, schema_err = coerce_output_schema(raw_schema)
119
+ if schema_err:
120
+ return [], f"Task {i} output_schema invalid: {schema_err}"
121
+ task_schemas.append(coerced_schema)
122
+ return task_schemas, None
123
+
124
+ # Per-task image ceiling: enough for screenshots/mocks while keeping the child's first request small.
125
+ _MAX_TASK_IMAGES = 8
126
+
127
+ def _normalize_task_images(task: dict, i: int) -> tuple[Optional[List[str]], Optional[str]]:
128
+ """``(cleaned_list_or_None, None)`` for a task's optional ``images`` (local paths, http(s) or data: URLs), else
129
+ ``(None, error)``. A bare string is wrapped into a one-entry list (small models emit scalars for arrays)."""
130
+ raw = task.get("images")
131
+ if raw is None:
132
+ return None, None
133
+ if isinstance(raw, str):
134
+ raw = [raw]
135
+ if not isinstance(raw, list):
136
+ return None, f"Task {i} 'images' must be an array of local file paths or http(s) URLs."
137
+ cleaned: List[str] = []
138
+ for item in raw:
139
+ if not isinstance(item, str) or not item.strip():
140
+ return None, f"Task {i} 'images' entries must be non-empty strings (local file paths or http(s) URLs)."
141
+ cleaned.append(item.strip())
142
+ if len(cleaned) > _MAX_TASK_IMAGES:
143
+ return None, (
144
+ f"Task {i} has {len(cleaned)} images; the per-task limit is {_MAX_TASK_IMAGES}. "
145
+ "Trim to the images the child actually needs to see."
146
+ )
147
+ return (cleaned or None), None
148
+
149
+ def _coerce_task_images(
150
+ task_list: List[Dict[str, Any]], images: Optional[List[str]]
151
+ ) -> tuple[List[Optional[List[str]]], Optional[str]]:
152
+ """Per-task validated image lists; a malformed list fails the whole call before any child spawns. The legacy
153
+ top-level ``images`` applies to a single task only, like ``output_schema``."""
154
+ task_images: List[Optional[List[str]]] = []
155
+ for i, task in enumerate(task_list):
156
+ if task.get("images") is None and len(task_list) == 1 and images is not None:
157
+ task = {**task, "images": images}
158
+ cleaned, err = _normalize_task_images(task, i)
159
+ if err:
160
+ return [], err
161
+ task_images.append(cleaned)
162
+ return task_images, None
tools/delegation_live_log.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Live, tail-able transcripts for delegated subagents.
2
+
3
+ One append-only log per child under ``<hermes_home>/cache/delegation/live/
4
+ <delegation_id>/task-<n>.log``, pre-created with a header at dispatch (so
5
+ ``tail -f`` attaches immediately); paths are returned from ``delegate_task``.
6
+ ``cache/delegation`` is mounted read-only into remote terminal backends, so
7
+ every line written here must be credential-redacted. Never raises into the
8
+ agent loop; append mode per write (close() is the flush); 7-day retention.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import logging
15
+ import shutil
16
+ import threading
17
+ import time
18
+ import uuid
19
+ from contextlib import contextmanager
20
+ from pathlib import Path
21
+ from typing import Any, Dict, List, Optional
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ LIVE_RETENTION_DAYS = 7
26
+
27
+ # Per-line truncation budgets (chars): the .log is a compact operational view;
28
+ # the child's SessionDB transcript and summary spill files carry full text.
29
+ _ASSISTANT_MAX = 600
30
+ _THINKING_MAX = 300
31
+ _ARGS_MAX = 220
32
+ _RESULT_MAX = 400
33
+ _KICKOFF_MAX = 500
34
+ # Stream deltas are buffered and flushed as one assistant line when another
35
+ # event type arrives (or on completion); capped so a huge reply can't hold memory.
36
+ _STREAM_BUFFER_FLUSH_CHARS = 4000
37
+ _TIME_FMT = "%Y-%m-%d %H:%M:%S"
38
+
39
+
40
+ def live_transcript_root() -> Path:
41
+ """Root directory for live transcripts (profile-safe, never ~/.hermes)."""
42
+ from hermes_constants import get_hermes_dir
43
+ return get_hermes_dir("cache/delegation", "delegation_cache") / "live"
44
+
45
+
46
+ @contextmanager
47
+ def _best_effort(what: str):
48
+ """Swallow and debug-log any failure: nothing here may reach the agent loop."""
49
+ try:
50
+ yield
51
+ except Exception as exc: # noqa: BLE001
52
+ logger.debug("Live transcript %s failed: %s", what, exc)
53
+
54
+
55
+ def _one_line(text: Any, limit: int) -> str:
56
+ """Collapse to a single line and truncate with an elided-chars note."""
57
+ s = " ".join(str(text or "").split())
58
+ if len(s) > limit:
59
+ s = s[:limit] + f" …(+{len(s) - limit} chars)"
60
+ return s
61
+
62
+
63
+ def _redact(text: str) -> str:
64
+ """Mask credentials (``force=True``: safety boundary, even when the global
65
+ toggle is off); if the redactor is unavailable, withhold rather than leak."""
66
+ if not text:
67
+ return text
68
+ try:
69
+ from agent.redact import redact_sensitive_text
70
+ return redact_sensitive_text(text, force=True) or ""
71
+ except Exception: # pragma: no cover - core module; never leak on failure
72
+ return "[line withheld: redaction unavailable]"
73
+
74
+
75
+ def _joined(*parts: str) -> str:
76
+ return " ".join(filter(None, parts))
77
+
78
+
79
+ def _dump_json(path: Path, payload: Dict[str, Any]) -> None:
80
+ path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
81
+
82
+
83
+ class LiveTranscriptWriter:
84
+ """Append-only event log for ONE subagent task. Best-effort: the first write
85
+ failure flips ``_ok`` off and later calls become debug-logged no-ops."""
86
+
87
+ def __init__(self, delegation_id: str, task_index: int, goal: str,
88
+ context: Optional[str] = None, root: Optional[Path] = None):
89
+ self.delegation_id = delegation_id
90
+ self.task_index = task_index
91
+ self._ok = False
92
+ self._lock = threading.Lock()
93
+ self._stream_buf: List[str] = []
94
+ self._stream_len = 0
95
+ self.path: Optional[Path] = None
96
+ with _best_effort(f"init ({delegation_id} task {task_index})"):
97
+ goal_line = _one_line(goal, _KICKOFF_MAX)
98
+ d = (root if root is not None else live_transcript_root()) / delegation_id
99
+ d.mkdir(parents=True, exist_ok=True)
100
+ path = d / f"task-{task_index}.log"
101
+ path.write_text(
102
+ "=== Hermes subagent live transcript ===\n"
103
+ f"delegation: {delegation_id} task: {task_index}\n"
104
+ f"goal: {_redact(goal_line)}\n" # header bypasses event(), so redact here too
105
+ f"started: {time.strftime(_TIME_FMT)}\n"
106
+ "(append-only; streams while the subagent runs — tail -f me)\n"
107
+ + "=" * 40 + "\n", encoding="utf-8")
108
+ self.path, self._ok = path, True
109
+ self.event("user", "kickoff: " + goal_line
110
+ + (f" | context: {_one_line(context, _KICKOFF_MAX)}" if context else ""))
111
+
112
+ def event(self, role: str, text: str) -> None:
113
+ """Append one ``HH:MM:SS role | text`` line. Single choke point: every typed
114
+ helper funnels through here so one redaction covers everything."""
115
+ if not self._ok or self.path is None:
116
+ return
117
+ line = f"{time.strftime('%H:%M:%S')} {role:<9}| {_redact(text)}\n"
118
+ try:
119
+ with self._lock, open(self.path, "a", encoding="utf-8") as fh:
120
+ fh.write(line)
121
+ except Exception as exc:
122
+ self._ok = False
123
+ logger.debug("Live transcript write failed (%s): %s", self.path, exc)
124
+
125
+ def _line(self, role: str, text: str, limit: int) -> None:
126
+ if t := _one_line(text, limit):
127
+ self.event(role, t)
128
+
129
+ def assistant_text(self, text: str) -> None:
130
+ self._line("assistant", text, _ASSISTANT_MAX)
131
+
132
+ def thinking(self, text: str) -> None:
133
+ self._line("think", text, _THINKING_MAX)
134
+
135
+ def tool_start(self, name: str, args_preview: Any = None) -> None:
136
+ self.flush_stream()
137
+ self.event("tool", f"-> {name or '?'}({_one_line(args_preview, _ARGS_MAX)})")
138
+
139
+ def tool_result(self, name: str, result: Any = None,
140
+ duration: Any = None, is_error: bool = False) -> None:
141
+ status = "ERROR" if is_error else "ok"
142
+ try:
143
+ dur = "" if duration is None else f" {float(duration):.1f}s"
144
+ except (TypeError, ValueError):
145
+ dur = ""
146
+ self.event("result", f"{name or '?'} {status}{dur}: {_one_line(result, _RESULT_MAX)}")
147
+
148
+ def marker(self, text: str) -> None:
149
+ """Lifecycle marker: start / final / error / interrupt / budget."""
150
+ self.flush_stream()
151
+ self.event("final", _one_line(text, _ASSISTANT_MAX))
152
+
153
+ def add_stream_delta(self, delta: str) -> None:
154
+ """Buffer streamed assistant reply text; flushed as one line."""
155
+ if not delta or not self._ok:
156
+ return
157
+ self._stream_buf.append(delta)
158
+ self._stream_len += len(delta)
159
+ if self._stream_len >= _STREAM_BUFFER_FLUSH_CHARS:
160
+ self.flush_stream()
161
+
162
+ def flush_stream(self) -> None:
163
+ if self._stream_buf:
164
+ text, self._stream_buf, self._stream_len = "".join(self._stream_buf), [], 0
165
+ self.assistant_text(text)
166
+
167
+ def _on_complete(self, tool_name, preview, args, kwargs):
168
+ dur = kwargs.get("duration_seconds")
169
+ summary = kwargs.get("summary") or preview
170
+ self.marker(_joined(
171
+ f"status={kwargs.get('status', '?')}",
172
+ f"duration={dur}s" if dur is not None else "",
173
+ f"summary: {_one_line(summary, _RESULT_MAX)}" if summary else ""))
174
+
175
+ # Event demux (the tool_progress_callback surface): handler(self, tool_name, preview, args, kwargs).
176
+ _OBSERVERS = {
177
+ "tool.started": lambda s, n, p, a, kw: s.tool_start(str(n or ""), p if p else a),
178
+ "tool.completed": lambda s, n, p, a, kw: s.tool_result(
179
+ str(n or ""), result=kw.get("result"), duration=kw.get("duration"),
180
+ is_error=bool(kw.get("is_error"))),
181
+ # Fired as cb("_thinking", <text>) — text rides in the tool_name slot.
182
+ "_thinking": lambda s, n, p, a, kw: s.thinking(str(n or p or "")),
183
+ # cb("reasoning.available", "_thinking", <text>, None)
184
+ "reasoning.available": lambda s, n, p, a, kw: s.thinking(str(p or "")),
185
+ "subagent.text": lambda s, n, p, a, kw: s.add_stream_delta(str(p or "")),
186
+ "subagent.start": lambda s, n, p, a, kw: s.event("start", _one_line(p, _KICKOFF_MAX)),
187
+ "subagent.complete": _on_complete}
188
+
189
+ def observe(self, event_type: Any, tool_name: Any = None, preview: Any = None,
190
+ args: Any = None, **kwargs: Any) -> None:
191
+ """Map a child tool_progress_callback event onto transcript lines.
192
+ Unknown events are ignored. Never raises (event() swallows I/O)."""
193
+ handler = self._OBSERVERS.get(str(event_type or ""))
194
+ if handler is not None:
195
+ handler(self, tool_name, preview, args, kwargs)
196
+
197
+ def finalize(self, entry: Dict[str, Any]) -> None:
198
+ """Terminal marker with exit-reason detail subagent.complete lacks."""
199
+ exit_reason = entry.get("exit_reason")
200
+ self.marker(_joined(
201
+ f"end status={entry.get('status', '?')}",
202
+ f"exit_reason={exit_reason}" if exit_reason else "",
203
+ "(iteration budget exhausted)" if exit_reason == "max_iterations" else "",
204
+ f"error: {_one_line(entry['error'], _RESULT_MAX)}" if entry.get("error") else ""))
205
+
206
+
207
+ def wrap_progress_callback(inner_cb, writer: LiveTranscriptWriter):
208
+ """Wrap a child's tool_progress_callback (may be None) so events also land in
209
+ the log; writer failures never propagate. Preserves the ``_flush`` contract."""
210
+
211
+ def _cb(event_type, tool_name=None, preview=None, args=None, **kwargs):
212
+ with _best_effort("observe"):
213
+ writer.observe(event_type, tool_name, preview, args, **kwargs)
214
+ if inner_cb is not None:
215
+ inner_cb(event_type, tool_name, preview, args, **kwargs)
216
+
217
+ def _flush():
218
+ with _best_effort("flush"):
219
+ writer.flush_stream()
220
+ if callable(getattr(inner_cb, "_flush", None)):
221
+ inner_cb._flush()
222
+
223
+ _cb._flush = _flush
224
+ return _cb
225
+
226
+
227
+ def create_live_transcripts(
228
+ task_list: List[Dict[str, Any]], context: Optional[str] = None,
229
+ delegation_id: Optional[str] = None, model: Optional[str] = None,
230
+ provider: Optional[str] = None,
231
+ ) -> tuple[Optional[str], List[Optional[LiveTranscriptWriter]], List[str]]:
232
+ """One pre-headered writer per task + a manifest.json; prunes stale dirs.
233
+ Returns ``(delegation_id, writers, paths)``; on any top-level failure
234
+ ``(None, [None]*n, [])`` so delegation proceeds untouched."""
235
+ n = len(task_list)
236
+ prune_stale_live_dirs() # best-effort; never raises
237
+ with _best_effort("creation"):
238
+ # Same id shape as async_delegation's so the dir name matches the handle.
239
+ deleg_id = delegation_id or f"deleg_{uuid.uuid4().hex[:8]}"
240
+ made = [LiveTranscriptWriter(deleg_id, i, str(t.get("goal", "")), context=t.get("context") or context)
241
+ for i, t in enumerate(task_list)]
242
+ writers: List[Optional[LiveTranscriptWriter]] = [w if w.path is not None else None for w in made]
243
+ paths: List[str] = [str(w.path) for w in made if w.path is not None]
244
+ if not paths:
245
+ return None, [None] * n, []
246
+ _write_manifest(deleg_id, task_list, paths, model=model, provider=provider)
247
+ return deleg_id, writers, paths
248
+ return None, [None] * n, []
249
+
250
+
251
+ def _manifest_path(delegation_id: str) -> Path:
252
+ return live_transcript_root() / delegation_id / "manifest.json"
253
+
254
+
255
+ def _write_manifest(delegation_id: str, task_list: List[Dict[str, Any]],
256
+ paths: List[str], model: Optional[str] = None,
257
+ provider: Optional[str] = None) -> None:
258
+ with _best_effort("manifest write"):
259
+ _dump_json(_manifest_path(delegation_id), {
260
+ "delegation_id": delegation_id, "started": time.strftime(_TIME_FMT),
261
+ "task_count": len(task_list), "model": model, "provider": provider,
262
+ "tasks": [{
263
+ "index": i,
264
+ # Same mounted dir as the .log files, so the goal needs the same redaction.
265
+ "goal": _redact(str(t.get("goal", ""))[:500]),
266
+ "log": paths[i] if i < len(paths) else None,
267
+ "status": "running"} for i, t in enumerate(task_list)]})
268
+
269
+
270
+ def update_manifest_statuses(delegation_id: Optional[str],
271
+ results: List[Dict[str, Any]]) -> None:
272
+ """Best-effort per-task status update once the batch has aggregated."""
273
+ if not delegation_id:
274
+ return
275
+ with _best_effort("manifest update"):
276
+ mp = _manifest_path(delegation_id)
277
+ manifest = json.loads(mp.read_text(encoding="utf-8"))
278
+ by_index = {r.get("task_index"): r for r in results if isinstance(r, dict)}
279
+ for task in manifest.get("tasks", []):
280
+ r = by_index.get(task.get("index"))
281
+ if r is not None:
282
+ task["status"] = r.get("status", task.get("status"))
283
+ if r.get("exit_reason"):
284
+ task["exit_reason"] = r["exit_reason"]
285
+ manifest["completed"] = time.strftime(_TIME_FMT)
286
+ _dump_json(mp, manifest)
287
+
288
+
289
+ def prune_stale_live_dirs(max_age_days: int = LIVE_RETENTION_DAYS) -> int:
290
+ """Remove live/<delegation_id> dirs older than the retention window. Best-effort."""
291
+ removed = 0
292
+ with _best_effort("pruning"):
293
+ root = live_transcript_root()
294
+ if not root.is_dir():
295
+ return 0
296
+ cutoff = time.time() - max_age_days * 86400
297
+ for child in root.iterdir():
298
+ try:
299
+ if child.is_dir() and child.stat().st_mtime < cutoff:
300
+ shutil.rmtree(child, ignore_errors=True)
301
+ removed += 1
302
+ except OSError:
303
+ continue
304
+ return removed
305
+
306
+
307
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
308
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
309
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
310
+ # The whole block is removed by reverting the commit that added it.
311
+
312
+ def new_live_delegation_id() -> str:
313
+ """Same shape as async_delegation's ids so the dir name matches the handle."""
314
+ return f"deleg_{uuid.uuid4().hex[:8]}"
315
+ # ---- END PLUGIN-COMPAT ----
tools/delegation_output_schema.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Structured-output schema helpers for delegate_task.
2
+
3
+ Optional per-task ``output_schema`` (a JSON Schema object): the child gets an
4
+ OUTPUT CONTRACT block appended to its context, the parent validates the final
5
+ answer with jsonschema, and on failure sends exactly ONE bounded retry turn
6
+ carrying the validation errors verbatim (more retries make frontier models
7
+ drop fields that were right the first time; the schema is never re-pasted).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import logging
14
+ from typing import Any, Dict, List, Optional, Tuple
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ def coerce_output_schema(raw: Any) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
20
+ """``(schema, None)`` when usable, ``(None, error)`` when not; ``None`` input
21
+ passes through as ``(None, None)`` (no schema requested)."""
22
+ if raw is None:
23
+ return None, None
24
+ if isinstance(raw, str):
25
+ # Models sometimes double-encode the schema as a JSON string.
26
+ try:
27
+ raw = json.loads(raw)
28
+ except (ValueError, TypeError):
29
+ return None, "output_schema must be a JSON Schema object, got a non-JSON string."
30
+ if not isinstance(raw, dict):
31
+ return None, "output_schema must be a JSON Schema object."
32
+ if not isinstance(raw, dict):
33
+ return None, f"output_schema must be a JSON Schema object, got {type(raw).__name__}."
34
+ try:
35
+ from jsonschema.validators import validator_for # type: ignore[import-untyped]
36
+ validator_for(raw).check_schema(raw)
37
+ except ImportError:
38
+ # Degrade to accepting the dict as-is so delegation still works without jsonschema.
39
+ logger.debug("jsonschema unavailable; skipping output_schema meta-validation")
40
+ except Exception as exc:
41
+ return None, f"output_schema is not a valid JSON Schema: {exc}"
42
+ return raw, None
43
+
44
+
45
+ def append_output_contract(context: Optional[str], schema: Dict[str, Any]) -> str:
46
+ """Append the explicit output contract block to a child's context."""
47
+ try:
48
+ schema_text = json.dumps(schema, indent=2, ensure_ascii=False)
49
+ except (TypeError, ValueError):
50
+ schema_text = str(schema)
51
+ block = ("OUTPUT CONTRACT (machine-validated):\n"
52
+ "Your FINAL response must be a single JSON object that validates "
53
+ "against this JSON Schema. No prose before or after the JSON; a "
54
+ "```json code fence is acceptable but not required.\n" f"{schema_text}")
55
+ base = (context or "").rstrip()
56
+ return f"{base}\n\n{block}" if base else block
57
+
58
+
59
+ def extract_json_candidate(text: str) -> str:
60
+ """Strip markdown fences and prose around the outermost ``{...}``/``[...]``."""
61
+ raw = (text or "").strip()
62
+ if raw.startswith("```"):
63
+ raw = raw.split("\n", 1)[-1]
64
+ if raw.rstrip().endswith("```"):
65
+ raw = raw.rstrip()[: -3]
66
+ raw = raw.strip()
67
+ if raw.lower().startswith("json\n"):
68
+ raw = raw.split("\n", 1)[1]
69
+ for opener, closer in (("{", "}"), ("[", "]")):
70
+ if raw.startswith(opener):
71
+ return raw
72
+ start = raw.find(opener)
73
+ end = raw.rfind(closer)
74
+ if start >= 0 and end > start:
75
+ return raw[start : end + 1]
76
+ return raw
77
+
78
+
79
+ def validate_output(text: str, schema: Dict[str, Any]) -> Tuple[bool, List[str]]:
80
+ """``(True, [])`` or ``(False, errors)`` with strings suitable for the retry turn."""
81
+ candidate = extract_json_candidate(text or "")
82
+ if not candidate.strip():
83
+ return False, ["Response was empty — expected a JSON object matching the schema."]
84
+ try:
85
+ parsed = json.loads(candidate)
86
+ except (ValueError, TypeError) as exc:
87
+ return False, [f"Response is not valid JSON: {exc}"]
88
+ try:
89
+ from jsonschema.validators import validator_for # type: ignore[import-untyped]
90
+ except ImportError:
91
+ logger.debug("jsonschema unavailable; accepting parsed JSON without validation")
92
+ return True, []
93
+ validator = validator_for(schema)(schema)
94
+ errors = sorted(validator.iter_errors(parsed), key=lambda e: list(e.absolute_path))
95
+ rendered = [ # bound error volume for the retry prompt
96
+ "$" + "".join(f"[{p}]" if isinstance(p, int) else f".{p}" for p in err.absolute_path) + f": {err.message}"
97
+ for err in errors[:10]]
98
+ return not rendered, rendered
99
+
100
+
101
+ def build_retry_message(errors: List[str]) -> str:
102
+ """Single bounded retry turn: errors verbatim, schema deliberately NOT re-pasted."""
103
+ error_block = "\n".join(f"- {e}" for e in errors)
104
+ return ("Your previous final response was rejected by the output contract "
105
+ "validator. Validation errors:\n" f"{error_block}\n\n"
106
+ "Reply with ONLY the corrected JSON object matching the OUTPUT "
107
+ "CONTRACT schema from your task context. No prose, no explanations.")
108
+
109
+
110
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
111
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
112
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
113
+ # The whole block is removed by reverting the commit that added it.
114
+
115
+ MAX_SCHEMA_RETRIES = 1
116
+ # ---- END PLUGIN-COMPAT ----
tools/desktop_ui.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Bridge desktop-only tools to Hermes-desktop renderer events.
3
+
4
+ The desktop ``tui_gateway`` installs an emitter via :func:`set_emitter`; elsewhere it
5
+ stays ``None`` and tools report "desktop only". Routing keys off ``HERMES_UI_SESSION_ID``
6
+ so the event lands on the window that owns the turn (the sink is lock-guarded).
7
+ """
8
+
9
+ import json
10
+ from typing import Callable, Optional
11
+
12
+ from gateway.session_context import get_session_env
13
+ from tools.registry import tool_error
14
+
15
+ # (sid, event, payload) sink, installed by the desktop gateway.
16
+ _emit: Optional[Callable[[str, str, dict], None]] = None
17
+
18
+
19
+ def set_emitter(fn: Optional[Callable[[str, str, dict], None]]) -> None:
20
+ """Install (or clear) the renderer-event sink. Called by the desktop gateway."""
21
+ global _emit
22
+ _emit = fn
23
+
24
+
25
+ def available() -> bool:
26
+ """True when running under the desktop app (an emitter is wired)."""
27
+ return _emit is not None
28
+
29
+
30
+ def user_enabled(setting: str, default: bool) -> bool:
31
+ """Read a desktop Appearance switch from ``display.<setting>``. The renderer mirrors
32
+ these toggles onto the CONNECTED gateway's config, so this is the user's real answer
33
+ for local/SSH/URL/cloud gateways alike; ``check_fn``s use it to withdraw a tool from
34
+ the schema. Unreadable config -> ``default`` so a shipped-on feature does not vanish
35
+ on a transient read error."""
36
+ try:
37
+ from hermes_cli.config import load_config_readonly
38
+ display = load_config_readonly().get("display")
39
+ except Exception:
40
+ return default
41
+ if not isinstance(display, dict) or setting not in display:
42
+ return default
43
+ return bool(display.get(setting))
44
+
45
+
46
+ def emit(event: str, payload: dict) -> bool:
47
+ """Route ``event`` to the window owning the current turn; False when no emitter."""
48
+ if _emit is None:
49
+ return False
50
+ _emit(get_session_env("HERMES_UI_SESSION_ID", ""), event, payload)
51
+ return True
52
+
53
+
54
+ def emit_or_error(event: str, payload: dict, fail_prefix: str, desktop_only: str, result: dict) -> str:
55
+ """Emit ``event``; ``tool_error`` text on failure (``fail_prefix`` + exception, or
56
+ ``desktop_only`` when no emitter), else ``result`` as JSON. Calls ``emit`` via the
57
+ module attribute so tests can patch it."""
58
+ try:
59
+ ok = emit(event, payload)
60
+ except Exception as exc:
61
+ return tool_error(f"{fail_prefix}{exc}")
62
+ return json.dumps(result, ensure_ascii=False) if ok else tool_error(desktop_only)
63
+
64
+
65
+ def passthrough_json(raw) -> str:
66
+ """Desktop answers with a JSON object; pass it through, else wrap the raw text."""
67
+ try:
68
+ return json.dumps(json.loads(raw), ensure_ascii=False)
69
+ except (TypeError, ValueError):
70
+ return json.dumps({"text": str(raw)}, ensure_ascii=False)
tools/env_probe.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local-environment toolchain probe for the system prompt: when the terminal backend
2
+ is local, one deterministic line about Python tooling (python3/python versions, missing
3
+ pip, pip bound to another Python, PEP 668) so models don't discover it by hitting
4
+ walls. Cached per process; "" when clean. Remote backends are skipped (the sandbox has
5
+ its own probe in agent/prompt_builder). Toggle: ``agent.environment_probe`` in config.yaml."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import shutil
11
+ import subprocess
12
+ import tempfile
13
+ import threading
14
+ from typing import Optional
15
+
16
+ from hermes_cli._subprocess_compat import windows_hide_flags
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # Concurrency model: exactly ONE background worker runs the probe; ``_PROBE_DONE``
21
+ # signals completion. Callers block at most ``_PROBE_WAIT_TIMEOUT`` s then fail open
22
+ # with "" — a stuck probe (e.g. a Windows pipe wedged by an orphaned pip descendant)
23
+ # can degrade only the probe line, never system-prompt construction.
24
+ # Module-level cache. The probe result is deterministic for the lifetime of the process — Python install
25
+ # state doesn't change mid-session in any way that would matter for the system prompt. See #67964.
26
+ _CACHE_LOCK = threading.Lock()
27
+ _CACHED_LINE: Optional[str] = None # None = not probed yet; "" = probed, nothing to say.
28
+ _PROBE_DONE = threading.Event()
29
+ _PROBE_THREAD: Optional[threading.Thread] = None
30
+ _PROBE_GEN = 0 # bumped on reset so a stale worker can't publish into the fresh generation
31
+ _PROBE_WAIT_TIMEOUT = 10.0 # healthy runtime ~0.5s
32
+ _WAIT_ALREADY_TIMED_OUT = False # after one full wait, later callers only peek
33
+
34
+ # Keep in sync with agent/prompt_builder.py:_REMOTE_TERMINAL_BACKENDS.
35
+ # Duplicated rather than imported to avoid a circular import.
36
+ _REMOTE_BACKENDS = frozenset({
37
+ "docker", "singularity", "modal", "daytona", "ssh", "managed_modal",
38
+ "vercel_sandbox",
39
+ })
40
+
41
+
42
+ def _plugin_backend_is_remote(backend: str) -> bool:
43
+ """Whether a plugin-registered terminal backend is remote (fail-soft)."""
44
+ if not backend or backend in _REMOTE_BACKENDS or backend == "local":
45
+ return False
46
+ try:
47
+ from agent.terminal_env_registry import provider_flag
48
+
49
+ return bool(provider_flag(backend, "is_remote", False))
50
+ except Exception:
51
+ return False
52
+
53
+
54
+ def _run(cmd: list[str], timeout: float = 3.0) -> tuple[int, str, str]:
55
+ """Run a short subprocess -> (returncode, stdout, stderr); failures (binary
56
+ missing, timeout, OSError) return (-1, "", "<reason>"). Output goes through temp
57
+ files, not pipes, so ``timeout`` bounds the *whole* call even on native Windows: a
58
+ console-script launcher (``pip.exe``) can spawn a descendant that inherits the
59
+ captured handles and outlives its parent; with OS pipes ``communicate()``'s reader
60
+ threads block until that grandchild closes the write end (a warm probe could hang
61
+ ~28 min holding ``_CACHE_LOCK``). Temp files make ``wait()`` cover only the child."""
62
+ try:
63
+ with tempfile.TemporaryFile() as out_f, tempfile.TemporaryFile() as err_f:
64
+ try:
65
+ result = subprocess.run(
66
+ cmd, stdout=out_f, stderr=err_f, timeout=timeout, check=False,
67
+ # CREATE_NO_WINDOW (0 on POSIX): pythonw hosts would flash a console
68
+ stdin=subprocess.DEVNULL, creationflags=windows_hide_flags())
69
+ except subprocess.TimeoutExpired:
70
+ return -1, "", "timeout"
71
+ out_f.seek(0)
72
+ err_f.seek(0)
73
+ return (result.returncode, out_f.read().decode("utf-8", "replace").strip(),
74
+ err_f.read().decode("utf-8", "replace").strip())
75
+ except FileNotFoundError:
76
+ return -1, "", "not found"
77
+ except OSError as exc:
78
+ return -1, "", f"oserror: {exc}"
79
+
80
+
81
+ def _py_out(binary: str, *args: str) -> Optional[str]:
82
+ """stdout of ``<binary> *args`` when the binary is on PATH and exits 0, else None."""
83
+ if not shutil.which(binary):
84
+ return None
85
+ rc, out, _err = _run([binary, *args])
86
+ return out if rc == 0 else None
87
+
88
+
89
+ def _python_version_of(binary: str) -> Optional[str]:
90
+ """Return a short version string like ``3.12.4`` for ``binary``, or None."""
91
+ code = "import sys; print('.'.join(map(str, sys.version_info[:3])))"
92
+ return _py_out(binary, "-c", code) or None
93
+
94
+
95
+ def _has_pip_module(binary: str) -> bool:
96
+ """True if ``<binary> -m pip --version`` succeeds."""
97
+ return _py_out(binary, "-m", "pip", "--version") is not None
98
+
99
+
100
+ def _detect_pep668(binary: str) -> bool:
101
+ """True when ``<binary>`` is PEP-668 externally-managed (``EXTERNALLY-MANAGED``
102
+ marker next to the stdlib, as Debian/Ubuntu ship)."""
103
+ code = ("import os; print('yes' if os.path.exists(os.path.join("
104
+ "os.path.dirname(os.__file__), 'EXTERNALLY-MANAGED')) else 'no')")
105
+ return (_py_out(binary, "-c", code) or "").strip() == "yes"
106
+
107
+
108
+ def _pip_python_version() -> Optional[str]:
109
+ """If ``pip`` is on PATH, the Python version it's bound to — the trailing
110
+ ``(python X.Y)`` of ``pip --version`` (e.g. ``"3.12"``), else None."""
111
+ out = _py_out("pip", "--version") or ""
112
+ if "(python " in out and out.endswith(")"):
113
+ return out.rsplit("(python ", 1)[1][:-1].strip()
114
+ return None
115
+
116
+
117
+ def _resolve_terminal_backend() -> str:
118
+ """Scope-aware terminal backend name (``local`` when unresolvable)."""
119
+ try:
120
+ from tools.terminal_scope import terminal_env
121
+
122
+ return (terminal_env("TERMINAL_ENV") or "local").strip().lower()
123
+ except Exception: # never let policy resolution break prompt building
124
+ logger.debug("terminal backend resolution failed", exc_info=True)
125
+ return "local"
126
+
127
+
128
+ def _build_probe_line() -> str:
129
+ """Build the one-liner; "" when nothing notable is detected — the goal is to
130
+ save the model from an avoidable wall, not narrate a healthy environment."""
131
+ py3_ver = _python_version_of("python3")
132
+ py_ver = _python_version_of("python") # for systems with a `python` alias
133
+ py3_has_pip = _has_pip_module("python3") if py3_ver else False
134
+ pip_bound_to = _pip_python_version()
135
+ py3_pep668 = _detect_pep668("python3") if py3_ver else False
136
+ # Bare which() is correct here (unlike Hermes's own uv call sites): this reports
137
+ # the environment *the model will see* in the terminal tool, whose PATH includes
138
+ # the Hermes-managed $HERMES_HOME/bin via local.py.
139
+ has_uv = shutil.which("uv") is not None
140
+
141
+ mismatch = bool(pip_bound_to and py3_ver and not py3_ver.startswith(pip_bound_to))
142
+ if py3_ver is not None and py3_has_pip and not mismatch and (not py3_pep668 or has_uv):
143
+ return ""
144
+ # Compact factual summary; ONE line so it doesn't dominate the prompt.
145
+ bits: list[str] = []
146
+ if py3_ver:
147
+ bits.append(f"python3={py3_ver}" + ("" if py3_has_pip else " (no pip module)"))
148
+ else:
149
+ bits.append("python3=missing")
150
+ if py_ver and py_ver != py3_ver:
151
+ bits.append(f"python={py_ver}")
152
+ elif not py_ver and py3_ver:
153
+ # Common on Debian/Ubuntu — stop the model typing `python`.
154
+ bits.append("python=missing (use python3)")
155
+ if pip_bound_to:
156
+ if mismatch:
157
+ bits.append(f"pip→python{pip_bound_to} (mismatch)")
158
+ elif not py3_has_pip:
159
+ bits.append(f"pip→python{pip_bound_to}") # pip script works, `-m pip` doesn't
160
+ elif not py3_has_pip:
161
+ # (when `pip` is off PATH but `python3 -m pip` works, say nothing)
162
+ bits.append("pip=missing")
163
+ if py3_pep668:
164
+ bits.append("PEP 668=yes (use venv or uv)")
165
+ if has_uv:
166
+ bits.append("uv=installed")
167
+ return "Python toolchain: " + ", ".join(bits) + "."
168
+
169
+
170
+ def get_environment_probe_line(*, force_refresh: bool = False) -> str:
171
+ """Return the cached probe line (building it on first call); "" when the
172
+ environment is clean, so the prompt assembler drops the section. Waits at most
173
+ ``_PROBE_WAIT_TIMEOUT`` on the single worker, then fails open with "".
174
+ ``force_refresh`` is for tests.
175
+
176
+ A wedged probe subprocess (#67964) therefore can never block system-prompt construction — at worst the
177
+ toolchain line is absent from prompts built while the probe is stuck.
178
+ """
179
+ global _WAIT_ALREADY_TIMED_OUT
180
+ if force_refresh:
181
+ _reset_cache_for_tests()
182
+ # Resolve the backend HERE, in the caller's context: under gateway multiplexing the
183
+ # routed profile's backend lives in the per-turn terminal scope, which the worker
184
+ # thread does not inherit. Remote backends answer "" without consulting the cache
185
+ # — the cached line describes the HOST toolchain.
186
+ # See #68559.
187
+ backend = _resolve_terminal_backend()
188
+ if backend in _REMOTE_BACKENDS or _plugin_backend_is_remote(backend):
189
+ return ""
190
+ if _PROBE_DONE.is_set():
191
+ return _CACHED_LINE or ""
192
+ _ensure_probe_started()
193
+ wait_timeout = 0.05 if _WAIT_ALREADY_TIMED_OUT else _PROBE_WAIT_TIMEOUT
194
+ if not _PROBE_DONE.wait(timeout=wait_timeout):
195
+ # Probe stuck or pathologically slow: the line is a nice-to-have,
196
+ # blocking prompt construction is an outage. Fail open.
197
+ if not _WAIT_ALREADY_TIMED_OUT:
198
+ _WAIT_ALREADY_TIMED_OUT = True
199
+ logger.warning(
200
+ "env_probe did not finish within %.0fs; building the system "
201
+ "prompt without the Python toolchain line", _PROBE_WAIT_TIMEOUT)
202
+ return ""
203
+ return _CACHED_LINE or ""
204
+
205
+
206
+ def _probe_worker(gen: int) -> None:
207
+ """Body of the single probe thread — computes and publishes the line."""
208
+ global _CACHED_LINE
209
+ try:
210
+ line = _build_probe_line()
211
+ except Exception as exc: # never let probe failure propagate
212
+ logger.debug("env_probe failed: %s", exc)
213
+ line = ""
214
+ with _CACHE_LOCK:
215
+ if gen != _PROBE_GEN:
216
+ return # superseded by a reset (tests) — discard stale result
217
+ _CACHED_LINE = line
218
+ _PROBE_DONE.set()
219
+
220
+
221
+ def _ensure_probe_started() -> None:
222
+ """Start the probe worker if it isn't running and hasn't finished."""
223
+ global _PROBE_THREAD
224
+ with _CACHE_LOCK:
225
+ if _PROBE_DONE.is_set() or (_PROBE_THREAD is not None and _PROBE_THREAD.is_alive()):
226
+ return
227
+ _PROBE_THREAD = threading.Thread(
228
+ target=_probe_worker, args=(_PROBE_GEN,), name="env-probe", daemon=True)
229
+ _PROBE_THREAD.start()
230
+
231
+
232
+ def warm_environment_probe_async() -> None:
233
+ """Start the probe in the background so the first system-prompt build doesn't
234
+ pay the ~0.5s of subprocess calls on the time-to-first-token path. Idempotent;
235
+ ``get_environment_probe_line`` waits (bounded) on the same worker."""
236
+ _ensure_probe_started()
237
+
238
+
239
+ def _reset_cache_for_tests() -> None:
240
+ """Test helper — clear the cache between probe scenarios."""
241
+ global _CACHED_LINE, _PROBE_THREAD, _PROBE_GEN, _WAIT_ALREADY_TIMED_OUT
242
+ with _CACHE_LOCK:
243
+ _CACHED_LINE = None
244
+ _PROBE_DONE.clear()
245
+ _PROBE_THREAD = None
246
+ _PROBE_GEN += 1
247
+ _WAIT_ALREADY_TIMED_OUT = False
248
+
249
+
250
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
251
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
252
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
253
+ # The whole block is removed by reverting the commit that added it.
254
+ import os # noqa: F401,E402
255
+ # ---- END PLUGIN-COMPAT ----
tools/feishu_doc_tool.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Feishu Document Tool -- read document content via Feishu/Lark API.
2
+
3
+ Provides ``feishu_doc_read`` for reading document content as plain text.
4
+ Uses the same lazy-import + BaseRequest pattern as feishu_comment.py.
5
+ """
6
+
7
+ from tools.feishu_lark import ( # noqa: F401 (set_client/get_client are imported by feishu_comment)
8
+ _check_feishu,
9
+ build_request,
10
+ get_client,
11
+ raw_body,
12
+ set_client)
13
+ from tools.registry import registry, tool_error, tool_result
14
+
15
+ _RAW_CONTENT_URI = "/open-apis/docx/v1/documents/:document_id/raw_content"
16
+
17
+ FEISHU_DOC_READ_SCHEMA = {
18
+ "name": "feishu_doc_read",
19
+ "description": (
20
+ "Read the full content of a Feishu/Lark document as plain text. "
21
+ "Useful when you need more context beyond the quoted text in a comment."
22
+ ),
23
+ "parameters": {
24
+ "type": "object",
25
+ "properties": {
26
+ "doc_token": {
27
+ "type": "string",
28
+ "description": "The document token (from the document URL or comment context).",
29
+ },
30
+ },
31
+ "required": ["doc_token"],
32
+ },
33
+ }
34
+
35
+
36
+ def _handle_feishu_doc_read(args: dict, **kwargs) -> str:
37
+ doc_token = args.get("doc_token", "").strip()
38
+ if not doc_token:
39
+ return tool_error("doc_token is required")
40
+ client = get_client()
41
+ if client is None:
42
+ return tool_error("Feishu client not available (not in a Feishu comment context)")
43
+ try:
44
+ request = build_request("GET", _RAW_CONTENT_URI, paths={"document_id": doc_token})
45
+ except ImportError:
46
+ return tool_error("lark_oapi not installed")
47
+
48
+ # Handlers run synchronously in a worker thread (no event loop): call the blocking client.
49
+ response = client.request(request)
50
+ code = getattr(response, "code", None)
51
+ if code != 0:
52
+ return tool_error(f"Failed to read document: code={code} msg={getattr(response, 'msg', 'unknown error')}")
53
+
54
+ body = raw_body(response)
55
+ if body is not None:
56
+ try:
57
+ return tool_result(success=True, content=body.get("data", {}).get("content", ""))
58
+ except AttributeError:
59
+ pass
60
+ data = getattr(response, "data", None) # fallback: the typed response.data
61
+ if data:
62
+ content = data.get("content", "") if isinstance(data, dict) else getattr(data, "content", str(data))
63
+ return tool_result(success=True, content=content)
64
+ return tool_error("No content returned from document API")
65
+
66
+
67
+ registry.register(
68
+ name="feishu_doc_read", toolset="feishu_doc", schema=FEISHU_DOC_READ_SCHEMA, handler=_handle_feishu_doc_read,
69
+ check_fn=_check_feishu, requires_env=[], is_async=False, description="Read Feishu document content",
70
+ emoji="\U0001f4c4")
71
+
72
+
73
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
74
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
75
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
76
+ # The whole block is removed by reverting the commit that added it.
77
+ import json # noqa: F401,E402
78
+ import logging # noqa: F401,E402
79
+ import threading # noqa: F401,E402
80
+
81
+
82
+ _PLUGIN_COMPAT_LAZY = {
83
+ 'logger': ('tools.approval', 'logger'),
84
+ }
85
+
86
+
87
+ def __getattr__(name): # PEP 562 — lazy so no import cycles
88
+ target = _PLUGIN_COMPAT_LAZY.get(name)
89
+ if target is None:
90
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
91
+ import importlib
92
+ from hermes_cli.plugin_compat import warn_once
93
+ warn_once(__name__, name, *target)
94
+ return getattr(importlib.import_module(target[0]), target[1])
95
+ # ---- END PLUGIN-COMPAT ----
tools/file_operations_common.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Result dataclasses and pure text helpers shared by ``tools.file_operations``
2
+ and its search/lint mixins. Leaf module (imports nothing from ``tools`` at module
3
+ scope) so nothing cycles. The ``to_dict`` output of every class here IS tool
4
+ behavior — key names, order and omission rules are pinned by tests and read by
5
+ the model.
6
+ """
7
+
8
+ import re
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, ClassVar, Dict, List, Optional
11
+
12
+
13
+ @dataclass
14
+ class ReadResult:
15
+ """Result from reading a file."""
16
+ content: str = ""
17
+ total_lines: int = 0
18
+ file_size: int = 0
19
+ truncated: bool = False
20
+ hint: Optional[str] = None
21
+ is_binary: bool = False
22
+ is_image: bool = False
23
+ base64_content: Optional[str] = None
24
+ mime_type: Optional[str] = None
25
+ dimensions: Optional[str] = None # For images: "WIDTHxHEIGHT"
26
+ error: Optional[str] = None
27
+ similar_files: List[str] = field(default_factory=list)
28
+
29
+ def to_dict(self) -> dict:
30
+ return {k: v for k, v in self.__dict__.items() if v is not None and v != []}
31
+
32
+
33
+ @dataclass
34
+ class WriteResult:
35
+ """Result from writing a file."""
36
+ bytes_written: int = 0
37
+ dirs_created: bool = False
38
+ # True when the on-disk sha256 matched the intended content; None when the
39
+ # backend couldn't verify (no sha256sum). A mismatch is a hard error, never a flag.
40
+ verified: Optional[bool] = None
41
+ lint: Optional[Dict[str, Any]] = None
42
+ # LSP semantic diagnostics, kept separate from ``lint`` (syntax) so the model
43
+ # reads the two as independent signals. None when LSP is off/inapplicable.
44
+ lsp_diagnostics: Optional[str] = None
45
+ error: Optional[str] = None
46
+ warning: Optional[str] = None
47
+
48
+ def to_dict(self) -> dict:
49
+ return {k: v for k, v in self.__dict__.items() if v is not None}
50
+
51
+
52
+ @dataclass
53
+ class PatchResult:
54
+ """Result from patching a file."""
55
+ success: bool = False
56
+ diff: str = ""
57
+ files_modified: List[str] = field(default_factory=list)
58
+ files_created: List[str] = field(default_factory=list)
59
+ files_deleted: List[str] = field(default_factory=list)
60
+ lint: Optional[Dict[str, Any]] = None
61
+ lsp_diagnostics: Optional[str] = None # see WriteResult.lsp_diagnostics
62
+ error: Optional[str] = None
63
+ # Success-shaped no-op: the edit was already present, nothing written; ``note`` says why.
64
+ no_change: bool = False
65
+ note: Optional[str] = None
66
+
67
+ # Emission order is part of the output contract.
68
+ _DICT_FIELDS: ClassVar[tuple] = (
69
+ "diff", "files_modified", "files_created", "files_deleted",
70
+ "lint", "lsp_diagnostics", "error",
71
+ )
72
+
73
+ def to_dict(self) -> dict:
74
+ result: Dict[str, Any] = {"success": self.success}
75
+ if self.no_change:
76
+ result["no_change"] = True
77
+ if self.note:
78
+ result["note"] = self.note
79
+ for key in self._DICT_FIELDS:
80
+ value = getattr(self, key)
81
+ if value:
82
+ result[key] = value
83
+ return result
84
+
85
+
86
+ @dataclass
87
+ class SearchMatch:
88
+ """A single search match."""
89
+ path: str
90
+ line_number: int
91
+ content: str
92
+ mtime: float = 0.0 # Modification time for sorting
93
+
94
+
95
+ @dataclass
96
+ class SearchResult:
97
+ """Result from searching."""
98
+ matches: List[SearchMatch] = field(default_factory=list)
99
+ files: List[str] = field(default_factory=list)
100
+ counts: Dict[str, int] = field(default_factory=dict)
101
+ total_count: int = 0
102
+ truncated: bool = False
103
+ limit_reason: Optional[str] = None
104
+ warning: Optional[str] = None
105
+ error: Optional[str] = None
106
+
107
+ # Below this many matches the verbose array is already compact enough that
108
+ # a path-grouping header would cost more tokens than it saves.
109
+ _DENSIFY_MIN_MATCHES: ClassVar[int] = 5
110
+
111
+ def _densify_matches(self) -> Optional[str]:
112
+ """Lossless path-grouped text block: path once, then `` <line>: <content>``
113
+ rows. Relies on rg/grep emitting a file's hits consecutively. None when
114
+ too few matches to be worth it."""
115
+ if len(self.matches) < self._DENSIFY_MIN_MATCHES:
116
+ return None
117
+ lines: list[str] = []
118
+ current_path: Optional[str] = None
119
+ for m in self.matches:
120
+ if m.path != current_path:
121
+ lines.append(m.path)
122
+ current_path = m.path
123
+ # rstrip only: leading indentation is meaningful code and kept verbatim.
124
+ lines.append(f" {m.line_number}: {m.content.rstrip()}")
125
+ return "\n".join(lines)
126
+
127
+ def to_dict(self, densify: bool = False) -> dict:
128
+ result: dict[str, object] = {"total_count": self.total_count}
129
+ if self.matches:
130
+ dense = self._densify_matches() if densify else None
131
+ if dense is not None:
132
+ # Self-describing so the model never guesses the block's shape.
133
+ result["matches_format"] = (
134
+ "path-grouped: each file path on its own line, followed by "
135
+ "indented '<line>: <content>' rows for matches in that file"
136
+ )
137
+ result["matches_text"] = dense
138
+ else:
139
+ result["matches"] = [
140
+ {"path": m.path, "line": m.line_number, "content": m.content} for m in self.matches
141
+ ]
142
+ if self.files:
143
+ result["files"] = self.files
144
+ if self.counts:
145
+ result["counts"] = self.counts
146
+ if self.truncated:
147
+ result["truncated"] = True
148
+ result["total_count_is_lower_bound"] = True
149
+ for key in ("limit_reason", "warning", "error"):
150
+ value = getattr(self, key)
151
+ if value:
152
+ result[key] = value
153
+ return result
154
+
155
+
156
+ @dataclass
157
+ class LintResult:
158
+ """Result from linting a file."""
159
+ success: bool = True
160
+ skipped: bool = False
161
+ output: str = ""
162
+ message: str = ""
163
+
164
+ def to_dict(self) -> dict:
165
+ if self.skipped:
166
+ return {"status": "skipped", "message": self.message}
167
+ result = {"status": "ok" if self.success else "error", "output": self.output}
168
+ if self.message:
169
+ result["message"] = self.message
170
+ return result
171
+
172
+
173
+ @dataclass
174
+ class ExecuteResult:
175
+ """Result from executing a shell command."""
176
+ stdout: str = ""
177
+ exit_code: int = 0
178
+
179
+
180
+ # ---------------------------------------------------------------------------
181
+ # Pure text helpers (no I/O)
182
+ # ---------------------------------------------------------------------------
183
+
184
+ _OSC_SEQUENCE_RE = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
185
+ _FENCE_MARKER_RE = re.compile(r"'?\x07?__HERMES_FENCE_[A-Za-z0-9]+__\x07?'?")
186
+
187
+
188
+ def _strip_terminal_fence_leaks(text: str) -> str:
189
+ """Strip leaked terminal fence wrappers (OSC sequences, fence markers) from
190
+ command output; drops lines that were nothing but wrapper."""
191
+ if not text:
192
+ return text
193
+ cleaned_lines: List[str] = []
194
+ for line in text.splitlines(keepends=True):
195
+ had_terminal_wrapper = "__HERMES_FENCE_" in line or "\x1b]" in line
196
+ cleaned = _FENCE_MARKER_RE.sub("", _OSC_SEQUENCE_RE.sub("", line)).replace("\x07", "")
197
+ if had_terminal_wrapper and cleaned.strip("'\r\n\t ") == "":
198
+ continue
199
+ cleaned_lines.append(cleaned)
200
+ return "".join(cleaned_lines)
201
+
202
+
203
+ def _detect_line_ending(sample: str) -> Optional[str]:
204
+ """Dominant line ending of ``sample`` (``\\r\\n`` if any CRLF in the first 4KB,
205
+ else ``\\n``), or None for empty/single-line content. Preserves a file's
206
+ endings across write_file/patch: bare-LF tool args would otherwise silently
207
+ normalize CRLF files, and patch would produce mixed endings."""
208
+ head = sample[:4096] if sample else ""
209
+ if "\r\n" in head:
210
+ return "\r\n"
211
+ if "\n" in head:
212
+ return "\n"
213
+ return None
214
+
215
+
216
+ def _normalize_line_endings(text: str, target: str) -> str:
217
+ """Convert every line ending (CRLF, lone CR, LF) in ``text`` to ``target``.
218
+ Idempotent. Collapses to LF first — separate replacements would
219
+ double-convert CRLF → LFLF."""
220
+ lf_normalized = text.replace("\r\n", "\n").replace("\r", "\n")
221
+ if target == "\n":
222
+ return lf_normalized
223
+ if target == "\r\n":
224
+ return lf_normalized.replace("\n", "\r\n")
225
+ return text
226
+
227
+
228
+ # UTF-8 BOM (EF BB BF == U+FEFF), prepended by some Windows editors. Stripped on
229
+ # read so the model never sees a phantom first character (and patch's first-line
230
+ # match works), restored on write when the on-disk file had one.
231
+ _UTF8_BOM = "\ufeff"
232
+
233
+
234
+ def _strip_bom(text: str) -> tuple[str, bool]:
235
+ """Return (text-without-leading-BOM, had_bom). Only a leading BOM is
236
+ stripped; mid-content U+FEFF is legitimate data."""
237
+ if _has_bom(text):
238
+ return text[len(_UTF8_BOM):], True
239
+ return text, False
240
+
241
+
242
+ def _has_bom(text: Optional[str]) -> bool:
243
+ """True if ``text`` begins with a UTF-8 BOM."""
244
+ return bool(text) and text.startswith(_UTF8_BOM)
245
+
246
+
247
+ # ---------------------------------------------------------------------------
248
+ # Pagination clamps
249
+ # ---------------------------------------------------------------------------
250
+
251
+ DEFAULT_READ_OFFSET = 1
252
+ DEFAULT_READ_LIMIT = 2000
253
+ DEFAULT_SEARCH_OFFSET = 0
254
+ DEFAULT_SEARCH_LIMIT = 50
255
+
256
+
257
+ def _coerce_int(value: Any, default: int) -> int:
258
+ """Best-effort integer coercion for tool pagination inputs."""
259
+ try:
260
+ return int(value)
261
+ except (TypeError, ValueError):
262
+ return default
263
+
264
+
265
+ def normalize_read_pagination(offset: Any = DEFAULT_READ_OFFSET,
266
+ limit: Any = DEFAULT_READ_LIMIT) -> tuple[int, int]:
267
+ """Clamp read_file pagination so invalid values can never reach a sed range
268
+ like ``0,-1p`` (schemas declare bounds, but not every caller enforces them).
269
+ The ``limit`` ceiling is ``tool_output.max_lines`` from config.yaml."""
270
+ from tools.tool_output_limits import get_max_lines
271
+ normalized_offset = max(1, _coerce_int(offset, DEFAULT_READ_OFFSET))
272
+ normalized_limit = max(1, min(_coerce_int(limit, DEFAULT_READ_LIMIT), get_max_lines()))
273
+ return normalized_offset, normalized_limit
274
+
275
+
276
+ def normalize_search_pagination(offset: Any = DEFAULT_SEARCH_OFFSET,
277
+ limit: Any = DEFAULT_SEARCH_LIMIT) -> tuple[int, int]:
278
+ """Return safe search pagination bounds for shell head/tail pipelines."""
279
+ return max(0, _coerce_int(offset, DEFAULT_SEARCH_OFFSET)), max(1, _coerce_int(limit, DEFAULT_SEARCH_LIMIT))
tools/file_operations_lint.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Syntax-lint and LSP-diagnostics tier for ``tools.file_operations``.
2
+
3
+ ``ShellFileOperations`` inherits ``LintMixin``; module constants and in-process
4
+ linters are pure functions importable from this module.
5
+ """
6
+
7
+ import ast
8
+ import json
9
+ import os
10
+ import tomllib
11
+ from typing import Callable, Dict, Optional
12
+
13
+ from tools.file_operations_common import LintResult
14
+
15
+ # Shell linters by extension (external toolchain). ``.tsx`` is deliberately absent:
16
+ # it hits the "No linter" skip and LSP covers it when enabled.
17
+ LINTERS = {
18
+ '.py': 'python -m py_compile {file} 2>&1',
19
+ '.js': 'node --check {file} 2>&1',
20
+ '.ts': 'npx tsc --noEmit {file} 2>&1',
21
+ '.go': 'go vet {file} 2>&1',
22
+ '.rs': 'rustfmt --check {file} 2>&1',
23
+ }
24
+
25
+ # Per-file shell linters that flood phantom errors on real projects (single-file
26
+ # ``tsc`` ignores tsconfig, ``go vet`` fails outside a module, ``rustfmt --check``
27
+ # is style-only): skipped when an LSP server claims the file. py_compile /
28
+ # node --check are file-local and correct so always run.
29
+ _SHELL_LINTER_LSP_REDUNDANT = frozenset({'.ts', '.go', '.rs'})
30
+
31
+ # Output substrings (case-insensitive) meaning the linter binary exists but could
32
+ # not run → ``skipped`` so the write isn't flagged and the LSP tier still runs.
33
+ _LINTER_UNUSABLE_PATTERNS = {
34
+ 'npx': (
35
+ 'this is not the tsc command you are looking for', # tsc not installed locally
36
+ 'could not determine executable to run',
37
+ 'not found in npm registry',
38
+ ),
39
+ 'rustfmt': (
40
+ 'no input filename given', # outside a Cargo project
41
+ 'error: not a workspace',
42
+ ),
43
+ 'go': (
44
+ 'cannot find package', # outside a module / GOPATH
45
+ 'go: cannot find main module',
46
+ ),
47
+ }
48
+
49
+
50
+ def _looks_like_linter_unusable(base_cmd: str, output: str) -> bool:
51
+ """True iff ``output`` from ``base_cmd`` (first word of the linter cmd) says the tool itself couldn't run."""
52
+ patterns = _LINTER_UNUSABLE_PATTERNS.get(base_cmd)
53
+ if not patterns:
54
+ return False
55
+ lower = output.lower()
56
+ return any(p in lower for p in patterns)
57
+
58
+
59
+ def _lint_json_inproc(content: str) -> tuple[bool, str]:
60
+ """In-process JSON syntax check. Returns (ok, error_message)."""
61
+ try:
62
+ json.loads(content)
63
+ return True, ""
64
+ except json.JSONDecodeError as e:
65
+ return False, f"JSONDecodeError: {e.msg} (line {e.lineno}, column {e.colno})"
66
+ except Exception as e: # noqa: BLE001 — any parse failure is a lint failure
67
+ return False, f"{type(e).__name__}: {e}"
68
+
69
+
70
+ def _lint_yaml_inproc(content: str) -> tuple[bool, str]:
71
+ """In-process YAML syntax check; ``__SKIP__`` when PyYAML is missing. Syntax-only
72
+ (``yaml.parse``), NOT ``safe_load``: loading rejects valid multi-doc streams and
73
+ app tags (``!Sub``, ``!vault``), and this is a fail-closed WRITE gate."""
74
+ try:
75
+ import yaml as _yaml
76
+ except ImportError:
77
+ return True, "__SKIP__"
78
+ try:
79
+ for _event in _yaml.parse(content):
80
+ pass
81
+ return True, ""
82
+ except _yaml.YAMLError as e:
83
+ return False, f"YAMLError: {e}"
84
+ except Exception as e: # noqa: BLE001
85
+ return False, f"{type(e).__name__}: {e}"
86
+
87
+
88
+ def _lint_toml_inproc(content: str) -> tuple[bool, str]:
89
+ """In-process TOML syntax check (stdlib tomllib)."""
90
+ try:
91
+ tomllib.loads(content)
92
+ return True, ""
93
+ except Exception as e: # TOMLDecodeError is a ValueError subclass
94
+ return False, f"{type(e).__name__}: {e}"
95
+
96
+
97
+ def _lint_python_inproc(content: str) -> tuple[bool, str]:
98
+ """In-process Python syntax check via ast.parse (py_compile's scope, no subprocess)."""
99
+ try:
100
+ ast.parse(content)
101
+ return True, ""
102
+ except SyntaxError as e:
103
+ loc = f" (line {e.lineno}, column {e.offset})" if e.lineno else ""
104
+ return False, f"{type(e).__name__}: {e.msg}{loc}"
105
+ except Exception as e: # noqa: BLE001
106
+ return False, f"{type(e).__name__}: {e}"
107
+
108
+
109
+ # In-process linters, preferred over shell linters (no subprocess). Each returns
110
+ # (ok, error); error ``"__SKIP__"`` = unavailable dependency, counts as "no linter".
111
+ LINTERS_INPROC: Dict[str, Callable[[str], tuple[bool, str]]] = {
112
+ '.py': _lint_python_inproc,
113
+ '.json': _lint_json_inproc,
114
+ '.yaml': _lint_yaml_inproc,
115
+ '.yml': _lint_yaml_inproc,
116
+ '.toml': _lint_toml_inproc,
117
+ }
118
+
119
+ # Extensions where write_file REFUSES on a parse failure. ``.py`` is excluded on
120
+ # purpose: test fixtures use ``*.py`` paths as a stand-in for arbitrary text, so
121
+ # Python keeps the non-blocking lint-delta report.
122
+ _FAIL_CLOSED_INPROC_EXTS = frozenset({'.json', '.yaml', '.yml', '.toml'})
123
+
124
+
125
+ class LintMixin:
126
+ """Post-write syntax lint + LSP diagnostics. Requires ``_exec``,
127
+ ``_has_command``, ``_escape_shell_arg``, ``_escape_native_tool_arg`` and
128
+ ``env`` from the host class."""
129
+
130
+ def _check_lint(self, path: str, content: Optional[str] = None) -> LintResult:
131
+ """Syntax-check ``path``: in-process linter when one matches the
132
+ extension (``content`` avoids a re-read), else the shell linter table."""
133
+ ext = os.path.splitext(path)[1].lower()
134
+ inproc = LINTERS_INPROC.get(ext)
135
+ if inproc is not None:
136
+ if content is None:
137
+ read_result = self._exec(f"cat {self._escape_shell_arg(path)} 2>/dev/null")
138
+ if read_result.exit_code != 0:
139
+ return LintResult(skipped=True, message=f"Failed to read {path} for lint")
140
+ content = read_result.stdout
141
+ ok, err = inproc(content)
142
+ if err == "__SKIP__":
143
+ return LintResult(skipped=True, message=f"No linter available for {ext} (missing dependency)")
144
+ return LintResult(success=ok, output="" if ok else err)
145
+ if ext not in LINTERS:
146
+ return LintResult(skipped=True, message=f"No linter for {ext} files")
147
+ # Single-file tsc can't read tsconfig.json and floods phantom TS2307/TS2339
148
+ # errors the delta filter misreports as "pre-existing"; let the LSP tier speak.
149
+ if ext == '.ts' and self._has_ancestor_tsconfig(path):
150
+ return LintResult(skipped=True, message=(
151
+ "Project tsconfig.json detected — per-file tsc skipped "
152
+ "(single-file tsc can't resolve project aliases/globals; "
153
+ "use the LSP tier or `tsc -p tsconfig.json` for real "
154
+ "diagnostics)."
155
+ ))
156
+ if ext in _SHELL_LINTER_LSP_REDUNDANT and self._lsp_will_handle(path):
157
+ return LintResult(skipped=True, message=f"LSP server handles {ext} — shell linter skipped")
158
+ linter_cmd = LINTERS[ext]
159
+ base_cmd = linter_cmd.split()[0]
160
+ if not self._has_command(base_cmd):
161
+ return LintResult(skipped=True, message=f"{base_cmd} not available")
162
+ # Native Windows binaries need C:/... not MSYS /c/... (→ phantom ENOENT).
163
+ result = self._exec(linter_cmd.replace("{file}", self._escape_native_tool_arg(path)), timeout=30)
164
+ if result.exit_code != 0 and _looks_like_linter_unusable(base_cmd, result.stdout):
165
+ from tools.ansi_strip import strip_ansi
166
+ cleaned = strip_ansi(result.stdout).strip()
167
+ # Collapse to one line — the npx banner is multi-line ASCII art.
168
+ first_line = next((ln.strip() for ln in cleaned.splitlines() if ln.strip()), cleaned[:120])
169
+ return LintResult(skipped=True, message=f"{base_cmd} not usable: {first_line[:200]}")
170
+ return LintResult(success=result.exit_code == 0, output=result.stdout.strip())
171
+
172
+ def _check_lint_delta(self, path: str, pre_content: Optional[str],
173
+ post_content: Optional[str] = None) -> LintResult:
174
+ """Post-write lint; when it fails and ``pre_content`` is known, report only
175
+ errors this edit introduced (pre-existing lines filtered out). Semantic
176
+ (LSP) diagnostics are a separate channel — see ``_maybe_lsp_diagnostics``."""
177
+ post = self._check_lint(path, content=post_content)
178
+ if post.success or post.skipped or pre_content is None:
179
+ return post
180
+ pre = self._check_lint(path, content=pre_content)
181
+ if pre.success or pre.skipped or not pre.output:
182
+ return post # pre-write was clean (or unlintable): all post errors are new
183
+ # Single-error parsers stop at the first error, so if every post error already
184
+ # existed we can't prove the edit is clean — say nothing new was introduced.
185
+ pre_lines = {ln.strip() for ln in pre.output.splitlines() if ln.strip()}
186
+ post_lines = [ln for ln in post.output.splitlines() if ln.strip() and ln.strip() not in pre_lines]
187
+ if not post_lines:
188
+ return LintResult(success=False, output=post.output, message=(
189
+ "Pre-existing lint errors — this edit didn't introduce new ones but the file is still broken."))
190
+ return LintResult(success=False, output=(
191
+ "New lint errors introduced by this edit "
192
+ "(pre-existing errors filtered out):\n" + "\n".join(post_lines)
193
+ ))
194
+
195
+ def _lsp_local_only(self) -> bool:
196
+ """True iff wired to a local backend. LSP servers run on the host and
197
+ can't see files inside Docker/Modal/SSH/Daytona sandboxes."""
198
+ env = getattr(self, "env", None) # tests may build via __new__ without __init__
199
+ if env is None:
200
+ return False
201
+ try:
202
+ from tools.environments.local import LocalEnvironment
203
+ except Exception: # noqa: BLE001
204
+ return False
205
+ return isinstance(env, LocalEnvironment)
206
+
207
+ def _lsp_service(self):
208
+ """The active LSPService, or None on a non-local backend / any failure.
209
+ LSP is an enrichment layer and must never break a write."""
210
+ if not self._lsp_local_only():
211
+ return None
212
+ try:
213
+ from agent.lsp import get_service
214
+ return get_service()
215
+ except Exception: # noqa: BLE001
216
+ return None
217
+
218
+ def _lsp_handles_extension(self, ext: str) -> bool:
219
+ """True iff some registered LSP server claims ``ext`` (static registry
220
+ only; safe on remote backends). Decides whether pre-write content is
221
+ worth capturing for the line-shift map."""
222
+ if not ext:
223
+ return False
224
+ try:
225
+ from agent.lsp.servers import SERVERS
226
+ except Exception: # noqa: BLE001
227
+ return False
228
+ return any(ext.lower() in srv.extensions for srv in SERVERS)
229
+
230
+ def _has_ancestor_tsconfig(self, path: str) -> bool:
231
+ """True iff a tsconfig.json exists in ``path``'s directory or any ancestor.
232
+ Host-side walk, local backend only: on a remote backend this answers False so
233
+ the shell linter still runs — never suppress lint on a probe that couldn't answer."""
234
+ if not self._lsp_local_only():
235
+ return False
236
+ try:
237
+ d = os.path.dirname(os.path.abspath(path))
238
+ while not os.path.isfile(os.path.join(d, "tsconfig.json")):
239
+ parent = os.path.dirname(d)
240
+ if parent == d:
241
+ return False
242
+ d = parent
243
+ return True
244
+ except Exception: # noqa: BLE001
245
+ return False
246
+
247
+ def _lsp_call(self, method: str, path: str, default):
248
+ """``svc.<method>(path)`` on the active service; ``default`` when there is
249
+ no service or the call raises (LSP never breaks a write)."""
250
+ svc = self._lsp_service()
251
+ if svc is None:
252
+ return default
253
+ try:
254
+ return getattr(svc, method)(path)
255
+ except Exception: # noqa: BLE001
256
+ return default
257
+
258
+ def _lsp_will_handle(self, path: str) -> bool:
259
+ """True iff the LSP service is active AND ``enabled_for(path)`` (workspace
260
+ detection, disabled-server set, broken-pair short-circuit). Any failure →
261
+ False so the shell linter still runs."""
262
+ return bool(self._lsp_call("enabled_for", path, False))
263
+
264
+ def _snapshot_lsp_baseline(self, path: str) -> None:
265
+ """Capture pre-edit LSP diagnostics so the post-write delta is correct. Silent on failure."""
266
+ self._lsp_call("snapshot_baseline", path, None)
267
+
268
+ def _maybe_lsp_diagnostics(self, path: str, *, pre_content: Optional[str] = None,
269
+ post_content: Optional[str] = None) -> str:
270
+ """Formatted LSP diagnostics introduced by this edit, or "" when LSP is
271
+ unavailable/disabled/clean. With both pre and post content a line-shift map
272
+ remaps baseline diagnostics into post-edit coordinates; otherwise every
273
+ pre-existing diagnostic below an inserted line would look new."""
274
+ svc = self._lsp_service()
275
+ if svc is None or not svc.enabled_for(path):
276
+ return ""
277
+ line_shift = None
278
+ if pre_content is not None and post_content is not None and pre_content != post_content:
279
+ try:
280
+ from agent.lsp.range_shift import build_line_shift
281
+ line_shift = build_line_shift(pre_content, post_content)
282
+ except Exception: # noqa: BLE001
283
+ line_shift = None
284
+ try:
285
+ diagnostics = svc.get_diagnostics_sync(path, delta=True, line_shift=line_shift)
286
+ except Exception: # noqa: BLE001
287
+ return ""
288
+ if not diagnostics:
289
+ return ""
290
+ try:
291
+ from agent.lsp.reporter import report_for_file, truncate
292
+ block = report_for_file(path, diagnostics)
293
+ return truncate("LSP diagnostics introduced by this edit:\n" + block) if block else ""
294
+ except Exception: # noqa: BLE001
295
+ return ""
tools/file_operations_search.py ADDED
@@ -0,0 +1,938 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Content/file search tier for ``tools.file_operations``.
2
+
3
+ ``ShellFileOperations`` inherits ``SearchMixin``; module-level helpers are pure
4
+ (no I/O).
5
+ """
6
+
7
+ import os
8
+ import posixpath
9
+ import re
10
+ import shlex
11
+ import subprocess
12
+ import sys
13
+ import threading
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Any, List, Optional
17
+
18
+ from agent.search_policy import SEARCH_PRUNE_DIR_NAMES
19
+ from tools import interrupt as tool_interrupt
20
+ from tools.file_operations_common import ExecuteResult, SearchMatch, SearchResult
21
+
22
+ _MACOS_TCC_PROTECTED_HOME_DIRS = (
23
+ "Desktop", "Documents", "Downloads", "Library", "Movies", "Music", "Pictures",
24
+ )
25
+
26
+
27
+ def _macos_protected_search_exclusions(
28
+ path: str, *, cwd: Optional[str] = None, home: Optional[str] = None, platform: Optional[str] = None,
29
+ ) -> List[str]:
30
+ """Protected home dirs (relative to ``path``) below a broad macOS search root.
31
+
32
+ Only an ANCESTOR search (``$HOME``, ``/Users``) gets exclusions, so recursive
33
+ tools never trigger unattended TCC prompts; a search rooted inside a
34
+ protected dir stays allowed.
35
+ """
36
+ if (platform or sys.platform) != "darwin":
37
+ return []
38
+ root = Path(path).expanduser()
39
+ if not root.is_absolute():
40
+ root = Path(cwd or os.getcwd()) / root
41
+ root = Path(os.path.normpath(str(root)))
42
+ home_path = Path(os.path.normpath(str(Path(home or Path.home()).expanduser())))
43
+ exclusions: List[str] = []
44
+ for dirname in _MACOS_TCC_PROTECTED_HOME_DIRS:
45
+ try:
46
+ relative = (home_path / dirname).relative_to(root)
47
+ except ValueError:
48
+ continue
49
+ if relative.parts:
50
+ exclusions.append(relative.as_posix())
51
+ return exclusions
52
+
53
+
54
+ # --- Filename-walk admission: one walk per (backend, root) at a time --------------
55
+
56
+ _FILENAME_SEARCH_ADMISSION = threading.Condition()
57
+ _ACTIVE_FILENAME_SEARCH_ROOTS: set[tuple[str, str, str]] = set()
58
+ _FILENAME_SEARCH_WAIT_SECONDS = 0.05
59
+
60
+
61
+ def _normalized_filename_search_root(env: Any, root: str, fallback_cwd: str) -> str:
62
+ """Normalize a filename-walk root without resolving remote paths locally."""
63
+ from tools.environments.local import LocalEnvironment, _IS_WINDOWS, _msys_to_windows_path
64
+
65
+ cwd = getattr(env, "cwd", None) or fallback_cwd
66
+ if isinstance(env, LocalEnvironment):
67
+ if _IS_WINDOWS:
68
+ root = _msys_to_windows_path(root)
69
+ cwd = _msys_to_windows_path(cwd)
70
+ if not os.path.isabs(root):
71
+ root = os.path.join(cwd, root)
72
+ return os.path.normcase(os.path.abspath(os.path.normpath(root)))
73
+ if not posixpath.isabs(root):
74
+ root = posixpath.join(cwd, root)
75
+ return posixpath.normpath(root)
76
+
77
+
78
+ def _filename_search_root_keys(env: Any, roots: List[str], fallback_cwd: str) -> tuple[tuple[str, str, str], ...]:
79
+ """Unique backend/root admission keys in deterministic order."""
80
+ env_type = type(env)
81
+ return tuple(sorted({
82
+ (env_type.__module__, env_type.__qualname__, _normalized_filename_search_root(env, root, fallback_cwd))
83
+ for root in roots}))
84
+
85
+
86
+ def _acquire_filename_search_roots(keys: tuple[tuple[str, str, str], ...]) -> bool:
87
+ """Atomically claim every key, polling for thread-scoped interruption."""
88
+ with _FILENAME_SEARCH_ADMISSION:
89
+ while any(key in _ACTIVE_FILENAME_SEARCH_ROOTS for key in keys):
90
+ if tool_interrupt.is_interrupted():
91
+ return False
92
+ _FILENAME_SEARCH_ADMISSION.wait(_FILENAME_SEARCH_WAIT_SECONDS)
93
+ if tool_interrupt.is_interrupted():
94
+ return False
95
+ if tool_interrupt.is_interrupted():
96
+ return False
97
+ return tool_interrupt.run_if_not_interrupted(lambda: _ACTIVE_FILENAME_SEARCH_ROOTS.update(keys))
98
+
99
+
100
+ def _release_filename_search_roots(keys: tuple[tuple[str, str, str], ...]) -> None:
101
+ """Release a completed walk and leave no idle per-root state behind."""
102
+ with _FILENAME_SEARCH_ADMISSION:
103
+ _ACTIVE_FILENAME_SEARCH_ROOTS.difference_update(keys)
104
+ _FILENAME_SEARCH_ADMISSION.notify_all()
105
+
106
+
107
+ _ADMISSION_INTERRUPTED_ERROR = (
108
+ "File search was interrupted while waiting for another filename "
109
+ "search on the same root. Retry when ready.")
110
+
111
+ _SEARCH_TIMEOUT_MARKER_RE = re.compile(r"\n?\[Command timed out after \d+s\]\s*$")
112
+
113
+
114
+ def _search_stdout_and_limit(result: ExecuteResult) -> tuple[str, Optional[str]]:
115
+ """Return stdout cleaned for parsing and a limit reason for search timeouts."""
116
+ if result.exit_code == 124:
117
+ return _SEARCH_TIMEOUT_MARKER_RE.sub("", result.stdout), "search_timeout"
118
+ return result.stdout, None
119
+
120
+
121
+ # A real rg/grep output line is a whitespace-free path token followed by ``:``
122
+ # (match/count), ``-`` (context), or nothing (files_only); tool diagnostics
123
+ # ("rg: ...", indented carets) never match.
124
+ _SEARCH_OUTPUT_RE = re.compile(r'^([A-Za-z]:)?[^\s:][^\n]*?[:\-]\d|^[^\s:][^\s]*$')
125
+
126
+
127
+ def _split_tool_diagnostics(output: str) -> tuple[str, str]:
128
+ """Separate rg/grep diagnostic lines from real match output → ``(diagnostics, payload)``.
129
+ ``_exec`` merges stderr into stdout; classifying by SHAPE lets the exit-2 guard
130
+ tell a pure failure (no payload) from a partial one (one unreadable file, others
131
+ matched) and guarantees error text is never parsed as a match."""
132
+ diagnostics: list[str] = []
133
+ payload: list[str] = []
134
+ for line in output.split('\n'):
135
+ if not line.strip():
136
+ continue
137
+ # Prefix check first: a match path can contain "-<digit>" (".../pytest-686/...").
138
+ if line.lstrip().startswith(("rg: ", "grep: ")):
139
+ diagnostics.append(line)
140
+ elif line == "--" or _SEARCH_OUTPUT_RE.match(line):
141
+ payload.append(line)
142
+ else:
143
+ diagnostics.append(line)
144
+ return '\n'.join(diagnostics), '\n'.join(payload)
145
+
146
+
147
+ def _parse_search_context_line(line: str) -> tuple[str, int, str] | None:
148
+ """Parse a ``path-line-content`` context line using the RIGHTMOST numeric
149
+ separator (filenames may contain ``-<digits>-`` segments):
150
+ ``dir/file-12-name.py-8-context`` → (``dir/file-12-name.py``, 8, ``context``)."""
151
+ if not line or line == "--":
152
+ return None
153
+ match = None
154
+ for candidate in re.finditer(r'-(\d+)-', line):
155
+ match = candidate
156
+ if match is None or match.start() == 0:
157
+ return None
158
+ return line[:match.start()], int(match.group(1)), line[match.end():]
159
+
160
+
161
+ _REGEX_NEWLINE_ESCAPE_RE = re.compile(r"(?<!\\)(?:\\\\)*\\n")
162
+
163
+
164
+ def _pattern_has_regex_newline(pattern: str) -> bool:
165
+ """True when a content regex wants to match a newline: a literal newline or a
166
+ ``\\n`` escape with an ODD number of backslashes (``\\\\n`` is a literal
167
+ backslash+n and must not count)."""
168
+ return "\n" in pattern or bool(_REGEX_NEWLINE_ESCAPE_RE.search(pattern))
169
+
170
+
171
+ def _is_line_oriented_newline_error(error: Optional[str]) -> bool:
172
+ """Return True for rg's hard error when multiline mode is required."""
173
+ return bool(error) and "literal \"\\n\" is not allowed" in error and "--multiline" in error
174
+
175
+
176
+ def _maybe_warn_line_oriented_newline_pattern(result: SearchResult, pattern: str) -> SearchResult:
177
+ """Attach a newline-regex warning only when search found no usable results."""
178
+ if result.total_count != 0 or not _pattern_has_regex_newline(pattern):
179
+ return result
180
+ if result.error and not _is_line_oriented_newline_error(result.error):
181
+ return result
182
+ result.error = None
183
+ result.warning = (
184
+ "0 results found. Note: search_files content search is line-oriented "
185
+ "and does not run ripgrep with -U/--multiline, so `\\n` in the regex "
186
+ "does not match line breaks. Use context=N to inspect neighboring "
187
+ "lines, or escape as `\\\\n` when searching for a literal backslash+n.")
188
+ return result
189
+
190
+
191
+ # Match lines are "file:lineno:content". Windows paths carry a drive letter
192
+ # ("C:\path"), so a naive split(":") breaks — the regex handles both.
193
+ _MATCH_LINE_RE = re.compile(r'^([A-Za-z]:)?(.*?):(\d+):(.*)$')
194
+
195
+ # Output-mode → engine flag (identical for rg and grep).
196
+ _OUTPUT_MODE_FLAGS = {"files_only": "-l", "count": "-c"}
197
+
198
+
199
+ def _parse_search_output(result, output_mode: str, limit: int, offset: int,
200
+ context: int, warning: Optional[str] = None) -> SearchResult:
201
+ """Parse rg/grep ``| head`` output into a SearchResult (shared by both engines).
202
+ Exit codes: 0=matches, 1=none, 2=error — but both tools return 2 on PARTIAL
203
+ errors (one unreadable file), so an error is surfaced only when exit==2 AND no
204
+ usable payload remains. ``warning`` is attached to files_only/content results."""
205
+ stdout, limit_reason = _search_stdout_and_limit(result)
206
+ diagnostics, payload = _split_tool_diagnostics(stdout)
207
+ if result.exit_code == 2 and not payload.strip():
208
+ error_msg = diagnostics.strip() or result.stdout.strip() or "Search error"
209
+ return SearchResult(error=f"Search failed: {error_msg}", total_count=0)
210
+ lines = [ln for ln in payload.strip().split('\n') if ln]
211
+ if output_mode == "files_only":
212
+ return SearchResult(
213
+ files=lines[offset:offset + limit], total_count=len(lines),
214
+ truncated=bool(limit_reason), limit_reason=limit_reason, warning=warning)
215
+ if output_mode == "count":
216
+ counts = {}
217
+ for line in lines:
218
+ if ':' in line:
219
+ path, n = line.rsplit(':', 1)
220
+ try:
221
+ counts[path] = int(n)
222
+ except ValueError:
223
+ pass
224
+ return SearchResult(
225
+ counts=counts, total_count=sum(counts.values()),
226
+ truncated=bool(limit_reason), limit_reason=limit_reason)
227
+ matches = []
228
+ for line in lines:
229
+ if line == "--":
230
+ continue
231
+ m = _MATCH_LINE_RE.match(line)
232
+ if m:
233
+ matches.append(SearchMatch(
234
+ path=(m.group(1) or '') + m.group(2), line_number=int(m.group(3)), content=m.group(4)[:500],
235
+ ))
236
+ continue
237
+ # Context lines only when requested, to avoid false positives on dashy paths.
238
+ if context > 0:
239
+ parsed = _parse_search_context_line(line)
240
+ if parsed:
241
+ matches.append(SearchMatch(path=parsed[0], line_number=parsed[1], content=parsed[2][:500]))
242
+ total = len(matches)
243
+ return SearchResult(
244
+ matches=matches[offset:offset + limit], total_count=total,
245
+ truncated=total > offset + limit or bool(limit_reason), limit_reason=limit_reason, warning=warning,
246
+ )
247
+
248
+
249
+ def _posix_roots(roots: List[str]) -> bool:
250
+ """Darwin-only: every root is POSIX-shaped (no drive letter / backslash)."""
251
+ return sys.platform == "darwin" and all(
252
+ not re.match(r"^[A-Za-z]:[\\/]", root) and "\\" not in root for root in roots)
253
+
254
+
255
+ class SearchMixin:
256
+ """File-name and content search via rg with find/grep fallbacks. Requires
257
+ ``_exec``, ``_has_command``, ``_expand_path``, ``_escape_shell_arg``,
258
+ ``_escape_native_tool_arg``, ``env``, ``cwd``, ``_command_cache``,
259
+ ``_rg_resolution_cache`` and ``_rg_modified_capability`` from the host class."""
260
+
261
+ # --- rg resolution --------------------------------------------------------
262
+
263
+ def _resolve_command(self, cmd: str) -> Optional[str]:
264
+ """Resolve an executable in the command host's namespace. Ordinary commands
265
+ keep the bool hit/miss cache; rg alone caches successful resolved paths and
266
+ re-probes misses so a mid-session install becomes visible (with off-PATH
267
+ Windows candidates: cargo, scoop, winget)."""
268
+ if cmd != "rg":
269
+ return cmd if self._has_command(cmd) else None
270
+ cached = self._rg_resolution_cache.get(cmd)
271
+ if cached:
272
+ return cached
273
+ result = self._exec("command -v rg 2>/dev/null")
274
+ if result.exit_code == 0 and result.stdout.strip():
275
+ resolved = result.stdout.strip().splitlines()[0]
276
+ if resolved == "yes": # compatibility with old boolean-probe fakes
277
+ resolved = "rg"
278
+ self._rg_resolution_cache[cmd] = resolved
279
+ return resolved
280
+ from tools.environments.local import LocalEnvironment, _IS_WINDOWS
281
+
282
+ if _IS_WINDOWS and isinstance(self.env, LocalEnvironment):
283
+ user_profile = os.environ.get("USERPROFILE") or str(Path.home())
284
+ local_app_data = os.environ.get("LOCALAPPDATA")
285
+ scoop = os.environ.get("SCOOP") or os.path.join(user_profile, "scoop")
286
+ candidates = [
287
+ os.path.join(user_profile, ".cargo", "bin", "rg.exe"),
288
+ os.path.join(scoop, "shims", "rg.exe"),
289
+ ]
290
+ if local_app_data:
291
+ candidates.append(os.path.join(local_app_data, "Microsoft", "WinGet", "Links", "rg.exe"))
292
+ for candidate in candidates:
293
+ if os.path.isfile(candidate):
294
+ resolved = candidate.replace("\\", "/")
295
+ self._rg_resolution_cache[cmd] = resolved
296
+ return resolved
297
+ return None
298
+
299
+ _RG_VERSION_RE = re.compile(
300
+ r"(?m)^ripgrep\s+((?:0|[1-9]\d*))\."
301
+ r"(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)"
302
+ r"(?:-(?:(?:0|[1-9]\d*)|(?:[0-9A-Za-z-]*[A-Za-z-]"
303
+ r"[0-9A-Za-z-]*))(?:\.(?:(?:0|[1-9]\d*)|"
304
+ r"(?:[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)))*)?"
305
+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
306
+ r"(?:\s+\(rev [^)]+\))?\s*$")
307
+
308
+ def _modified_rg_capability_error(self, executable: str) -> Optional[str]:
309
+ """Cached actionable error unless rg can sort exactly (full SemVer, >= 14)."""
310
+ if executable in self._rg_modified_capability:
311
+ return self._rg_modified_capability[executable]
312
+ result = self._exec(f"{self._quote_executable(executable)} --version", timeout=10)
313
+ match = self._RG_VERSION_RE.search(result.stdout or "")
314
+ if result.exit_code == 0 and match and int(match.group(1)) >= 14:
315
+ error = None
316
+ else:
317
+ error = ("Exact modification-time order requires ripgrep 14 or newer; "
318
+ "upgrade ripgrep or use order='discovery'.")
319
+ self._rg_modified_capability[executable] = error
320
+ return error
321
+
322
+ # --- native rg transport (local POSIX) --------------------------------------
323
+
324
+ def _run_rg_native(self, argv: List[str], fetch_limit: int, timeout: int,
325
+ merge_stderr: bool = False) -> ExecuteResult:
326
+ """Run ``argv`` (shell-quoted rg words) natively and stop reading after
327
+ ``fetch_limit`` lines — the ``| head -n`` of the shell pipeline without the
328
+ two bash spawns. ``shlex.split`` undoes the escaping the builders apply for
329
+ the shell path, so both transports see identical arguments. Exit code and
330
+ stdout follow the shell contract (rg 0/1/2; 124 on timeout with partial
331
+ output; 130 on interrupt), so ``_parse_search_output`` is shared. Once the
332
+ bound is reached rg is killed like ``head`` closing the pipe would.
333
+ ``merge_stderr`` mirrors the shell path's stderr handling: merged for content
334
+ search (diagnostics feed the error message), discarded (``2>/dev/null``) for
335
+ file lists and probes."""
336
+ from tools.environments.local import _kill_process_group_posix, _make_run_env
337
+ cwd = getattr(self.env, "cwd", None) or self.cwd
338
+ args = shlex.split(" ".join(argv))
339
+ try:
340
+ proc = subprocess.Popen(
341
+ args, cwd=cwd, env=_make_run_env(self.env.env), stdin=subprocess.DEVNULL,
342
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT if merge_stderr else subprocess.DEVNULL,
343
+ start_new_session=True)
344
+ except OSError as exc:
345
+ return ExecuteResult(stdout=f"rg: {exc}", exit_code=2)
346
+
347
+ # Drain on a thread so a silent rg (huge tree, no hits yet) cannot pin the
348
+ # caller past the deadline or past a /stop; the waiter below owns both.
349
+ lines: List[bytes] = []
350
+ bounded = threading.Event()
351
+
352
+ def _drain() -> None:
353
+ for raw in proc.stdout:
354
+ lines.append(raw)
355
+ if len(lines) >= fetch_limit:
356
+ bounded.set()
357
+ break
358
+
359
+ drainer = threading.Thread(target=_drain, daemon=True)
360
+ drainer.start()
361
+ deadline = time.monotonic() + timeout
362
+ exit_code: Optional[int] = None
363
+ while True:
364
+ drainer.join(0.05)
365
+ if not drainer.is_alive() or bounded.is_set():
366
+ break
367
+ if tool_interrupt.is_interrupted():
368
+ exit_code = 130
369
+ break
370
+ if time.monotonic() > deadline:
371
+ exit_code = 124
372
+ break
373
+ if proc.poll() is None:
374
+ _kill_process_group_posix(proc) # native lane is POSIX-only (gate above)
375
+ proc.wait()
376
+ drainer.join()
377
+ proc.stdout.close()
378
+ stdout = b"".join(lines).decode("utf-8", errors="replace")
379
+ if exit_code == 124:
380
+ return ExecuteResult(stdout=stdout + f"\n[Command timed out after {timeout}s]", exit_code=124)
381
+ if exit_code == 130:
382
+ return ExecuteResult(stdout=stdout + "\n[Command interrupted]", exit_code=130)
383
+ # A killed-at-bound rg reports a signal (negative returncode); head would have
384
+ # left the pipeline at 0 unless rg itself already failed.
385
+ return ExecuteResult(stdout=stdout, exit_code=0 if bounded.is_set() else proc.returncode)
386
+
387
+ def _run_rg_bounded(self, words: List[str], fetch_limit: int, timeout: int, *,
388
+ merge_stderr: bool = False, native_ok: bool = True,
389
+ shell_prefix: str = "") -> ExecuteResult:
390
+ """Run an rg command (shell-quoted words) and keep the first ``fetch_limit``
391
+ lines: natively on a local POSIX host, else through the backend shell as
392
+ ``<prefix><words> | head -n N``. ``native_ok=False`` keeps a form the native
393
+ lane cannot express (the multi-root ``cd`` prefix); ``shell_prefix`` is shell-only."""
394
+ if native_ok and self._native_read_enabled():
395
+ return self._run_rg_native(words, fetch_limit, timeout, merge_stderr=merge_stderr)
396
+ stderr = "" if merge_stderr else " 2>/dev/null"
397
+ return self._exec(f"{shell_prefix}{' '.join(words)}{stderr} | head -n {fetch_limit}", timeout=timeout)
398
+
399
+ def _quote_executable(self, executable: str) -> str:
400
+ """Quote an executable without leaking controller path semantics."""
401
+ if re.fullmatch(r"[A-Za-z0-9_.-]+", executable):
402
+ return executable
403
+ from tools.environments.local import LocalEnvironment
404
+
405
+ if isinstance(self.env, LocalEnvironment):
406
+ return self._escape_native_tool_arg(executable)
407
+ return "'" + executable.replace("'", "'\"'\"'") + "'"
408
+
409
+ # --- macOS protected-folder exclusions --------------------------------------
410
+
411
+ def _macos_search_exclusions(self, path: str) -> List[str]:
412
+ """Protected descendants to prune for this search root, if any. Gated on
413
+ ``env.is_local``: ``sys.platform``/``_HOME`` describe the CONTROLLER, but the
414
+ search runs on ``env``'s host. Envs without the flag default to local
415
+ semantics; pruning is a warning-carrying skip, never data loss."""
416
+ env = getattr(self, "env", None)
417
+ if env is not None and getattr(env, "is_local", True) is False:
418
+ return []
419
+ from tools import file_operations as _fo # lazy: _HOME is monkeypatched there
420
+ cwd = getattr(self.env, "cwd", None) or self.cwd
421
+ return _macos_protected_search_exclusions(path, cwd=cwd, home=_fo._HOME, platform=sys.platform)
422
+
423
+ def _protected_prune_paths(self, path: str) -> List[str]:
424
+ """Absolute-ish protected paths for find's ``-path ... -prune``."""
425
+ return [os.path.normpath(os.path.join(path, item)) for item in self._macos_search_exclusions(path)]
426
+
427
+ def _effective_macos_search_exclusions(self, roots: List[str]) -> List[tuple[str, str, str]]:
428
+ """Unique ``(root, relative, absolute)`` exclusions across ``roots``, never
429
+ pruning a root the caller chose explicitly."""
430
+ cwd = getattr(self.env, "cwd", None) or self.cwd
431
+ use_posix_paths = _posix_roots(roots)
432
+
433
+ def normalized(root: str) -> str:
434
+ if use_posix_paths:
435
+ return posixpath.normpath(root if posixpath.isabs(root) else posixpath.join(cwd, root))
436
+ return os.path.normcase(os.path.abspath(os.path.normpath(root)))
437
+
438
+ normalized_roots = [normalized(root) for root in roots]
439
+ explicit_roots = set(normalized_roots)
440
+ seen = set()
441
+ effective = []
442
+ for root, normalized_root in zip(roots, normalized_roots):
443
+ for relative in self._macos_search_exclusions(root):
444
+ if use_posix_paths:
445
+ absolute = key = posixpath.normpath(posixpath.join(normalized_root, relative))
446
+ else:
447
+ absolute = os.path.normpath(os.path.join(root, relative))
448
+ key = os.path.normcase(os.path.abspath(absolute))
449
+ if key in explicit_roots or key in seen:
450
+ continue
451
+ seen.add(key)
452
+ effective.append((root, relative, absolute))
453
+ return effective
454
+
455
+ @staticmethod
456
+ def _macos_protected_search_warning(paths: List[str]) -> str:
457
+ skipped = ", ".join(os.path.basename(item) for item in paths)
458
+ return ("Skipped macOS protected folders during broad search to avoid "
459
+ f"an unattended privacy prompt: {skipped}. Search a protected "
460
+ "folder directly when access is intentional.")
461
+
462
+ def _prune_expr(self, protected_paths: List[str]) -> str:
463
+ """find ``\\( -path A -o -path B \\) -prune`` clause for the protected dirs."""
464
+ terms = " -o ".join(f"-path {self._escape_shell_arg(item)}" for item in protected_paths)
465
+ return f"\\( {terms} \\) -prune"
466
+
467
+ def _rg_exclusion_globs(self, path: str) -> List[str]:
468
+ """``--glob '!<dir>/**'`` pairs excluding protected dirs from an rg run."""
469
+ out: List[str] = []
470
+ for item in self._macos_search_exclusions(path):
471
+ out.extend(["--glob", self._escape_shell_arg(f"!{item}/**")])
472
+ return out
473
+
474
+ def _path_exists_probe(self, path: str) -> str:
475
+ """Stdout of the existence probe: contains "exists" or "not_found"."""
476
+ if self._native_read_enabled():
477
+ full = path if os.path.isabs(path) else os.path.join(getattr(self.env, "cwd", None) or self.cwd, path)
478
+ return "exists" if os.path.exists(full) else "not_found"
479
+ return self._exec(f"test -e {self._escape_shell_arg(path)} && echo exists || echo not_found").stdout
480
+
481
+ def _dispatch_search(self, pattern: str, path: str, target: str,
482
+ file_glob: Optional[str], limit: int, offset: int,
483
+ output_mode: str, context: int, order: str = "discovery") -> SearchResult:
484
+ if target == "files":
485
+ return self._search_files(pattern, path, limit, offset, order)
486
+ return self._search_content(pattern, path, file_glob, limit, offset, output_mode, context)
487
+
488
+ def _path_not_found_result(self, path: str) -> SearchResult:
489
+ """Error result for a missing search root, with nearby-entry suggestions."""
490
+ parent = os.path.dirname(path) or "."
491
+ basename_query = os.path.basename(path)
492
+ hint_parts = [f"Path not found: {path}"]
493
+ parent_check = self._exec(f"test -d {self._escape_shell_arg(parent)} && echo yes || echo no")
494
+ if "yes" in parent_check.stdout and basename_query:
495
+ ls_result = self._exec(f"ls -1 {self._escape_shell_arg(parent)} 2>/dev/null | head -20")
496
+ if ls_result.exit_code == 0 and ls_result.stdout.strip():
497
+ lq = basename_query.lower()
498
+ candidates = [
499
+ os.path.join(parent, e) for e in ls_result.stdout.strip().split('\n')
500
+ if e and (lq in e.lower() or e.lower() in lq or e.lower().startswith(lq[:3]))]
501
+ if candidates:
502
+ hint_parts.append("Similar paths: " + ", ".join(candidates[:5]))
503
+ return SearchResult(error=". ".join(hint_parts), total_count=0)
504
+
505
+ def _try_multi_path_search(self, pattern: str, path: str, target: str,
506
+ file_glob: Optional[str], limit: int, offset: int,
507
+ output_mode: str, context: int,
508
+ order: str = "discovery") -> Optional[SearchResult]:
509
+ """Recover a not-found ``path`` that is really several paths in one string.
510
+ Commas explicitly delimit paths (internal spaces preserved); without commas
511
+ split on whitespace. Search every existing part, merge, and note skipped
512
+ parts. None when it doesn't look like a multi-path string."""
513
+ if "," in path:
514
+ parts = [part.strip() for part in path.split(",") if part.strip()]
515
+ else:
516
+ parts = path.split()
517
+ if len(parts) < 2:
518
+ return None
519
+ existing, missing = [], []
520
+ for p in parts:
521
+ expanded = self._expand_path(p)
522
+ (existing if "exists" in self._path_exists_probe(expanded) else missing).append(expanded)
523
+ if not existing:
524
+ return None
525
+ if target == "files":
526
+ # One global traversal across roots so modified ordering and pagination
527
+ # are exact; root admission wraps the actual rg/find invocation.
528
+ merged = self._search_files(pattern, existing, limit, offset, order)
529
+ else:
530
+ merged = SearchResult()
531
+ for root in existing:
532
+ sub = self._search_content(pattern, root, file_glob, limit, offset, output_mode, context)
533
+ if sub.error:
534
+ return sub
535
+ merged.matches.extend(sub.matches)
536
+ merged.files.extend(sub.files)
537
+ merged.counts.update(sub.counts)
538
+ merged.total_count += sub.total_count
539
+ merged.truncated = merged.truncated or sub.truncated
540
+ merged.matches = merged.matches[:limit]
541
+ merged.files = merged.files[:limit]
542
+ note = f"path contained {len(parts)} entries; searched {len(existing)} that exist"
543
+ if missing:
544
+ note += "; skipped missing: " + ", ".join(missing[:3])
545
+ if len(missing) > 3:
546
+ note += f" (+{len(missing) - 3} more)"
547
+ warning_parts = [note]
548
+ if not merged.error:
549
+ protected_paths = [absolute for _r, _rel, absolute in self._effective_macos_search_exclusions(existing)]
550
+ if protected_paths:
551
+ warning_parts.append(self._macos_protected_search_warning(protected_paths))
552
+ merged.warning = " ".join(warning_parts)
553
+ return merged
554
+
555
+ def _search_prune_glob_args(self) -> str:
556
+ """rg globs pruning known heavyweight recursive subtrees. Both forms are
557
+ needed: globs are relative to each rg root, so ``**/name/**`` alone misses an
558
+ explicitly selected ``name/`` root. Names come from the shared scan policy —
559
+ no second search-only list."""
560
+ globs = []
561
+ for dirname in sorted(SEARCH_PRUNE_DIR_NAMES):
562
+ for prefix in ("", "**/"):
563
+ globs.extend(("--glob", self._escape_shell_arg(f"!{prefix}{dirname}/**")))
564
+ return " ".join(globs)
565
+
566
+ # (rg flags, message template) probes for a 0-match content search, in order.
567
+ # The fixed-string probe only runs when the pattern has regex metacharacters.
568
+ _ZERO_MATCH_PROBES = (
569
+ ("-i", "0 exact matches, but {total} case-insensitive match(es) in {n} file(s): "
570
+ "{paths} — the pattern's casing may be wrong."),
571
+ # rg skips dotdirs and .gitignore'd files by default; say so instead of a bare zero.
572
+ ("--hidden --no-ignore", "0 matches in visible files, but {total} match(es) in {n} "
573
+ "hidden or gitignored file(s): {paths} — these are excluded by default."),
574
+ ("-F", "0 regex matches, but {total} literal match(es) in {n} file(s): {paths} — the "
575
+ "pattern contains regex metacharacters that likely need escaping "
576
+ "(or pass a simpler substring)."),
577
+ )
578
+
579
+ def _zero_match_probe(self, pattern: str, path: str, file_glob: Optional[str]) -> Optional[str]:
580
+ """Steering hint for a 0-match content search, or None: a bare zero gives the
581
+ model nothing to act on, so run cheap count-only rg probes (case-insensitive,
582
+ hidden/ignored, fixed-string) and report the first that hits."""
583
+ rg_executable = self._resolve_command('rg')
584
+ if not rg_executable:
585
+ return None
586
+ rg = self._quote_executable(rg_executable)
587
+ has_meta = bool(re.search(r"[.\[\](){}?*+^$\\|]", pattern))
588
+ glob_expr = f" --glob {self._escape_shell_arg(file_glob)}" if file_glob else ""
589
+ for flags, template in self._ZERO_MATCH_PROBES:
590
+ if flags == "-F" and not has_meta:
591
+ continue
592
+ # The hidden/ignored probe keeps --no-ignore so project-local ignored
593
+ # files stay diagnosable, but prunes heavyweight trees before rg recurses.
594
+ if flags.startswith("--hidden"):
595
+ glob_expr_probe = f"{glob_expr} {self._search_prune_glob_args()}"
596
+ else:
597
+ glob_expr_probe = glob_expr
598
+ probe_words = [rg, flags, "--count-matches", glob_expr_probe,
599
+ self._escape_shell_arg(pattern), self._escape_native_tool_arg(path)]
600
+ probe = self._run_rg_bounded(probe_words, 50, timeout=30)
601
+ total, per_file = 0, []
602
+ for line in (probe.stdout or "").strip().splitlines():
603
+ p, _sep, n = line.rpartition(":")
604
+ if n.isdigit():
605
+ total += int(n)
606
+ per_file.append(p)
607
+ if total > 0:
608
+ extra = len(per_file) - 5
609
+ paths = ", ".join(per_file[:5]) + (f" (+{extra} more)" if extra > 0 else "")
610
+ return template.format(total=total, n=len(per_file), paths=paths)
611
+ return None
612
+
613
+ def _is_broad_local_search_root(self, path: str) -> bool:
614
+ """Whether a no-rg LOCAL root (filesystem root, $HOME or an ancestor of it) is
615
+ unsafe for recursive find. Controller paths never classify remotes."""
616
+ from tools.environments.local import LocalEnvironment, _IS_WINDOWS, _msys_to_windows_path
617
+
618
+ if not isinstance(self.env, LocalEnvironment):
619
+ return False
620
+
621
+ def normalized(value: str) -> str:
622
+ if _IS_WINDOWS:
623
+ value = _msys_to_windows_path(value).replace("\\", "/")
624
+ if not os.path.isabs(value):
625
+ value = os.path.join(getattr(self.env, "cwd", None) or self.cwd, value)
626
+ return os.path.normcase(os.path.abspath(value))
627
+
628
+ from tools import file_operations as _fo # lazy: _HOME is monkeypatched there
629
+ root = normalized(path)
630
+ home = normalized(_fo._HOME)
631
+ drive = os.path.splitdrive(root)[0]
632
+ anchor = drive + os.sep if drive else os.path.abspath(os.sep)
633
+ if root == os.path.normcase(anchor):
634
+ return True
635
+ try:
636
+ common = os.path.commonpath([root, home])
637
+ except ValueError:
638
+ return False
639
+ return root == home or common == root
640
+
641
+ def _search_files(self, pattern: str, path: str | List[str], limit: int, offset: int,
642
+ order: str = "discovery") -> SearchResult:
643
+ """Search for files by name (glob-like) across one or more roots: rg --files,
644
+ else a bounded find. ``order``: "discovery" (fast, bounded) or "modified"
645
+ (exact global newest-first; needs rg 14+ or GNU find)."""
646
+ search_pattern = pattern if (not pattern.startswith('**/') and '/' not in pattern) \
647
+ else pattern.split('/')[-1]
648
+ roots = [path] if isinstance(path, str) else path
649
+ if not roots:
650
+ return SearchResult(error="File search requires at least one search root in 'path'.")
651
+
652
+ # Prefer ripgrep: bounded parallel traversal with ignore semantics. Resolve
653
+ # the engine and exact-order capability BEFORE admission so a queued request
654
+ # does not occupy a root while doing command discovery.
655
+ if self._has_command("rg"):
656
+ rg_executable = self._resolve_command("rg") or "rg"
657
+ if order == "modified":
658
+ capability_error = self._modified_rg_capability_error(rg_executable)
659
+ if capability_error:
660
+ return SearchResult(error=capability_error)
661
+ keys = _filename_search_root_keys(self.env, roots, self.cwd)
662
+ if not _acquire_filename_search_roots(keys):
663
+ return SearchResult(error=_ADMISSION_INTERRUPTED_ERROR)
664
+ try:
665
+ return self._search_files_rg(search_pattern, path, limit, offset, order,
666
+ rg_executable=rg_executable)
667
+ finally:
668
+ _release_filename_search_roots(keys)
669
+
670
+ # A local find rooted at/above $HOME or a filesystem root can take minutes and
671
+ # prompt on protected paths: refuse before invoking find.
672
+ if any(self._is_broad_local_search_root(root) for root in roots):
673
+ return SearchResult(error=(
674
+ "Broad local file search without ripgrep is disabled because "
675
+ "find cannot keep this traversal safely bounded. Install "
676
+ "ripgrep or search a narrower directory."))
677
+ if not self._has_command("find"):
678
+ return SearchResult(
679
+ error="File search requires 'rg' (ripgrep) or 'find'. "
680
+ "Install ripgrep for best results: "
681
+ "https://github.com/BurntSushi/ripgrep#installation")
682
+
683
+ # Prune hidden descendant dirs (and hidden files, matching rg's default) while
684
+ # still allowing an explicitly selected hidden root; dash-prefixed roots get
685
+ # ``./`` so find doesn't parse them as options.
686
+ find_roots = [f"./{root}" if root.startswith("-") else root for root in roots]
687
+ q_roots = [self._escape_shell_arg(root) for root in find_roots]
688
+ root_exemptions = "".join(f" ! -path {root}" for root in q_roots)
689
+ hidden_prune = f" \\( -type d -name '.*'{root_exemptions} \\) -prune -o"
690
+ protected_paths = [absolute for _r, _rel, absolute in self._effective_macos_search_exclusions(roots)]
691
+ protected_prune = f" {self._prune_expr(protected_paths)} -o" if protected_paths else ""
692
+ fetch_limit = offset + limit + 1
693
+ base = (f"find {' '.join(q_roots)}{protected_prune}{hidden_prune} -type f "
694
+ f"! -name '.*' -name {self._escape_shell_arg(search_pattern)}")
695
+ if order == "modified":
696
+ cmd = "set -o pipefail; " + base + f" -printf '%T@ %p\\n' 2>/dev/null | sort -rn | head -n {fetch_limit}"
697
+ else:
698
+ cmd = "set -o pipefail; " + base + f" -print 2>/dev/null | head -n {fetch_limit}"
699
+
700
+ keys = _filename_search_root_keys(self.env, roots, self.cwd)
701
+ if not _acquire_filename_search_roots(keys):
702
+ return SearchResult(error=_ADMISSION_INTERRUPTED_ERROR)
703
+ try:
704
+ result = self._exec(cmd, timeout=60)
705
+ finally:
706
+ _release_filename_search_roots(keys)
707
+ stdout, limit_reason = _search_stdout_and_limit(result)
708
+
709
+ # Parse BEFORE classifying exit 141: under pipefail a bounded producer gets
710
+ # SIGPIPE when head closes after fetch_limit rows — benign only when the
711
+ # payload proves the bound was reached; a shorter payload is a hard failure.
712
+ raw_files: List[str] = []
713
+ for line in stdout.splitlines():
714
+ if order == "modified":
715
+ parts = line.split(" ", 1)
716
+ if len(parts) != 2 or not parts[0].replace(".", "", 1).isdigit():
717
+ continue
718
+ raw_files.append(parts[1])
719
+ elif line:
720
+ raw_files.append(line)
721
+ bounded_sigpipe = result.exit_code == 141 and len(raw_files) >= fetch_limit
722
+ if result.exit_code not in {0, 124} and not bounded_sigpipe:
723
+ if order == "modified":
724
+ return SearchResult(error=(
725
+ "Exact modification-time order requires GNU find with "
726
+ "-printf support; install ripgrep 14+ or use order='discovery'."))
727
+ return SearchResult(error="File search failed while running bounded find traversal.")
728
+
729
+ from tools.environments.local import LocalEnvironment, _IS_WINDOWS, _msys_to_windows_path
730
+ if _IS_WINDOWS and isinstance(self.env, LocalEnvironment):
731
+ raw_files = [_msys_to_windows_path(file_path) for file_path in raw_files]
732
+ return SearchResult(
733
+ files=raw_files[offset:offset + limit], total_count=len(raw_files),
734
+ truncated=len(raw_files) > offset + limit or bool(limit_reason), limit_reason=limit_reason)
735
+
736
+ def _search_files_rg(self, pattern: str, path: str | List[str], limit: int, offset: int,
737
+ order: str = "discovery", rg_executable: Optional[str] = None) -> SearchResult:
738
+ """File-name search via ``rg --files`` (respects .gitignore, skips hidden dirs,
739
+ parallel walk). Discovery order stays bounded and fast; exact modification-time
740
+ ordering is explicit because it scans globally."""
741
+ # Wrap bare names so -g matches at any depth (equivalent to find -name).
742
+ glob_pattern = f"*{pattern}" if ('/' not in pattern and not pattern.startswith('*')) else pattern
743
+ roots = [path] if isinstance(path, str) else path
744
+ fetch_limit = limit + offset + 1
745
+ effective_exclusions = self._effective_macos_search_exclusions(roots)
746
+ scoped_common = None
747
+ command_roots = roots
748
+ if len(roots) > 1 and effective_exclusions and _posix_roots(roots):
749
+ # Several roots: rg globs are root-relative, so cd to the common ancestor
750
+ # and express roots + exclusions relative to it.
751
+ cwd = getattr(self.env, "cwd", None) or self.cwd
752
+ absolute_roots = [
753
+ posixpath.normpath(root if posixpath.isabs(root) else posixpath.join(cwd, root))
754
+ for root in roots]
755
+ scoped_common = posixpath.commonpath(absolute_roots)
756
+ command_roots = [posixpath.relpath(root, scoped_common) for root in absolute_roots]
757
+ exclusion_terms = [
758
+ f"--glob {self._escape_shell_arg(f'!{posixpath.relpath(absolute, scoped_common)}/**')}"
759
+ for _r, _rel, absolute in effective_exclusions]
760
+ else:
761
+ exclusion_terms = [
762
+ f"--glob {self._escape_shell_arg(f'!{relative}/**')}"
763
+ for _r, relative, _abs in effective_exclusions]
764
+ exclusion_globs = " ".join(dict.fromkeys(exclusion_terms))
765
+ exclusion_args = f" {exclusion_globs}" if exclusion_globs else ""
766
+ rg_executable = rg_executable or self._resolve_command("rg")
767
+ if not rg_executable:
768
+ return SearchResult(error="File search requires ripgrep (rg).")
769
+ if order == "modified":
770
+ capability_error = self._modified_rg_capability_error(rg_executable)
771
+ if capability_error:
772
+ return SearchResult(error=capability_error)
773
+ rg = self._quote_executable(rg_executable)
774
+ sort_arg = " --sortr=modified" if order == "modified" else ""
775
+ root_args = " ".join(self._escape_native_tool_arg(root) for root in command_roots)
776
+ cd_prefix = f"cd {self._escape_shell_arg(scoped_common)} && " if scoped_common else ""
777
+ # ``--`` terminates options so a dash-prefixed root is never parsed as a flag.
778
+ rg_cmd = (f"{rg} --files{sort_arg} -g {self._escape_shell_arg(glob_pattern)}"
779
+ f"{exclusion_args} -- {root_args}")
780
+ result = self._run_rg_bounded([rg_cmd], fetch_limit, timeout=60, native_ok=not scoped_common,
781
+ shell_prefix=f"set -o pipefail; {cd_prefix}")
782
+ stdout, limit_reason = _search_stdout_and_limit(result)
783
+ all_files = [f for f in stdout.splitlines() if f]
784
+ if scoped_common:
785
+ all_files = [
786
+ f if posixpath.isabs(f) else posixpath.normpath(posixpath.join(scoped_common, f))
787
+ for f in all_files]
788
+ bounded_sigpipe = result.exit_code == 141 and len(all_files) >= fetch_limit
789
+ if result.exit_code not in {0, 1, 124} and not bounded_sigpipe:
790
+ if order == "modified":
791
+ return SearchResult(error=(
792
+ "Exact modification-time order failed; ripgrep 14+ is "
793
+ "required. Upgrade ripgrep or use order='discovery'."))
794
+ return SearchResult(error="File search failed while running ripgrep.")
795
+ return SearchResult(
796
+ files=all_files[offset:offset + limit], total_count=len(all_files),
797
+ truncated=len(all_files) > offset + limit or bool(limit_reason), limit_reason=limit_reason)
798
+
799
+ def _search_content(self, pattern: str, path: str, file_glob: Optional[str],
800
+ limit: int, offset: int, output_mode: str, context: int) -> SearchResult:
801
+ """Content search: rg, else grep; attaches zero-match steering hints."""
802
+ used_rg = self._has_command('rg')
803
+ if used_rg:
804
+ result = self._search_with_rg(pattern, path, file_glob, limit, offset, output_mode, context,
805
+ rg_executable=self._resolve_command("rg") or "rg")
806
+ elif self._has_command('grep'):
807
+ result = self._search_with_grep(pattern, path, file_glob, limit, offset, output_mode, context)
808
+ else:
809
+ return SearchResult(
810
+ error="Content search requires ripgrep (rg) or grep. "
811
+ "Install ripgrep: https://github.com/BurntSushi/ripgrep#installation")
812
+ if (not result.error and result.total_count == 0
813
+ and not result.matches and not result.files and not result.counts):
814
+ try:
815
+ hint = self._zero_match_probe(pattern, path, file_glob)
816
+ except Exception:
817
+ hint = None
818
+ if hint:
819
+ result.warning = hint if not result.warning else f"{result.warning} {hint}"
820
+ # rg auto-enables --multiline for \n patterns, so the line-oriented
821
+ # explanation only applies to the grep fallback.
822
+ if used_rg:
823
+ return result
824
+ return _maybe_warn_line_oriented_newline_pattern(result, pattern)
825
+
826
+ def _run_search_pipeline(self, cmd_parts: List[str], output_mode: str, limit: int,
827
+ offset: int, context: int, warning: Optional[str] = None,
828
+ line_cap: bool = False) -> SearchResult:
829
+ """Run ``cmd_parts | head -n <fetch_limit>`` under pipefail and parse. Extra
830
+ rows report the true total (context mode also emits "--" separators, so
831
+ grab 200 more). pipefail keeps the engine's exit 2 alive across ``| head``
832
+ (a truncating head makes rg exit 0 / grep 141, which the ==2 guard ignores).
833
+ ``line_cap`` appends ``| cut -c1-2000`` for engines without --max-columns
834
+ (grep): bounds giant single-line matches at the pipe layer; skipped for
835
+ files_only/count where lines are paths/counts."""
836
+ fetch_limit = limit + offset + (200 if context > 0 else 0)
837
+ if line_cap: # grep/find pipelines: shell only, with the column cap
838
+ parts = cmd_parts + ["|", "head", "-n", str(fetch_limit)]
839
+ if output_mode not in ("files_only", "count"):
840
+ parts += ["|", "cut", "-c1-2000"]
841
+ result = self._exec("set -o pipefail; " + " ".join(parts), timeout=60)
842
+ else:
843
+ result = self._run_rg_bounded(cmd_parts, fetch_limit, timeout=60, merge_stderr=True,
844
+ shell_prefix="set -o pipefail; ")
845
+ return _parse_search_output(result, output_mode, limit, offset, context, warning=warning)
846
+
847
+ def _search_with_rg(self, pattern: str, path: str, file_glob: Optional[str],
848
+ limit: int, offset: int, output_mode: str, context: int,
849
+ rg_executable: Optional[str] = None) -> SearchResult:
850
+ """Search using ripgrep."""
851
+ rg_executable = rg_executable or self._resolve_command("rg")
852
+ if not rg_executable:
853
+ return SearchResult(error="Content search requires ripgrep (rg).")
854
+ cmd_parts = [self._quote_executable(rg_executable), "--line-number", "--no-heading", "--with-filename"]
855
+ # Giant-single-line containment (cline#13525): a match inside a multi-MB
856
+ # single-line dump makes rg emit the ENTIRE line (``head -n`` counts lines).
857
+ # --max-columns bounds each printed line at the rg layer; --max-columns-preview
858
+ # keeps a truncated prefix so the model still sees the hit. 2000 cols exceeds
859
+ # the 500-char content clamp, so nothing previously visible is lost.
860
+ if output_mode not in ("files_only", "count"):
861
+ cmd_parts.extend(["--max-columns", "2000", "--max-columns-preview"])
862
+ # A regex \n hard-errors in line-oriented mode; enable -U up front and say so.
863
+ multiline = _pattern_has_regex_newline(pattern)
864
+ if multiline:
865
+ cmd_parts.append("--multiline")
866
+ if context > 0:
867
+ cmd_parts.extend(["-C", str(context)])
868
+ cmd_parts.extend(self._rg_exclusion_globs(path))
869
+ if file_glob:
870
+ cmd_parts.extend(["--glob", self._escape_shell_arg(file_glob)])
871
+ if output_mode in _OUTPUT_MODE_FLAGS:
872
+ cmd_parts.append(_OUTPUT_MODE_FLAGS[output_mode])
873
+ cmd_parts.append(self._escape_shell_arg(pattern))
874
+ # rg is a native Windows binary (winget/cargo/choco): needs C:/... not MSYS /c/...
875
+ cmd_parts.append(self._escape_native_tool_arg(path))
876
+ ml_note = (
877
+ "Pattern contains \\n — multiline mode (-U) was enabled automatically "
878
+ "so the regex can match across line boundaries."
879
+ ) if multiline else None
880
+ return self._run_search_pipeline(cmd_parts, output_mode, limit, offset, context, warning=ml_note)
881
+
882
+ def _grep_cmd(self, head: List[str], pattern: str, output_mode: str, context: int,
883
+ file_glob: Optional[str] = None) -> List[str]:
884
+ """``head`` + context/include/mode flags + quoted pattern (argument order is fixed)."""
885
+ parts = list(head)
886
+ if context > 0:
887
+ parts.extend(["-C", str(context)])
888
+ if file_glob:
889
+ parts.extend(["--include", self._escape_shell_arg(file_glob)])
890
+ if output_mode in _OUTPUT_MODE_FLAGS:
891
+ parts.append(_OUTPUT_MODE_FLAGS[output_mode])
892
+ parts.append(self._escape_shell_arg(pattern))
893
+ return parts
894
+
895
+ def _search_with_grep(self, pattern: str, path: str, file_glob: Optional[str],
896
+ limit: int, offset: int, output_mode: str, context: int) -> SearchResult:
897
+ """Fallback search using grep."""
898
+ # grep's --exclude-dir matches BASENAMES anywhere, so it can't express "only
899
+ # the home-level Downloads"; route pruning through find's path-scoped -prune.
900
+ protected_paths = self._protected_prune_paths(path)
901
+ if protected_paths:
902
+ return self._search_with_grep_pruned(
903
+ pattern, path, file_glob, limit, offset, output_mode, context, protected_paths)
904
+ # -H forces filenames; -E matches rg regex behavior; --exclude-dir='.*'
905
+ # mirrors rg's hidden-dir default (.git/, .hub/index-cache/, ...).
906
+ cmd_parts = self._grep_cmd(["grep", "-rnHE", "--exclude-dir='.*'"], pattern, output_mode, context, file_glob)
907
+ # --exclude-dir applies to the root too, so "." would be excluded by '.*';
908
+ # anchor relative paths at the shell's live $PWD.
909
+ is_absolute = path.startswith(("/", "\\\\")) or bool(re.match(r"^[A-Za-z]:[\\/]", path))
910
+ if is_absolute:
911
+ search_root = self._escape_shell_arg(path)
912
+ else:
913
+ relative_path = path[2:] if path.startswith("./") else path
914
+ search_root = '"$PWD"'
915
+ if relative_path not in {"", "."}:
916
+ search_root += f"/{self._escape_shell_arg(relative_path)}"
917
+ cmd_parts.append(search_root)
918
+ return self._run_search_pipeline(cmd_parts, output_mode, limit, offset, context, line_cap=True)
919
+
920
+ def _search_with_grep_pruned(self, pattern: str, path: str, file_glob: Optional[str],
921
+ limit: int, offset: int, output_mode: str, context: int,
922
+ protected_paths: List[str]) -> SearchResult:
923
+ """grep fallback with PATH-scoped protected-dir pruning: ``find ... -prune``
924
+ enumerates files (traversal never enters protected dirs) and hands them to
925
+ grep via ``-exec {} +``; hidden dirs pruned to mirror ``--exclude-dir='.*'``.
926
+ Trade-off: find folds grep's exit code, so a hard grep error surfaces as an
927
+ empty result — acceptable for this darwin-local-broad-search-only branch."""
928
+ grep_parts = self._grep_cmd(["grep", "-nHE"], pattern, output_mode, context)
929
+ find_parts = [
930
+ "find", self._escape_shell_arg(path or "."),
931
+ self._prune_expr(protected_paths), "-o",
932
+ "\\( -type d -name '.*' \\) -prune", "-o",
933
+ "-type f",
934
+ ]
935
+ if file_glob:
936
+ find_parts.extend(["-name", self._escape_shell_arg(file_glob)])
937
+ find_parts.extend(["-exec", *grep_parts, "{}", "+", "2>/dev/null"])
938
+ return self._run_search_pipeline(find_parts, output_mode, limit, offset, context, line_cap=True)
tools/file_state.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cross-agent file state coordination.
2
+
3
+ Prevents mangled edits when concurrent subagents (same process, same
4
+ filesystem) touch the same file: B writes a file A already read, so A's next
5
+ write would clobber B's changes. Complements the single-agent path-overlap
6
+ check in ``agent.tool_dispatch_helpers._should_parallelize_tool_batch``. A process-wide
7
+ ``FileStateRegistry`` tracks per-agent read stamps, the global last writer and
8
+ a per-path lock; every method is a no-op under ``HERMES_DISABLE_FILE_STATE_GUARD=1``.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import threading
14
+ import time
15
+ from collections import defaultdict
16
+ from contextlib import contextmanager
17
+ from pathlib import Path
18
+ from typing import Dict, Iterable, List, Optional, Tuple
19
+
20
+ # (mtime, read_ts, partial). partial=True when read_file returned a windowed
21
+ # view (offset > 1 or limit < total_lines) — a later write should still warn
22
+ # so the model re-reads in full.
23
+ ReadStamp = Tuple[float, float, bool]
24
+
25
+ # Bounded so long sessions don't accumulate unbounded state.
26
+ _MAX_PATHS_PER_AGENT = 4096
27
+ _MAX_GLOBAL_WRITERS = 4096
28
+
29
+
30
+ def _disabled() -> bool:
31
+ # Re-read each call so tests can toggle via monkeypatch.setenv.
32
+ return os.environ.get("HERMES_DISABLE_FILE_STATE_GUARD", "").strip() == "1"
33
+
34
+
35
+ def _mtime_or_none(resolved: str) -> Optional[float]:
36
+ try:
37
+ return os.path.getmtime(resolved)
38
+ except OSError:
39
+ return None
40
+
41
+
42
+ def _fmt_ts(ts: float) -> str:
43
+ # Short wall-clock for warnings; avoids datetime formatting on the hot path.
44
+ return time.strftime("%H:%M:%S", time.localtime(ts))
45
+
46
+
47
+ def _evict_oldest(container, cap: int) -> None:
48
+ """Pop entries until *container* is within *cap* (sets: arbitrary; dicts: oldest
49
+ by insertion order). An eviction only costs one redundant re-send or staleness check."""
50
+ for _ in range(len(container) - cap):
51
+ try:
52
+ if isinstance(container, set):
53
+ container.pop()
54
+ else:
55
+ container.pop(next(iter(container)))
56
+ except (StopIteration, KeyError):
57
+ break
58
+
59
+
60
+ class FileStateRegistry:
61
+ """Process-wide coordinator for cross-agent file edits."""
62
+
63
+ def __init__(self) -> None:
64
+ self._reads: Dict[str, Dict[str, ReadStamp]] = defaultdict(dict)
65
+ self._last_writer: Dict[str, Tuple[str, float]] = {}
66
+ self._path_locks: Dict[str, threading.Lock] = {}
67
+ self._path_lock_users: Dict[str, int] = {}
68
+ self._meta_lock = threading.Lock() # guards _path_locks
69
+ self._state_lock = threading.Lock() # guards _reads + _last_writer
70
+
71
+ @contextmanager
72
+ def lock_path(self, resolved: str):
73
+ """Per-path lock: threads on the same path serialize, different paths proceed.
74
+ The lock entry is dropped once the last holder/waiter exits."""
75
+ with self._meta_lock:
76
+ lock = self._path_locks.setdefault(resolved, threading.Lock())
77
+ self._path_lock_users[resolved] = self._path_lock_users.get(resolved, 0) + 1
78
+ lock.acquire()
79
+ try:
80
+ yield
81
+ finally:
82
+ lock.release()
83
+ with self._meta_lock:
84
+ users = self._path_lock_users[resolved] - 1
85
+ if users:
86
+ self._path_lock_users[resolved] = users
87
+ else:
88
+ self._path_lock_users.pop(resolved, None)
89
+ self._path_locks.pop(resolved, None)
90
+
91
+ def _stamp(self, task_id: str, resolved: str, mtime: float, now: float, partial: bool) -> None:
92
+ """Caller holds ``_state_lock``."""
93
+ agent_reads = self._reads[task_id]
94
+ agent_reads[resolved] = (float(mtime), now, bool(partial))
95
+ _evict_oldest(agent_reads, _MAX_PATHS_PER_AGENT)
96
+
97
+ def record_read(self, task_id: str, resolved: str, *, partial: bool = False,
98
+ mtime: Optional[float] = None) -> None:
99
+ if _disabled():
100
+ return
101
+ mtime = _mtime_or_none(resolved) if mtime is None else mtime
102
+ if mtime is None:
103
+ return
104
+ with self._state_lock:
105
+ self._stamp(task_id, resolved, mtime, time.time(), partial)
106
+
107
+ def note_write(self, task_id: str, resolved: str, *, mtime: Optional[float] = None) -> None:
108
+ """Record a successful write: global last-writer AND this agent's own
109
+ read stamp (a write is an implicit read of the current content)."""
110
+ if _disabled():
111
+ return
112
+ mtime = _mtime_or_none(resolved) if mtime is None else mtime
113
+ if mtime is None:
114
+ return
115
+ now = time.time()
116
+ with self._state_lock:
117
+ self._last_writer[resolved] = (task_id, now)
118
+ _evict_oldest(self._last_writer, _MAX_GLOBAL_WRITERS)
119
+ self._stamp(task_id, resolved, mtime, now, False)
120
+
121
+ def check_stale(self, task_id: str, resolved: str) -> Optional[str]:
122
+ """Model-facing warning if this write would be stale, else ``None``. Severity
123
+ order: sibling wrote after our read > mtime drift / partial read > never read."""
124
+ if _disabled():
125
+ return None
126
+ with self._state_lock:
127
+ stamp = self._reads.get(task_id, {}).get(resolved)
128
+ last_writer = self._last_writer.get(resolved)
129
+
130
+ if stamp is None and last_writer is None: # net-new file / first touch
131
+ return None
132
+ current_mtime = _mtime_or_none(resolved)
133
+ if current_mtime is None:
134
+ return None # file doesn't exist — write creates it; not stale
135
+
136
+ if last_writer is not None:
137
+ writer_tid, writer_ts = last_writer
138
+ if writer_tid != task_id:
139
+ if stamp is None:
140
+ return (
141
+ f"{resolved} was modified by sibling subagent "
142
+ f"{writer_tid!r} but this agent never read it. "
143
+ "Read the file before writing to avoid overwriting "
144
+ "the sibling's changes.")
145
+ read_ts = stamp[1]
146
+ if writer_ts > read_ts:
147
+ return (
148
+ f"{resolved} was modified by sibling subagent "
149
+ f"{writer_tid!r} at {_fmt_ts(writer_ts)} — after "
150
+ f"this agent's last read at {_fmt_ts(read_ts)}. "
151
+ "Re-read the file before writing.")
152
+
153
+ if stamp is not None:
154
+ read_mtime, _read_ts, partial = stamp
155
+ if current_mtime != read_mtime:
156
+ return (
157
+ f"{resolved} was modified since you last read it "
158
+ "on disk (external edit or unrecorded writer). "
159
+ "Re-read the file before writing.")
160
+ if partial:
161
+ return (
162
+ f"{resolved} was last read with offset/limit pagination "
163
+ "(partial view). Re-read the whole file before "
164
+ "overwriting it.")
165
+ return None
166
+
167
+ return (
168
+ f"{resolved} was not read by this agent. "
169
+ "Read the file first so you can write an informed edit.")
170
+
171
+ def writes_since(self, exclude_task_id: str, since_ts: float,
172
+ paths: Iterable[str]) -> Dict[str, List[str]]:
173
+ """``{writer_task_id: [paths]}`` for writes after ``since_ts`` by agents
174
+ other than ``exclude_task_id`` (delegate_task's "subagent modified files
175
+ you previously read" reminder)."""
176
+ if _disabled():
177
+ return {}
178
+ paths_set = set(paths)
179
+ out: Dict[str, List[str]] = defaultdict(list)
180
+ with self._state_lock:
181
+ for p, (writer_tid, ts) in self._last_writer.items():
182
+ if writer_tid != exclude_task_id and ts >= since_ts and p in paths_set:
183
+ out[writer_tid].append(p)
184
+ return dict(out)
185
+
186
+ def known_reads(self, task_id: str) -> List[str]:
187
+ """Resolved paths this agent has read."""
188
+ if _disabled():
189
+ return []
190
+ with self._state_lock:
191
+ return list(self._reads.get(task_id, {}).keys())
192
+
193
+ def forget_task(self, task_id: str) -> None:
194
+ """Release read stamps owned by a task after its lifecycle ends."""
195
+ with self._state_lock:
196
+ self._reads.pop(task_id, None)
197
+
198
+ def clear(self) -> None:
199
+ """Reset all state. Intended for tests only."""
200
+ with self._state_lock:
201
+ self._reads.clear()
202
+ self._last_writer.clear()
203
+ with self._meta_lock:
204
+ self._path_locks.clear()
205
+ self._path_lock_users.clear()
206
+
207
+
208
+ _registry = FileStateRegistry()
209
+
210
+
211
+ def get_registry() -> FileStateRegistry:
212
+ return _registry
213
+
214
+
215
+ # Convenience wrappers (short names used at call sites).
216
+ def record_read(task_id: str, resolved_or_path: str | Path, *, partial: bool = False) -> None:
217
+ _registry.record_read(task_id, str(resolved_or_path), partial=partial)
218
+
219
+
220
+ def note_write(task_id: str, resolved_or_path: str | Path) -> None:
221
+ _registry.note_write(task_id, str(resolved_or_path))
222
+
223
+
224
+ def check_stale(task_id: str, resolved_or_path: str | Path) -> Optional[str]:
225
+ return _registry.check_stale(task_id, str(resolved_or_path))
226
+
227
+
228
+ def lock_path(resolved_or_path: str | Path):
229
+ return _registry.lock_path(str(resolved_or_path))
230
+
231
+
232
+ def writes_since(exclude_task_id: str, since_ts: float, paths: Iterable[str | Path]) -> Dict[str, List[str]]:
233
+ return _registry.writes_since(exclude_task_id, since_ts, [str(p) for p in paths])
234
+
235
+
236
+ def known_reads(task_id: str) -> List[str]:
237
+ return _registry.known_reads(task_id)
238
+
239
+
240
+ __all__ = [
241
+ "FileStateRegistry",
242
+ "get_registry",
243
+ "record_read",
244
+ "note_write",
245
+ "check_stale",
246
+ "lock_path",
247
+ "writes_since",
248
+ "known_reads"]
tools/file_tools_read_tracking.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-task read/search bookkeeping for the file tools.
2
+
3
+ Process-lifetime state behind read_file/search_files/write_file/patch.
4
+ Per task_id ``_read_tracker``
5
+ stores: ``last_key``/``consecutive`` (loop detection; reset by any OTHER tool
6
+ call), ``read_history`` (diagnostics), ``dedup`` (key -> mtime; survives context
7
+ compression), ``dedup_generation_reads`` (keys whose full content was served since
8
+ the last compaction boundary; cleared on compression so one recovery read returns
9
+ full content), ``dedup_hits`` (stub-loop breaker), ``read_timestamps``
10
+ (staleness warnings) and ``not_found`` (short-TTL negative cache). Every
11
+ container is hard-capped (``_cap_read_tracker_data``) so long sessions stay small.
12
+ """
13
+
14
+ import logging
15
+ import os
16
+ import threading
17
+ import time
18
+
19
+ from tools.file_state import _evict_oldest
20
+ from tools.file_tools_paths import _authoritative_workspace_root, _resolve_path_for_task
21
+
22
+ logger = logging.getLogger("tools.file_tools")
23
+
24
+ _read_tracker_lock = threading.Lock()
25
+ _read_tracker: dict = {}
26
+
27
+ # Consecutive patch failures per (task_id, resolved_path); escalates the hint
28
+ # when the model keeps failing the same file. Reset on a successful patch.
29
+ _patch_failure_lock = threading.Lock()
30
+ _patch_failure_tracker: dict = {} # {task_id: {resolved_path: count}}
31
+ _PATCH_FAILURE_PATHS_CAP = 64
32
+
33
+ # Only the most recent reads matter for dedup, loop detection and external-edit
34
+ # warnings; caps bound accretion regardless of session length.
35
+ _READ_HISTORY_CAP = 500
36
+ _DEDUP_CAP = 1000
37
+ _READ_TIMESTAMPS_CAP = 1000
38
+ _NOT_FOUND_CAP = 500
39
+ _NOT_FOUND_TTL_SECONDS = 60.0 # a path that didn't exist may be created soon
40
+
41
+
42
+ def _task_data(task_id: str) -> dict:
43
+ """Get-or-create the tracker entry for *task_id*, back-filling missing containers
44
+ (search_tool / tests create partial entries). Lock must be held."""
45
+ task_data = _read_tracker.setdefault(task_id, {
46
+ "last_key": None, "consecutive": 0, "read_history": set()})
47
+ for key in ("dedup", "dedup_hits", "read_timestamps"):
48
+ task_data.setdefault(key, {})
49
+ task_data.setdefault("dedup_generation_reads", set())
50
+ return task_data
51
+
52
+
53
+ def _record_patch_failure(task_id: str, resolved_path: str) -> int:
54
+ """Increment and return the consecutive-failure count for this path."""
55
+ with _patch_failure_lock:
56
+ task_failures = _patch_failure_tracker.setdefault(task_id, {})
57
+ # Evict the oldest entry once a task has failed on many distinct files.
58
+ if resolved_path not in task_failures:
59
+ _evict_oldest(task_failures, _PATCH_FAILURE_PATHS_CAP - 1)
60
+ task_failures[resolved_path] = task_failures.get(resolved_path, 0) + 1
61
+ return task_failures[resolved_path]
62
+
63
+
64
+ def _reset_patch_failures(task_id: str, resolved_paths: list) -> None:
65
+ """Clear consecutive-failure counts for the given paths."""
66
+ if not resolved_paths:
67
+ return
68
+ with _patch_failure_lock:
69
+ task_failures = _patch_failure_tracker.get(task_id)
70
+ for rp in resolved_paths if task_failures else ():
71
+ task_failures.pop(rp, None)
72
+
73
+
74
+ def _cap_read_tracker_data(task_data: dict) -> None:
75
+ """Enforce size caps on the per-task sub-containers. Call with ``_read_tracker_lock`` held."""
76
+ # Caps are read at call time so tests can monkeypatch the module constants.
77
+ for key, cap in (
78
+ ("read_history", _READ_HISTORY_CAP),
79
+ ("dedup", _DEDUP_CAP),
80
+ ("dedup_hits", _DEDUP_CAP),
81
+ ("dedup_generation_reads", _DEDUP_CAP),
82
+ ("read_timestamps", _READ_TIMESTAMPS_CAP),
83
+ ("not_found", _NOT_FOUND_CAP)):
84
+ container = task_data.get(key)
85
+ if container is not None and len(container) > cap:
86
+ _evict_oldest(container, cap)
87
+
88
+
89
+ def _resolved_or_none(filepath: str, task_id: str) -> str | None:
90
+ try:
91
+ return str(_resolve_path_for_task(filepath, task_id))
92
+ except (OSError, ValueError):
93
+ return None
94
+
95
+
96
+ def _pop_not_found(op: str, resolved_str: str, task_id: str) -> None:
97
+ """Drop the negative-cache entry for *(op, resolved_str)*. Lock must be held."""
98
+ task_data = _read_tracker.get(task_id)
99
+ nf = task_data.get("not_found") if task_data else None
100
+ if nf:
101
+ nf.pop((op, resolved_str), None)
102
+
103
+
104
+ def _check_not_found_cache(op: str, resolved_str: str, task_id: str) -> str | None:
105
+ """Return cached not-found JSON for *(op, resolved_str)* if still fresh.
106
+
107
+ *op* is "read" or "search" (different error JSON shapes). Evicted by TTL,
108
+ by write_file/patch on the path, or by any other tool call.
109
+ """
110
+ with _read_tracker_lock:
111
+ task_data = _read_tracker.get(task_id)
112
+ entry = (task_data.get("not_found") or {}).get((op, resolved_str)) if task_data else None
113
+ if entry is None:
114
+ return None
115
+ ts, cached_json = entry
116
+ if time.monotonic() - ts > _NOT_FOUND_TTL_SECONDS:
117
+ _pop_not_found(op, resolved_str, task_id)
118
+ return None
119
+ # "check → create → read" is common, so never serve a stale miss for a path
120
+ # that now exists. The stat runs OUTSIDE the tracker lock: a hung stat on a
121
+ # dead network mount must not stall every task.
122
+ if os.path.exists(resolved_str):
123
+ with _read_tracker_lock:
124
+ _pop_not_found(op, resolved_str, task_id)
125
+ return None
126
+ return cached_json
127
+
128
+
129
+ def _record_not_found(op: str, resolved_str: str, task_id: str, error_json: str) -> None:
130
+ """Cache a not-found error so the next *op* call for *resolved_str* skips I/O."""
131
+ with _read_tracker_lock:
132
+ task_data = _task_data(task_id)
133
+ task_data.setdefault("not_found", {})[(op, resolved_str)] = (time.monotonic(), error_json)
134
+ _cap_read_tracker_data(task_data)
135
+
136
+
137
+ def _bump_consecutive(task_data: dict, key: tuple) -> int:
138
+ """Update last_key/consecutive for *key* and return the new count. Lock must be held."""
139
+ if task_data["last_key"] == key:
140
+ task_data["consecutive"] += 1
141
+ else:
142
+ task_data["last_key"] = key
143
+ task_data["consecutive"] = 1
144
+ return task_data["consecutive"]
145
+
146
+
147
+ def reset_file_dedup(task_id: str = None):
148
+ """Advance the read-dedup generation after context compression (one task, or all
149
+ when ``task_id`` is None). The per-key ``dedup`` mtime map is PRESERVED so unchanged
150
+ files keep returning stubs instead of re-bloating the reclaimed context; the
151
+ generation-read set is cleared so the FIRST unchanged read of each key after
152
+ compaction returns full content the summary may have dropped. Stub-hit counters
153
+ are cleared so the hard block restarts fresh."""
154
+ with _read_tracker_lock:
155
+ if task_id:
156
+ targets = [_read_tracker[task_id]] if _read_tracker.get(task_id) else []
157
+ else:
158
+ targets = list(_read_tracker.values())
159
+ for task_data in targets:
160
+ if "dedup_hits" in task_data:
161
+ task_data["dedup_hits"].clear()
162
+ task_data.setdefault("dedup_generation_reads", set()).clear()
163
+
164
+
165
+ def notify_other_tool_call(task_id: str = "default"):
166
+ """Reset the consecutive read/search counter for a task.
167
+
168
+ Called by the dispatcher for every tool OTHER than read_file/search_files.
169
+ Also clears stub-hit counters and the not-found cache: any other tool may
170
+ have created a previously-missing path (or flipped its permissions).
171
+ """
172
+ with _read_tracker_lock:
173
+ task_data = _read_tracker.get(task_id)
174
+ if task_data:
175
+ task_data["last_key"] = None
176
+ task_data["consecutive"] = 0
177
+ for key in ("dedup_hits", "not_found"):
178
+ if task_data.get(key):
179
+ task_data[key].clear()
180
+
181
+
182
+ def _invalidate_dedup_for_path(filepath: str, task_id: str) -> None:
183
+ """Evict every dedup entry (all offset/limit ranges) and not-found entry for *filepath*
184
+ after a write, so the next read returns fresh content. Acquires the lock itself."""
185
+ resolved = _resolved_or_none(filepath, task_id)
186
+ if resolved is None:
187
+ return
188
+ with _read_tracker_lock:
189
+ task_data = _read_tracker.get(task_id)
190
+ if task_data is None:
191
+ return
192
+ dedup = task_data.get("dedup")
193
+ if dedup:
194
+ for k in [k for k in dedup if k[0] == resolved]:
195
+ del dedup[k]
196
+ _pop_not_found("read", resolved, task_id)
197
+ _pop_not_found("search", resolved, task_id)
198
+
199
+
200
+ def _update_read_timestamp(filepath: str, task_id: str) -> None:
201
+ """After a successful write: invalidate dedup and refresh the stored mtime so
202
+ consecutive edits by the same task don't trigger false staleness warnings.
203
+
204
+ Also invalidates the dedup cache for the written path so that subsequent reads return fresh content
205
+ (fixes #13144).
206
+ """
207
+ _invalidate_dedup_for_path(filepath, task_id)
208
+ resolved = _resolved_or_none(filepath, task_id)
209
+ if resolved is None:
210
+ return
211
+ try:
212
+ current_mtime = os.path.getmtime(resolved)
213
+ except OSError:
214
+ return
215
+ with _read_tracker_lock:
216
+ task_data = _read_tracker.get(task_id)
217
+ if task_data is not None:
218
+ task_data.setdefault("read_timestamps", {})[resolved] = current_mtime
219
+ _cap_read_tracker_data(task_data)
220
+
221
+
222
+ def _check_file_staleness(filepath: str, task_id: str) -> str | None:
223
+ """Warn (don't block) when the file's mtime changed since this task last read it.
224
+ ``None`` when never read, fresh, or unstattable (a deleted file is the write's problem)."""
225
+ resolved = _resolved_or_none(filepath, task_id)
226
+ if resolved is None:
227
+ return None
228
+ with _read_tracker_lock:
229
+ task_data = _read_tracker.get(task_id)
230
+ read_mtime = task_data.get("read_timestamps", {}).get(resolved) if task_data else None
231
+ if read_mtime is None:
232
+ return None
233
+ try:
234
+ current_mtime = os.path.getmtime(resolved)
235
+ except OSError:
236
+ return None
237
+ if current_mtime != read_mtime:
238
+ return (
239
+ f"Warning: {filepath} was modified since you last read it "
240
+ "(external edit or concurrent agent). The content you read may be "
241
+ "stale. Consider re-reading the file to verify before writing.")
242
+ return None
243
+
244
+
245
+ def _mark_verification_stale(task_id: str, resolved_paths: list[str],
246
+ session_id: str | None = None) -> None:
247
+ """Best-effort note that successful edits made prior verification stale. cwd: the
248
+ first edited path's recognised project root, else the workspace root, else the first parent."""
249
+ from pathlib import Path
250
+
251
+ paths = [p for p in resolved_paths if p]
252
+ if not paths:
253
+ return
254
+ try:
255
+ from agent.coding_context import project_facts_for
256
+ from agent.verification_evidence import mark_workspace_edited
257
+
258
+ parents = [str(Path(p).parent) for p in paths]
259
+ cwd = (next((c for c in parents if project_facts_for(c)), None)
260
+ or _authoritative_workspace_root(task_id) or parents[0])
261
+ mark_workspace_edited(session_id=session_id or task_id, cwd=cwd, paths=paths)
262
+ except Exception:
263
+ logger.debug("verification stale marker failed", exc_info=True)
tools/focus_pane_tool.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reveal/focus a pane in the Hermes desktop GUI (``pane.reveal`` via ``desktop_ui``).
3
+
4
+ The renderer runs each pane's own reveal path and only acts on the active window, so
5
+ a background turn never moves the user's focus. URLs/files go through `desktop_preview`.
6
+ """
7
+
8
+ from tools import desktop_ui
9
+ from tools.registry import registry, tool_error
10
+
11
+ PANES = ("chat", "files", "terminal", "review", "sessions")
12
+
13
+
14
+ def focus_pane_tool(pane: str) -> str:
15
+ """Ask the desktop GUI to reveal and focus ``pane``."""
16
+ name = (pane or "").strip().lower()
17
+ if name not in PANES:
18
+ return tool_error(f"pane must be one of: {', '.join(PANES)}.")
19
+ return desktop_ui.emit_or_error(
20
+ "pane.reveal", {"pane": name}, f"Failed to focus the {name} pane: ",
21
+ "Pane focus is only available in the Hermes desktop app.", {"success": True, "pane": name})
22
+
23
+
24
+ registry.register(
25
+ name="focus_pane",
26
+ toolset="desktop_ui",
27
+ schema={
28
+ "name": "focus_pane",
29
+ "description": (
30
+ "Reveal and focus a Hermes desktop pane when the user asks to see it: "
31
+ "chat, files, terminal, review (git diff), or sessions. For URLs/"
32
+ "files use the desktop_preview tool instead."
33
+ ),
34
+ "parameters": {
35
+ "type": "object",
36
+ "properties": {
37
+ "pane": {
38
+ "type": "string",
39
+ "enum": list(PANES),
40
+ "description": "Which pane to reveal.",
41
+ },
42
+ },
43
+ "required": ["pane"],
44
+ },
45
+ },
46
+ handler=lambda args, **kw: focus_pane_tool(pane=args.get("pane", "")),
47
+ emoji="🪟",
48
+ )
49
+
50
+
51
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
52
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
53
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
54
+ # The whole block is removed by reverting the commit that added it.
55
+ import json # noqa: F401,E402
56
+
57
+ FOCUS_PANE_SCHEMA = {
58
+ "name": "focus_pane",
59
+ "description": (
60
+ "Reveal and focus a Hermes desktop pane when the user asks to see it: "
61
+ "chat, files, terminal, review (git diff), or sessions. For URLs/"
62
+ "files use the desktop_preview tool instead."
63
+ ),
64
+ "parameters": {
65
+ "type": "object",
66
+ "properties": {
67
+ "pane": {
68
+ "type": "string",
69
+ "enum": list(PANES),
70
+ "description": "Which pane to reveal.",
71
+ },
72
+ },
73
+ "required": ["pane"],
74
+ },
75
+ }
76
+ # ---- END PLUGIN-COMPAT ----
tools/homeassistant_tool.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Home Assistant tool for controlling smart home devices via REST API.
2
+
3
+ Registers ``ha_list_entities``, ``ha_get_state``, ``ha_list_services``, ``ha_call_service``.
4
+ Auth is a Long-Lived Access Token (``HASS_TOKEN``); the instance URL comes from
5
+ ``HASS_URL`` (default http://homeassistant.local:8123).
6
+ """
7
+
8
+ import asyncio
9
+ import json
10
+ import logging
11
+ import re
12
+ from typing import Any, Dict, Optional
13
+
14
+ from agent.secret_scope import get_secret
15
+ from tools.registry import registry, tool_error
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ def _get_config():
21
+ """Return the active profile's Home Assistant URL and token."""
22
+ return (
23
+ (get_secret("HASS_URL", "http://homeassistant.local:8123") or "").rstrip("/"),
24
+ get_secret("HASS_TOKEN", "") or "")
25
+
26
+
27
+ # Valid HA entity_id (e.g. "light.living_room", "sensor.temperature_1").
28
+ _ENTITY_ID_RE = re.compile(r"^[a-z_][a-z0-9_]*\.[a-z0-9_]+$")
29
+
30
+ # Domain/service names are interpolated into /api/services/{domain}/{service}, so only
31
+ # [a-z0-9_] is allowed: anything else enables SSRF via path traversal
32
+ # (domain="../../api/config") or blocklist bypass (domain="shell_command/../light").
33
+ _SERVICE_NAME_RE = re.compile(r"^[a-z][a-z0-9_]*$")
34
+
35
+ # Domains that allow arbitrary code/command execution on the HA host or SSRF on the
36
+ # local network. HA has zero service-level access control; all safety lives here.
37
+ _BLOCKED_DOMAINS = frozenset({
38
+ "shell_command", # arbitrary shell commands as root in HA container
39
+ "command_line", # sensors/switches that execute shell commands
40
+ "python_script", # sandboxed but can escalate via hass.services.call()
41
+ "pyscript", # scripting integration with broader access
42
+ "hassio", # addon control, host shutdown/reboot, stdin to containers
43
+ "rest_command", # HTTP requests from HA server (SSRF vector)
44
+ })
45
+
46
+
47
+ def _get_headers(token: str = "") -> Dict[str, str]:
48
+ """Return authorization headers for HA REST API."""
49
+ if not token:
50
+ _, token = _get_config()
51
+ return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
52
+
53
+
54
+ async def _api_json(method: str, path: str, timeout: float, payload: Any = None) -> Any:
55
+ """One HA REST call (GET or POST JSON) that raises on HTTP errors and returns the JSON body."""
56
+ import aiohttp
57
+ hass_url, hass_token = _get_config()
58
+ kwargs: Dict[str, Any] = {"headers": _get_headers(hass_token), "timeout": aiohttp.ClientTimeout(total=timeout)}
59
+ if method == "POST":
60
+ kwargs["json"] = payload
61
+ async with aiohttp.ClientSession() as session:
62
+ async with session.request(method, f"{hass_url}{path}", **kwargs) as resp:
63
+ resp.raise_for_status()
64
+ return await resp.json()
65
+
66
+
67
+ # ── async helpers (called from sync handlers via _run_async) ─────────────────
68
+ def _filter_and_summarize(states: list, domain: Optional[str] = None, area: Optional[str] = None) -> Dict:
69
+ """Filter raw HA states by domain/area (area matches friendly_name or area attr) and compact them."""
70
+ if domain:
71
+ states = [s for s in states if s.get("entity_id", "").startswith(f"{domain}.")]
72
+ if area:
73
+ area_lower = area.lower()
74
+ states = [
75
+ s for s in states
76
+ if area_lower in (s.get("attributes", {}).get("friendly_name", "") or "").lower()
77
+ or area_lower in (s.get("attributes", {}).get("area", "") or "").lower()]
78
+ entities = [
79
+ {
80
+ "entity_id": s["entity_id"], "state": s["state"],
81
+ "friendly_name": s.get("attributes", {}).get("friendly_name", "")}
82
+ for s in states]
83
+ return {"count": len(entities), "entities": entities}
84
+
85
+
86
+ async def _async_list_entities(domain: Optional[str] = None, area: Optional[str] = None) -> Dict[str, Any]:
87
+ return _filter_and_summarize(await _api_json("GET", "/api/states", 15), domain, area)
88
+
89
+
90
+ async def _async_get_state(entity_id: str) -> Dict[str, Any]:
91
+ data = await _api_json("GET", f"/api/states/{entity_id}", 10)
92
+ return {
93
+ "entity_id": data["entity_id"], "state": data["state"], "attributes": data.get("attributes", {}),
94
+ "last_changed": data.get("last_changed"), "last_updated": data.get("last_updated")}
95
+
96
+
97
+ def _build_service_payload(entity_id: Optional[str] = None, data: Optional[Dict[str, Any]] = None) -> Dict:
98
+ """JSON payload for a HA service call; ``entity_id`` overrides data["entity_id"]."""
99
+ payload: Dict[str, Any] = dict(data or {})
100
+ if entity_id:
101
+ payload["entity_id"] = entity_id
102
+ return payload
103
+
104
+
105
+ def _parse_service_response(domain: str, service: str, result: Any) -> Dict[str, Any]:
106
+ affected = []
107
+ if isinstance(result, list):
108
+ affected = [{"entity_id": s.get("entity_id", ""), "state": s.get("state", "")} for s in result]
109
+ return {"success": True, "service": f"{domain}.{service}", "affected_entities": affected}
110
+
111
+
112
+ async def _async_call_service(
113
+ domain: str, service: str, entity_id: Optional[str] = None, data: Optional[Dict[str, Any]] = None,
114
+ ) -> Dict[str, Any]:
115
+ result = await _api_json(
116
+ "POST", f"/api/services/{domain}/{service}", 15, _build_service_payload(entity_id, data))
117
+ return _parse_service_response(domain, service, result)
118
+
119
+
120
+ async def _async_list_services(domain: Optional[str] = None) -> Dict[str, Any]:
121
+ """Available services, optionally filtered by domain, compacted for context."""
122
+ services = await _api_json("GET", "/api/services", 15)
123
+ if domain:
124
+ services = [s for s in services if s.get("domain") == domain]
125
+ result = []
126
+ for svc_domain in services:
127
+ domain_services = {}
128
+ for svc_name, svc_info in svc_domain.get("services", {}).items():
129
+ svc_entry: Dict[str, Any] = {"description": svc_info.get("description", "")}
130
+ fields = svc_info.get("fields", {})
131
+ if fields:
132
+ svc_entry["fields"] = {
133
+ k: v.get("description", "") for k, v in fields.items() if isinstance(v, dict)}
134
+ domain_services[svc_name] = svc_entry
135
+ result.append({"domain": svc_domain.get("domain", ""), "services": domain_services})
136
+ return {"count": len(result), "domains": result}
137
+
138
+
139
+ # ── sync wrappers (handler signature: (args, **kw) -> str) ───────────────────
140
+ def _run_async(coro):
141
+ """Run a coroutine from a sync handler; hops to a thread if a loop is already running."""
142
+ try:
143
+ loop = asyncio.get_running_loop()
144
+ except RuntimeError:
145
+ loop = None
146
+ if loop and loop.is_running(): # already inside a loop: asyncio.run() needs its own thread
147
+ import concurrent.futures
148
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
149
+ return pool.submit(asyncio.run, coro).result(timeout=30)
150
+ return asyncio.run(coro)
151
+
152
+
153
+ def _dispatch(coro, log_name: str, fail_msg: str) -> str:
154
+ """Run ``coro`` and wrap as ``{"result": ...}``; on error log and return tool_error."""
155
+ try:
156
+ return json.dumps({"result": _run_async(coro)})
157
+ except Exception as e:
158
+ logger.error("%s error: %s", log_name, e)
159
+ return tool_error(f"{fail_msg}: {e}")
160
+
161
+
162
+ def _handle_get_state(args: dict, **kw) -> str:
163
+ entity_id = args.get("entity_id", "")
164
+ if not entity_id:
165
+ return tool_error("Missing required parameter: entity_id")
166
+ if not _ENTITY_ID_RE.match(entity_id):
167
+ return tool_error(f"Invalid entity_id format: {entity_id}")
168
+ return _dispatch(_async_get_state(entity_id), "ha_get_state", f"Failed to get state for {entity_id}")
169
+
170
+
171
+ def _handle_call_service(args: dict, **kw) -> str:
172
+ domain = args.get("domain", "")
173
+ service = args.get("service", "")
174
+ if not domain or not service:
175
+ return tool_error("Missing required parameters: domain and service")
176
+ # Format check BEFORE the blocklist: rejects "shell_command/../light" style bypasses.
177
+ if not _SERVICE_NAME_RE.match(domain):
178
+ return tool_error(f"Invalid domain format: {domain!r}")
179
+ if not _SERVICE_NAME_RE.match(service):
180
+ return tool_error(f"Invalid service format: {service!r}")
181
+ if domain in _BLOCKED_DOMAINS:
182
+ return tool_error(
183
+ f"Service domain '{domain}' is blocked for security. "
184
+ f"Blocked domains: {', '.join(sorted(_BLOCKED_DOMAINS))}")
185
+ entity_id = args.get("entity_id")
186
+ if entity_id and not _ENTITY_ID_RE.match(entity_id):
187
+ return tool_error(f"Invalid entity_id format: {entity_id}")
188
+ data = args.get("data")
189
+ if isinstance(data, str): # XML tool-calling mode delivers data as a JSON string
190
+ try:
191
+ data = json.loads(data) if data.strip() else None
192
+ except json.JSONDecodeError as e:
193
+ return tool_error(f"Invalid JSON string in 'data' parameter: {e}")
194
+ return _dispatch(
195
+ _async_call_service(domain, service, entity_id, data),
196
+ "ha_call_service", f"Failed to call {domain}.{service}")
197
+
198
+
199
+ def _check_ha_available() -> bool:
200
+ """Tool is only available when HASS_TOKEN is set."""
201
+ return bool(get_secret("HASS_TOKEN"))
202
+
203
+
204
+ # ── tool schemas ─────────────────────────────────────────────────────────────
205
+ HA_LIST_ENTITIES_SCHEMA = {
206
+ "name": "ha_list_entities",
207
+ "description": (
208
+ "List Home Assistant entities. Optionally filter by domain "
209
+ "(light, switch, climate, sensor, binary_sensor, cover, fan, etc.) "
210
+ "or by area name (living room, kitchen, bedroom, etc.)."
211
+ ),
212
+ "parameters": {
213
+ "type": "object",
214
+ "properties": {
215
+ "domain": {
216
+ "type": "string",
217
+ "description": (
218
+ "Entity domain to filter by (e.g. 'light', 'switch', 'climate', "
219
+ "'sensor', 'binary_sensor', 'cover', 'fan', 'media_player'). "
220
+ "Omit to list all entities."
221
+ ),
222
+ },
223
+ "area": {
224
+ "type": "string",
225
+ "description": (
226
+ "Area/room name to filter by (e.g. 'living room', 'kitchen'). "
227
+ "Matches against entity friendly names. Omit to list all."
228
+ ),
229
+ },
230
+ },
231
+ "required": [],
232
+ },
233
+ }
234
+
235
+ HA_GET_STATE_SCHEMA = {
236
+ "name": "ha_get_state",
237
+ "description": (
238
+ "Get the detailed state of a single Home Assistant entity, including all "
239
+ "attributes (brightness, color, temperature setpoint, sensor readings, etc.)."
240
+ ),
241
+ "parameters": {
242
+ "type": "object",
243
+ "properties": {
244
+ "entity_id": {
245
+ "type": "string",
246
+ "description": (
247
+ "The entity ID to query (e.g. 'light.living_room', "
248
+ "'climate.thermostat', 'sensor.temperature')."
249
+ ),
250
+ },
251
+ },
252
+ "required": ["entity_id"],
253
+ },
254
+ }
255
+
256
+ HA_LIST_SERVICES_SCHEMA = {
257
+ "name": "ha_list_services",
258
+ "description": (
259
+ "List available Home Assistant services (actions) for device control. "
260
+ "Shows what actions can be performed on each device type and what "
261
+ "parameters they accept. Use this to discover how to control devices "
262
+ "found via ha_list_entities."
263
+ ),
264
+ "parameters": {
265
+ "type": "object",
266
+ "properties": {
267
+ "domain": {
268
+ "type": "string",
269
+ "description": (
270
+ "Filter by domain (e.g. 'light', 'climate', 'switch'). "
271
+ "Omit to list services for all domains."
272
+ ),
273
+ },
274
+ },
275
+ "required": [],
276
+ },
277
+ }
278
+
279
+ HA_CALL_SERVICE_SCHEMA = {
280
+ "name": "ha_call_service",
281
+ "description": (
282
+ "Call a Home Assistant service to control a device. Use ha_list_services "
283
+ "to discover available services and their parameters for each domain."
284
+ ),
285
+ "parameters": {
286
+ "type": "object",
287
+ "properties": {
288
+ "domain": {
289
+ "type": "string",
290
+ "description": (
291
+ "Service domain (e.g. 'light', 'switch', 'climate', "
292
+ "'cover', 'media_player', 'fan', 'scene', 'script')."
293
+ ),
294
+ },
295
+ "service": {
296
+ "type": "string",
297
+ "description": (
298
+ "Service name (e.g. 'turn_on', 'turn_off', 'toggle', "
299
+ "'set_temperature', 'set_hvac_mode', 'open_cover', "
300
+ "'close_cover', 'set_volume_level')."
301
+ ),
302
+ },
303
+ "entity_id": {
304
+ "type": "string",
305
+ "description": (
306
+ "Target entity ID (e.g. 'light.living_room'). "
307
+ "Some services (like scene.turn_on) may not need this."
308
+ ),
309
+ },
310
+ "data": {
311
+ "type": "string",
312
+ "description": (
313
+ "Additional service data as a JSON string. Examples: "
314
+ '{"brightness": 255, "color_name": "blue"} for lights, '
315
+ '{"temperature": 22, "hvac_mode": "heat"} for climate, '
316
+ '{"volume_level": 0.5} for media players.'
317
+ ),
318
+ },
319
+ },
320
+ "required": ["domain", "service"],
321
+ },
322
+ }
323
+
324
+
325
+ for _schema, _handler in (
326
+ (HA_LIST_ENTITIES_SCHEMA, lambda args, **kw: _dispatch(
327
+ _async_list_entities(domain=args.get("domain"), area=args.get("area")),
328
+ "ha_list_entities", "Failed to list entities")),
329
+ (HA_GET_STATE_SCHEMA, _handle_get_state),
330
+ (HA_LIST_SERVICES_SCHEMA, lambda args, **kw: _dispatch(
331
+ _async_list_services(domain=args.get("domain")), "ha_list_services", "Failed to list services")),
332
+ (HA_CALL_SERVICE_SCHEMA, _handle_call_service)):
333
+ registry.register(
334
+ name=_schema["name"], toolset="homeassistant", schema=_schema, handler=_handler,
335
+ check_fn=_check_ha_available, emoji="🏠")
tools/hook_output_spill.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spill oversized hook-injected context to disk with a preview placeholder.
2
+
3
+ Hook ``{"context": ...}`` output rides EVERY subsequent API call, so a large blob
4
+ inflates every turn and breaks the prompt-cache prefix. Above
5
+ ``hooks.output_spill.max_chars`` (default 10000) the text is written under
6
+ ``hooks.output_spill.directory`` (default ``<HERMES_HOME>/hook_outputs/<session>``)
7
+ and the payload becomes a ``preview_head``/``preview_tail`` excerpt plus the path.
8
+ ``enabled: false`` disables. Never raises: an I/O failure still returns a preview.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import os
15
+ import uuid
16
+ from pathlib import Path
17
+ from typing import Any, Dict, Optional
18
+
19
+ from tools.tool_output_limits import _coerce_int, _coerce_positive_int
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ DEFAULT_MAX_CHARS = 10_000
25
+ DEFAULT_PREVIEW_HEAD = 500
26
+ DEFAULT_PREVIEW_TAIL = 500
27
+ DEFAULT_ENABLED = True
28
+
29
+
30
+ def get_spill_config() -> Dict[str, Any]:
31
+ """Return resolved hook output-spill config. Never raises."""
32
+ section: Dict[str, Any] = {}
33
+ try:
34
+ from hermes_cli.config import load_config
35
+ cfg = load_config() or {}
36
+ hooks = cfg.get("hooks") if isinstance(cfg, dict) else None
37
+ if isinstance(hooks, dict) and isinstance(hooks.get("output_spill"), dict):
38
+ section = hooks["output_spill"]
39
+ except Exception:
40
+ section = {}
41
+ enabled_raw = section.get("enabled", DEFAULT_ENABLED)
42
+ directory = section.get("directory")
43
+ return {
44
+ "enabled": bool(enabled_raw) if enabled_raw is not None else DEFAULT_ENABLED,
45
+ "max_chars": _coerce_positive_int(section.get("max_chars"), DEFAULT_MAX_CHARS),
46
+ # head/tail allow zero (empty tail), max_chars must be positive.
47
+ "preview_head": _coerce_int(section.get("preview_head"), DEFAULT_PREVIEW_HEAD, 0),
48
+ "preview_tail": _coerce_int(section.get("preview_tail"), DEFAULT_PREVIEW_TAIL, 0),
49
+ "directory": directory if isinstance(directory, str) else None,
50
+ }
51
+
52
+
53
+ def _resolve_spill_dir(directory_override: Optional[str], session_id: Optional[str]) -> Path:
54
+ """Per-session spill directory; session id is sanitised so it can't escape ``base``."""
55
+ if directory_override:
56
+ base = Path(os.path.expanduser(directory_override))
57
+ else:
58
+ from hermes_constants import get_hermes_home
59
+ base = Path(get_hermes_home()) / "hook_outputs"
60
+ session_segment = (session_id or "no-session").replace("/", "_").replace("\\", "_").replace("..", "_")
61
+ return base / session_segment
62
+
63
+
64
+ def spill_if_oversized(
65
+ text: str, *, session_id: Optional[str] = None, source: str = "hook", config: Optional[Dict[str, Any]] = None,
66
+ ) -> str:
67
+ """Spill ``text`` to disk if it exceeds the configured cap.
68
+
69
+ Returns ``text`` unchanged (under cap, disabled, or empty) or a preview
70
+ string pointing at the full content. Non-string input is ``str()``-coerced;
71
+ ``source`` labels the preview header; ``config`` overrides config.yaml.
72
+ """
73
+ if text is None:
74
+ return ""
75
+ if not isinstance(text, str):
76
+ try:
77
+ text = str(text)
78
+ except Exception:
79
+ return ""
80
+ cfg = config if config is not None else get_spill_config()
81
+ if not cfg.get("enabled", True):
82
+ return text
83
+ if len(text) <= int(cfg.get("max_chars") or DEFAULT_MAX_CHARS):
84
+ return text
85
+ head = int(cfg.get("preview_head") or 0)
86
+ tail = int(cfg.get("preview_tail") or 0)
87
+
88
+ # A disk failure must never blow up the turn — fall through to a preview
89
+ # without a saved path.
90
+ saved_path: Optional[str] = None
91
+ try:
92
+ spill_dir = _resolve_spill_dir(cfg.get("directory"), session_id)
93
+ from tools.spill_safety import ensure_spill_dir, write_text_exclusive
94
+ # Hook context may embed raw secrets: private perms + exclusive,
95
+ # symlink-refusing create (the per-session dir is predictable).
96
+ ensure_spill_dir(spill_dir, private=True)
97
+ spill_path = spill_dir / f"{uuid.uuid4().hex}.txt"
98
+ # Trailing newline so tail readers don't report "missing newline".
99
+ write_text_exclusive(spill_path, text if text.endswith("\n") else text + "\n", private=True)
100
+ saved_path = str(spill_path)
101
+ except Exception as exc:
102
+ logger.warning("hook output spill failed: %s", exc)
103
+
104
+ total = len(text)
105
+ parts = [
106
+ f"[{source} output truncated — {total:,} chars; full content "
107
+ + (f"saved to {saved_path}]" if saved_path else "unavailable — spill write failed]"),
108
+ ]
109
+ if head > 0 and text[:head]:
110
+ parts.extend(["--- head ---", text[:head]])
111
+ if tail > 0 and total > head:
112
+ parts.extend(["--- tail ---", text[-tail:]])
113
+ return "\n".join(parts)
114
+
115
+
116
+ __all__ = ["DEFAULT_MAX_CHARS", "DEFAULT_PREVIEW_HEAD", "DEFAULT_PREVIEW_TAIL", "DEFAULT_ENABLED",
117
+ "get_spill_config", "spill_if_oversized"]
tools/image_generation_tool.py ADDED
@@ -0,0 +1,877 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Image generation via FAL.ai (model picked in ``hermes tools``, persisted to ``image_gen.model``).
3
+
4
+ ``_build_fal_payload()`` / ``_build_fal_edit_payload()`` translate unified inputs into the
5
+ ``FAL_MODELS`` payload filtered to its ``supports`` whitelist so models never receive rejected
6
+ keys. Clarity upscaling is strictly per-call opt-in: default-on degraded text/CJK/faces.
7
+ """
8
+
9
+ import json
10
+ import logging
11
+ import os
12
+ import datetime
13
+ import threading
14
+ import uuid
15
+ from typing import Any, Dict, Optional
16
+
17
+ # Imported lazily by _load_fal_client() (~64 ms on every CLI cold start); a test-monkeypatched
18
+ # value short-circuits the loader.
19
+ fal_client: Any = None
20
+
21
+
22
+ def _load_fal_client() -> Any:
23
+ """Lazily import fal_client into the module global (idempotent; keeps a test-installed mock)."""
24
+ global fal_client
25
+ if fal_client is None:
26
+ from tools.fal_common import import_fal_client
27
+ fal_client = import_fal_client()
28
+ return fal_client
29
+
30
+
31
+ from tools.debug_helpers import DebugSession
32
+ from tools.fal_common import (
33
+ _ManagedFalSyncClient, _extract_http_status, _managed_fal_billing_error,
34
+ _normalize_fal_queue_url_format,
35
+ )
36
+ from tools.image_generation_catalog import (
37
+ DEFAULT_ASPECT_RATIO, DEFAULT_MODEL, FAL_MODELS, UPSCALER_CREATIVITY, UPSCALER_DEFAULT_PROMPT,
38
+ UPSCALER_FACTOR, UPSCALER_GUIDANCE_SCALE, UPSCALER_MODEL, UPSCALER_NEGATIVE_PROMPT,
39
+ UPSCALER_NUM_INFERENCE_STEPS, UPSCALER_RESEMBLANCE, UPSCALER_SAFETY_CHECKER, VALID_ASPECT_RATIOS,
40
+ )
41
+ from tools.managed_tool_gateway import resolve_managed_tool_gateway
42
+ from tools.tool_backend_helpers import (
43
+ NOUS_MANAGED_PROVIDER, fal_key_is_configured, managed_nous_tools_enabled,
44
+ nous_tool_gateway_unavailable_message, read_selection, selection_error)
45
+
46
+ logger = logging.getLogger(__name__)
47
+
48
+ _debug = DebugSession("image_tools", env_var="IMAGE_TOOLS_DEBUG")
49
+ _managed_fal_client = None
50
+ _managed_fal_client_config = None
51
+ _managed_fal_client_lock = threading.Lock()
52
+
53
+
54
+ # --- Managed FAL gateway (Nous Subscription) ---
55
+ def _resolve_managed_fal_gateway():
56
+ """Managed gateway config for the stored `hermes tools` selection, or ``None`` for direct FAL.
57
+
58
+ ``"nous"`` (or legacy ``use_gateway: true``) → managed ONLY (unreachable = selection-naming
59
+ error, never a silent FAL_KEY fallback). Other stored provider → direct ONLY (missing FAL_KEY
60
+ = error naming the selection). Never configured → autodetect: direct if FAL_KEY, else managed.
61
+ """
62
+ selected = read_selection("image_gen")
63
+ if selected == NOUS_MANAGED_PROVIDER:
64
+ gateway = resolve_managed_tool_gateway("fal-queue")
65
+ if gateway is None:
66
+ raise ValueError(selection_error(
67
+ "image_gen", NOUS_MANAGED_PROVIDER,
68
+ "the Nous Tool Gateway is not available (not entitled or unreachable)"))
69
+ return gateway
70
+ if selected is not None:
71
+ if fal_key_is_configured():
72
+ return None
73
+ raise ValueError(selection_error("image_gen", selected, "FAL_KEY is not set"))
74
+ # Never-configured category: legacy credential autodetect (do NOT persist).
75
+ return None if fal_key_is_configured() else resolve_managed_tool_gateway("fal-queue")
76
+
77
+
78
+ def _get_managed_fal_client(managed_gateway):
79
+ """Reuse the managed FAL client so its internal httpx.Client is not leaked per call."""
80
+ global _managed_fal_client, _managed_fal_client_config
81
+ client_config = (managed_gateway.gateway_origin.rstrip("/"), managed_gateway.nous_user_token)
82
+ with _managed_fal_client_lock:
83
+ if _managed_fal_client is None or _managed_fal_client_config != client_config:
84
+ # Resolved on this module so monkeypatching ``image_generation_tool.fal_client`` still applies.
85
+ _managed_fal_client = _ManagedFalSyncClient(
86
+ _load_fal_client(), key=managed_gateway.nous_user_token,
87
+ queue_run_origin=managed_gateway.gateway_origin)
88
+ _managed_fal_client_config = client_config
89
+ return _managed_fal_client
90
+
91
+
92
+ class ImageGenerationInterrupted(Exception):
93
+ """Raised when the user interrupts while a FAL job is in flight."""
94
+
95
+
96
+ def _wait_fal_result(handler, *, poll_seconds: float = 0.5):
97
+ """Interrupt-aware ``handler.get()``: the SDK blocks 30-60s, hiding user interrupts.
98
+
99
+ The get runs on a daemon worker; the interrupt bit is polled between join slices and on
100
+ interrupt the worker is abandoned (remote job keeps running).
101
+ """
102
+ from tools.interrupt import is_interrupted
103
+ result_box: list = []
104
+ error_box: list = []
105
+ def _get():
106
+ try:
107
+ result_box.append(handler.get())
108
+ except BaseException as exc: # noqa: BLE001 — re-raised on the caller thread
109
+ error_box.append(exc)
110
+ worker = threading.Thread(target=_get, daemon=True, name="fal-result-wait")
111
+ worker.start()
112
+ while worker.is_alive():
113
+ if is_interrupted():
114
+ raise ImageGenerationInterrupted(
115
+ "Image generation interrupted by user — abandoned the in-flight FAL job.")
116
+ worker.join(timeout=poll_seconds)
117
+ if error_box:
118
+ raise error_box[0]
119
+ return result_box[0] if result_box else None
120
+
121
+
122
+ def _submit_fal_request(model: str, arguments: Dict[str, Any]):
123
+ """Submit a FAL request using direct credentials or the managed queue gateway."""
124
+ _load_fal_client()
125
+ request_headers = {"x-idempotency-key": str(uuid.uuid4())}
126
+ managed_gateway = _resolve_managed_fal_gateway()
127
+ if managed_gateway is None:
128
+ return fal_client.submit(model, arguments=arguments, headers=request_headers)
129
+ try:
130
+ return _get_managed_fal_client(managed_gateway).submit(
131
+ model, arguments=arguments, headers=request_headers)
132
+ except Exception as exc:
133
+ # A managed-gateway 4xx usually means the portal doesn't proxy this model
134
+ # (allowlist miss, billing gate): give remediation instead of a raw httpx error.
135
+ status = _extract_http_status(exc)
136
+ if status is not None and 400 <= status < 500:
137
+ billing = _managed_fal_billing_error(exc, "model")
138
+ if billing is not None:
139
+ raise ValueError(
140
+ f"Nous Subscription gateway rejected model '{model}' (HTTP {status}): {billing}") from exc
141
+ gateway_message = ""
142
+ if status in {401, 402, 403}:
143
+ gateway_message = "\n\n" + nous_tool_gateway_unavailable_message(
144
+ "managed FAL image generation", force_fresh=True)
145
+ raise ValueError(
146
+ f"Nous Subscription gateway rejected model '{model}' (HTTP {status}). This model "
147
+ f"may not yet be enabled on the Nous Portal's FAL proxy. Either:\n"
148
+ f" • Set FAL_KEY in your environment to use FAL.ai directly, or\n"
149
+ f" • Pick a different model via `hermes tools` → Image Generation."
150
+ f"{gateway_message}") from exc
151
+ raise
152
+
153
+
154
+ # --- Config readers, model resolution + payload construction ---
155
+ def _read_image_gen_key(key: str) -> Optional[str]:
156
+ """Return the stripped ``image_gen.<key>`` string from config.yaml, or None."""
157
+ try:
158
+ from hermes_cli.config import load_config
159
+ cfg = load_config()
160
+ section = cfg.get("image_gen") if isinstance(cfg, dict) else None
161
+ value = section.get(key) if isinstance(section, dict) else None
162
+ if isinstance(value, str) and value.strip():
163
+ return value.strip()
164
+ except Exception as exc:
165
+ logger.debug("Could not read image_gen.%s: %s", key, exc)
166
+ return None
167
+
168
+
169
+ def _read_configured_image_model():
170
+ """``image_gen.model`` from config.yaml, or None."""
171
+ return _read_image_gen_key("model")
172
+
173
+
174
+ def _read_configured_image_provider():
175
+ """``image_gen.provider`` from config.yaml, or None (unset keeps the in-tree FAL fallback even
176
+ when other providers are registered; ``"fal"`` routes via ``plugins/image_gen/fal/``).
177
+
178
+ We only consult the plugin registry when this is explicitly set — an unset value keeps users on the
179
+ in-tree FAL fallback even when other providers happen to be registered (e.g. a user has OPENAI_API_KEY
180
+ set for other features but never asked for OpenAI image gen). ``"fal"`` explicitly routes through
181
+ ``plugins/image_gen/fal/`` (which delegates back into this module's pipeline via call-time indirection —
182
+ see issue #26241).
183
+ """
184
+ return _read_image_gen_key("provider")
185
+
186
+
187
+ def _plugin_provider_name() -> Optional[str]:
188
+ """Configured provider that must go through the plugin registry; None for unset/fal/nous."""
189
+ configured = _read_configured_image_provider()
190
+ if not configured or configured in ("fal", NOUS_MANAGED_PROVIDER):
191
+ return None
192
+ return configured
193
+
194
+
195
+ def _resolve_fal_model() -> tuple:
196
+ """Return ``(model_id, meta)`` for the configured FAL model, falling back to DEFAULT_MODEL (warned) when unknown."""
197
+ # FAL_IMAGE_MODEL is an undocumented escape hatch (backward-compat for tests/scripts).
198
+ model_id = _read_image_gen_key("model") or os.getenv("FAL_IMAGE_MODEL", "").strip()
199
+ if model_id and model_id not in FAL_MODELS:
200
+ logger.warning("Unknown FAL model '%s' in config; falling back to %s", model_id, DEFAULT_MODEL)
201
+ model_id = None
202
+ model_id = model_id or DEFAULT_MODEL
203
+ return model_id, FAL_MODELS[model_id]
204
+
205
+
206
+ _SIZE_KEY_BY_STYLE = {"image_size_preset": "image_size", "gpt_literal": "image_size",
207
+ "aspect_ratio": "aspect_ratio"}
208
+
209
+
210
+ def _build_payload(model_id, prompt, aspect_ratio, seed, overrides, image_urls=None) -> Dict[str, Any]:
211
+ """Text-to-image / edit payload (``image_urls`` selects edit mode): defaults + native size
212
+ spec + overrides, filtered to the model whitelist.
213
+
214
+ Edit endpoints mostly auto-infer size, so the size key is sent only when ``edit_supports``
215
+ lists it. ``prompt`` (and the source-image key on edits) survive a whitelist gap: every FAL
216
+ endpoint requires them, so a catalog mistake can't send a broken request.
217
+ """
218
+ meta = FAL_MODELS[model_id]
219
+ edit = image_urls is not None
220
+ supports = (meta.get("edit_supports") or set()) if edit else meta["supports"]
221
+ sizes = meta["sizes"]
222
+ aspect = (aspect_ratio or DEFAULT_ASPECT_RATIO).lower().strip()
223
+ if aspect not in sizes:
224
+ aspect = DEFAULT_ASPECT_RATIO
225
+ payload: Dict[str, Any] = dict(meta.get("defaults", {}))
226
+ payload["prompt"] = (prompt or "").strip()
227
+ required = {"prompt"}
228
+ if edit: # a few edit endpoints (Kling Image v3) take a singular `image_url` string instead of the list
229
+ image_param = meta.get("edit_image_param") or "image_urls"
230
+ payload[image_param] = list(image_urls)[0] if image_param != "image_urls" else list(image_urls)
231
+ required.add(image_param)
232
+ size_key = _SIZE_KEY_BY_STYLE.get(meta["size_style"])
233
+ if size_key is None and not edit:
234
+ raise ValueError(f"Unknown size_style: {meta['size_style']!r}")
235
+ if size_key is not None and (not edit or size_key in supports):
236
+ payload[size_key] = sizes[aspect]
237
+ if isinstance(seed, int):
238
+ payload["seed"] = seed
239
+ payload.update({k: v for k, v in (overrides or {}).items() if v is not None})
240
+ return {k: v for k, v in payload.items() if k in supports or k in required}
241
+
242
+
243
+ def _build_fal_payload(model_id, prompt, aspect_ratio=DEFAULT_ASPECT_RATIO, seed=None, overrides=None):
244
+ """FAL text-to-image payload for ``model_id`` from unified inputs."""
245
+ return _build_payload(model_id, prompt, aspect_ratio, seed, overrides)
246
+
247
+
248
+ def _build_fal_edit_payload(model_id, prompt, image_urls, aspect_ratio=DEFAULT_ASPECT_RATIO,
249
+ seed=None, overrides=None):
250
+ """FAL *edit* (image-to-image) payload: ``image_urls`` + prompt, filtered to ``edit_supports``."""
251
+ return _build_payload(model_id, prompt, aspect_ratio, seed, overrides, image_urls=image_urls)
252
+
253
+
254
+ # --- Upscaler ---
255
+ def _upscale_image(image_url: str, original_prompt: str) -> Optional[Dict[str, Any]]:
256
+ """Upscale via FAL's Clarity Upscaler; None on failure (caller keeps the original)."""
257
+ try:
258
+ logger.info("Upscaling image with Clarity Upscaler...")
259
+ handler = _submit_fal_request(UPSCALER_MODEL, arguments={
260
+ "image_url": image_url, "prompt": f"{UPSCALER_DEFAULT_PROMPT}, {original_prompt}",
261
+ "upscale_factor": UPSCALER_FACTOR, "negative_prompt": UPSCALER_NEGATIVE_PROMPT,
262
+ "creativity": UPSCALER_CREATIVITY, "resemblance": UPSCALER_RESEMBLANCE,
263
+ "guidance_scale": UPSCALER_GUIDANCE_SCALE,
264
+ "num_inference_steps": UPSCALER_NUM_INFERENCE_STEPS,
265
+ "enable_safety_checker": UPSCALER_SAFETY_CHECKER})
266
+ result = _wait_fal_result(handler)
267
+ if result and "image" in result:
268
+ up = result["image"]
269
+ logger.info("Image upscaled successfully to %sx%s",
270
+ up.get("width", "unknown"), up.get("height", "unknown"))
271
+ return {
272
+ "url": up["url"], "width": up.get("width", 0), "height": up.get("height", 0),
273
+ "upscaled": True, "upscale_factor": UPSCALER_FACTOR}
274
+ logger.error("Upscaler returned invalid response")
275
+ return None
276
+ except ImageGenerationInterrupted:
277
+ # A user interrupt must not degrade into a silent "use original" fallback.
278
+ raise
279
+ except Exception as e:
280
+ logger.error("Error upscaling image: %s", e, exc_info=True)
281
+ return None
282
+
283
+
284
+ # --- Artifact path hinting for non-local terminal backends ---
285
+ _CONTAINER_HOME_ENVS = {"DockerEnvironment", "SingularityEnvironment", "ModalEnvironment"}
286
+ # No env yet: only deterministic cache roots translate side-effect free (SSH: tilde path; its
287
+ # first sync uploads the cache file).
288
+ _CACHE_BASE_BY_BACKEND = {"docker": "/root/.hermes", "singularity": "/root/.hermes",
289
+ "modal": "/root/.hermes", "ssh": "~/.hermes"}
290
+
291
+
292
+ def _looks_like_absolute_file_path(value: str) -> bool:
293
+ if not value or not isinstance(value, str) or value.lower().startswith(("http://", "https://", "data:")):
294
+ return False
295
+ return os.path.isabs(value) or (len(value) >= 3 and value[1] == ":" and value[2] in {"/", "\\"})
296
+
297
+
298
+ def _active_terminal_env(task_id: str | None):
299
+ try:
300
+ from tools.terminal_tool_lifecycle import get_active_env
301
+ return get_active_env(task_id or "default")
302
+ except Exception as exc: # noqa: BLE001 - artifact hinting must not break generation
303
+ logger.debug("Could not inspect active terminal environment: %s", exc)
304
+ return None
305
+
306
+
307
+ def _agent_cache_base_for_env(env: Any) -> str | None:
308
+ if env is not None:
309
+ # Optional extension hook: an environment may expose its own agent-visible cache root.
310
+ explicit = getattr(env, "agent_visible_cache_base", None)
311
+ if callable(explicit):
312
+ try:
313
+ value = explicit()
314
+ if value:
315
+ return str(value).rstrip("/")
316
+ except Exception as exc: # noqa: BLE001
317
+ logger.debug("active env agent_visible_cache_base failed: %s", exc)
318
+ remote_home = getattr(env, "_remote_home", None)
319
+ if remote_home:
320
+ return f"{str(remote_home).rstrip('/')}/.hermes"
321
+ if env.__class__.__name__ in _CONTAINER_HOME_ENVS:
322
+ return "/root/.hermes"
323
+ from tools.terminal_scope import terminal_env
324
+ backend = (terminal_env("TERMINAL_ENV") or "local").strip().lower()
325
+ return _CACHE_BASE_BY_BACKEND.get(backend)
326
+
327
+
328
+ def _postprocess_image_generate_result(raw: str, task_id: str | None = None) -> str:
329
+ """Annotate successful local results: ``image`` stays the host/gateway-deliverable path;
330
+ ``agent_visible_image`` is the same file as seen by a non-local terminal backend."""
331
+ try:
332
+ payload = json.loads(raw) if isinstance(raw, str) else raw
333
+ except Exception:
334
+ return raw
335
+ if not isinstance(payload, dict) or not payload.get("success"):
336
+ return raw
337
+ image = payload.get("image")
338
+ if not isinstance(image, str) or not _looks_like_absolute_file_path(image):
339
+ return raw
340
+ env = _active_terminal_env(task_id)
341
+ cache_base = _agent_cache_base_for_env(env)
342
+ if not cache_base:
343
+ return raw
344
+ try:
345
+ from tools.credential_files import map_cache_path_to_container
346
+ agent_path = map_cache_path_to_container(image, container_base=cache_base)
347
+ except Exception as exc: # noqa: BLE001
348
+ logger.debug("Could not translate image cache path for backend: %s", exc)
349
+ return raw
350
+ if not agent_path or agent_path == image:
351
+ return raw
352
+ sync_manager = getattr(env, "_sync_manager", None)
353
+ if sync_manager is not None:
354
+ try:
355
+ sync_manager.sync(force=True)
356
+ except Exception as exc: # noqa: BLE001 - keep generation success; log for operators
357
+ logger.warning("Could not force-sync generated image artifact: %s", exc)
358
+ payload.setdefault("host_image", image)
359
+ payload.setdefault("agent_visible_image", agent_path)
360
+ return json.dumps(payload, ensure_ascii=False)
361
+
362
+
363
+ # --- Tool entry point ---
364
+ def _format_images(images: list, should_upscale: bool, prompt: str) -> list:
365
+ """Normalize FAL result images, optionally chaining the upscaler (falls back to the original on failure)."""
366
+ formatted = []
367
+ for img in images:
368
+ if not (isinstance(img, dict) and "url" in img):
369
+ continue
370
+ if should_upscale:
371
+ upscaled = _upscale_image(img["url"], prompt.strip())
372
+ if upscaled:
373
+ formatted.append(upscaled)
374
+ continue
375
+ logger.warning("Using original image as fallback (upscale failed)")
376
+ formatted.append({
377
+ "url": img["url"], "width": img.get("width", 0), "height": img.get("height", 0),
378
+ "upscaled": False})
379
+ return formatted
380
+
381
+
382
+ def _prepare_fal_request(model_id, meta, prompt, aspect_ratio, seed, overrides, source_images):
383
+ """Validate inputs and return ``(endpoint, arguments)``; raises ValueError with the user-facing message."""
384
+ if not isinstance(prompt, str) or not prompt.strip():
385
+ raise ValueError("Prompt is required and must be a non-empty string")
386
+ # A stored-but-broken selection raises the selection-naming error from
387
+ # _resolve_managed_fal_gateway(); only never-configured reports "no backend at all".
388
+ if not (fal_key_is_configured() or _resolve_managed_fal_gateway()):
389
+ raise ValueError(_build_no_backend_setup_message())
390
+ edit_endpoint, display = meta.get("edit_endpoint"), meta.get("display", model_id)
391
+ # Fail clearly rather than silently dropping sources and producing an unrelated picture.
392
+ if source_images and not edit_endpoint:
393
+ raise ValueError(
394
+ f"Model '{display}' ({model_id}) is not capable of image-to-image / editing. "
395
+ f"Provide a text-only prompt (omit image_url), or switch to an edit-capable model "
396
+ f"via `hermes tools` → Image Generation.")
397
+ aspect_lc = (aspect_ratio or DEFAULT_ASPECT_RATIO).lower().strip()
398
+ if aspect_lc not in VALID_ASPECT_RATIOS:
399
+ logger.warning("Invalid aspect_ratio '%s', defaulting to '%s'", aspect_ratio, DEFAULT_ASPECT_RATIO)
400
+ aspect_lc = DEFAULT_ASPECT_RATIO
401
+ if source_images:
402
+ # Clamp reference count to the model's declared cap.
403
+ max_refs = int(meta.get("max_reference_images") or 1)
404
+ clamped_sources = source_images[:max_refs] if max_refs > 0 else source_images
405
+ arguments = _build_fal_edit_payload(
406
+ model_id, prompt, clamped_sources, aspect_lc, seed=seed, overrides=overrides)
407
+ logger.info("Editing image with %s (%s) — %d source image(s), prompt: %s",
408
+ display, edit_endpoint, len(clamped_sources), prompt[:80])
409
+ return edit_endpoint, arguments
410
+ arguments = _build_fal_payload(model_id, prompt, aspect_lc, seed=seed, overrides=overrides)
411
+ logger.info("Generating image with %s (%s) — prompt: %s", display, model_id, prompt[:80])
412
+ return model_id, arguments
413
+
414
+
415
+ def image_generate_tool(
416
+ prompt: str, aspect_ratio: str = DEFAULT_ASPECT_RATIO,
417
+ num_inference_steps: Optional[int] = None, guidance_scale: Optional[float] = None,
418
+ num_images: Optional[int] = None, output_format: Optional[str] = None,
419
+ seed: Optional[int] = None, image_url: Optional[str] = None,
420
+ reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None) -> str:
421
+ """Generate (or, with source images + an ``edit_endpoint`` model, edit) an image via FAL.
422
+
423
+ Extra kwargs are overrides filtered per-model via ``supports`` / ``edit_supports`` (dropped
424
+ silently so callers survive model switches). Returns JSON ``{"success", "image", "modality",
425
+ "error", "error_type"}``.
426
+ """
427
+ model_id, meta = _resolve_fal_model()
428
+ refs = reference_image_urls if isinstance(reference_image_urls, (list, tuple)) else []
429
+ source_images = [c.strip() for c in (image_url, *refs) if isinstance(c, str) and c.strip()]
430
+ use_edit = bool(source_images) and bool(meta.get("edit_endpoint"))
431
+ modality = "image" if use_edit else "text"
432
+ overrides: Dict[str, Any] = {
433
+ "num_inference_steps": num_inference_steps, "guidance_scale": guidance_scale,
434
+ "num_images": num_images, "output_format": output_format}
435
+ debug_call_data = {
436
+ "model": model_id,
437
+ "parameters": {"prompt": prompt, "aspect_ratio": aspect_ratio, **overrides, "seed": seed,
438
+ "modality": modality, "source_images": len(source_images)},
439
+ "error": None, "success": False, "images_generated": 0, "generation_time": 0}
440
+ start_time = datetime.datetime.now()
441
+
442
+ def finish(generation_time: float, response: Dict[str, Any]) -> str:
443
+ debug_call_data["generation_time"] = generation_time
444
+ _debug.log_call("image_generate_tool", debug_call_data)
445
+ _debug.save()
446
+ return json.dumps(response, indent=2, ensure_ascii=False)
447
+ try:
448
+ endpoint, arguments = _prepare_fal_request(
449
+ model_id, meta, prompt, aspect_ratio, seed,
450
+ {k: v for k, v in overrides.items() if v is not None}, source_images)
451
+ result = _wait_fal_result(_submit_fal_request(endpoint, arguments=arguments))
452
+ generation_time = (datetime.datetime.now() - start_time).total_seconds()
453
+ if not result or "images" not in result:
454
+ raise ValueError("Invalid response from FAL.ai API — no images returned")
455
+ images = result.get("images", [])
456
+ if not images:
457
+ raise ValueError("No images were generated")
458
+ # Explicit ``upscale`` wins, including for edits; the catalog default never upscales
459
+ # edits (Clarity is a text-to-image pass and must not silently alter compositions).
460
+ if upscale is not None:
461
+ should_upscale = bool(upscale)
462
+ else:
463
+ should_upscale = bool(meta.get("upscale", False)) and not use_edit
464
+ formatted_images = _format_images(images, should_upscale, prompt)
465
+ if not formatted_images:
466
+ raise ValueError("No valid image URLs returned from API")
467
+ upscaled_count = sum(1 for img in formatted_images if img.get("upscaled"))
468
+ logger.info("Generated %s image(s) in %.1fs (%s upscaled) via %s [%s]",
469
+ len(formatted_images), generation_time, upscaled_count, endpoint, modality)
470
+ debug_call_data["success"] = True
471
+ debug_call_data["images_generated"] = len(formatted_images)
472
+ return finish(generation_time, {
473
+ "success": True,
474
+ "image": formatted_images[0]["url"],
475
+ "modality": modality,
476
+ "upscaled": bool(formatted_images[0].get("upscaled"))})
477
+ except Exception as e:
478
+ error_msg = f"Error generating image: {str(e)}"
479
+ logger.error("%s", error_msg, exc_info=True)
480
+ debug_call_data["error"] = error_msg
481
+ generation_time = (datetime.datetime.now() - start_time).total_seconds()
482
+ return finish(generation_time,
483
+ {"success": False, "image": None, "error": str(e), "error_type": type(e).__name__})
484
+
485
+
486
+ def check_fal_api_key() -> bool:
487
+ """True if the selected FAL backend (never configured: any FAL backend) is available.
488
+
489
+ A stored-but-broken selection reports False here (registry gating); the naming error
490
+ surfaces at call time from ``_resolve_managed_fal_gateway``.
491
+ """
492
+ try:
493
+ gateway = _resolve_managed_fal_gateway()
494
+ except ValueError:
495
+ return False
496
+ return bool(gateway) or fal_key_is_configured()
497
+
498
+
499
+ def _build_no_backend_setup_message() -> str:
500
+ """Actionable no-backend error: FAL_KEY signup, managed-gateway status, plugin alternative."""
501
+ managed = managed_nous_tools_enabled()
502
+ lines = ["Image generation is unavailable in this environment.", "", "Missing requirements:"]
503
+ if managed:
504
+ lines.append(" - FAL_KEY is not set and the managed FAL gateway is unreachable")
505
+ else:
506
+ lines.append(" - FAL_KEY environment variable is not set")
507
+ if gateway_message := nous_tool_gateway_unavailable_message("managed FAL image generation"):
508
+ lines.append(f" - {gateway_message}")
509
+ lines += ["", "To enable image generation, do one of:",
510
+ " 1. Get a free API key at https://fal.ai and set FAL_KEY=<your-key> "
511
+ "(then restart the session)"]
512
+ if managed:
513
+ lines.append(" 2. Sign in to a Nous account that has the managed FAL gateway enabled "
514
+ "(`hermes setup`)")
515
+ lines.append(" 3. Configure a different image_gen provider via `hermes tools` → Image Generation "
516
+ "(run `hermes plugins list` to see installed backends)")
517
+ return "\n".join(lines)
518
+
519
+
520
+ def _get_plugin_provider(name: str, *, force: bool = False):
521
+ """Discover plugins (local import: importing this module must not trigger discovery) and return the named provider."""
522
+ from agent.image_gen_registry import get_provider
523
+ from hermes_cli.plugins import _ensure_plugins_discovered
524
+ if force:
525
+ _ensure_plugins_discovered(force=True)
526
+ else:
527
+ _ensure_plugins_discovered()
528
+ return get_provider(name)
529
+
530
+
531
+ def check_image_generation_requirements() -> bool:
532
+ """True if FAL or the explicitly configured image backend is available."""
533
+ try:
534
+ if check_fal_api_key():
535
+ # Lazy import doubles as the SDK presence check: ImportError falls through to plugins.
536
+ _load_fal_client()
537
+ return True
538
+ except ImportError:
539
+ pass
540
+ configured = _plugin_provider_name()
541
+ if configured is None:
542
+ return False
543
+ # Probe only the selected plugin: a cloud key alone must not opt a user into a paid backend.
544
+ provider = _get_plugin_provider(configured)
545
+ return bool(provider and provider.is_available())
546
+
547
+
548
+ # --- Registry ---
549
+ from tools.registry import registry, tool_error
550
+
551
+ IMAGE_GENERATE_SCHEMA = {
552
+ "name": "image_generate",
553
+ # Placeholder: description AND params are rebuilt at get_tool_definitions() time by
554
+ # _build_dynamic_image_schema() from the active backend's capabilities. Edit-only args
555
+ # and upscale are advertised ONLY when supported; the handler accepts them regardless
556
+ # (replay compat + teaching errors).
557
+ "description": (
558
+ "Generate images from text prompts. The active model's edit/reference "
559
+ "capabilities are rendered at serving time."
560
+ ),
561
+ "parameters": {
562
+ "type": "object",
563
+ "properties": {
564
+ "prompt": {
565
+ "type": "string",
566
+ "description": (
567
+ "The text prompt describing the desired image (text-to-"
568
+ "image) or the edit to apply (image-to-image). Be detailed "
569
+ "and descriptive."
570
+ ),
571
+ },
572
+ "aspect_ratio": {
573
+ "type": "string",
574
+ "enum": list(VALID_ASPECT_RATIOS),
575
+ "description": "The aspect ratio of the generated image. 'landscape' is 16:9 wide, 'portrait' is 16:9 tall, 'square' is 1:1.",
576
+ "default": DEFAULT_ASPECT_RATIO,
577
+ },
578
+ # image_url / reference_image_urls / upscale are added per-capability; never statically.
579
+ },
580
+ # See #95681.
581
+ "required": ["prompt"],
582
+ },
583
+ }
584
+
585
+
586
+ # --- Plugin provider dispatch + managed-mode Krea routing ---
587
+ def _provider_error(error: str, error_type: str) -> str:
588
+ """JSON error envelope shared by every provider-dispatch failure path."""
589
+ return json.dumps({"success": False, "image": None, "error": error, "error_type": error_type})
590
+
591
+
592
+ def _provider_result(result, contract_error: str) -> str:
593
+ """JSON-encode a provider's dict result; anything else is a contract violation."""
594
+ if not isinstance(result, dict):
595
+ return _provider_error(contract_error, "provider_contract")
596
+ return json.dumps(result)
597
+
598
+
599
+ def _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale, model=None) -> Dict[str, Any]:
600
+ """Add the optional ``provider.generate(**kwargs)`` args in place (edit args only when supplied)."""
601
+ if model:
602
+ kwargs["model"] = model
603
+ if isinstance(image_url, str) and image_url.strip():
604
+ kwargs["image_url"] = image_url.strip()
605
+ if reference_image_urls is not None:
606
+ from agent.image_gen_provider import normalize_reference_images
607
+ norm_refs = normalize_reference_images(reference_image_urls)
608
+ if norm_refs:
609
+ kwargs["reference_image_urls"] = norm_refs
610
+ if upscale is not None:
611
+ kwargs["upscale"] = bool(upscale)
612
+ return kwargs
613
+
614
+
615
+ def _dispatch_to_plugin_provider(
616
+ prompt: str, aspect_ratio: str, image_url: Optional[str] = None,
617
+ reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None):
618
+ """JSON result from the selected plugin provider, or ``None`` to fall through to in-tree FAL
619
+ (provider unset / ``"fal"`` / ``"nous"``). Providers without ``upscale`` ignore it via ``**kwargs``."""
620
+ configured = _plugin_provider_name()
621
+ if configured is None:
622
+ return None
623
+ try:
624
+ provider = _get_plugin_provider(configured)
625
+ except Exception as exc:
626
+ logger.debug("image_gen plugin dispatch skipped: %s", exc)
627
+ return None
628
+ if provider is None:
629
+ # Long-lived sessions may have discovered plugins before a bundled backend
630
+ # was patched in or config changed: retry once with a forced refresh.
631
+ try:
632
+ provider = _get_plugin_provider(configured, force=True)
633
+ except Exception as exc:
634
+ logger.debug("image_gen plugin force-refresh skipped: %s", exc)
635
+ if provider is None:
636
+ return _provider_error(
637
+ f"image_gen.provider='{configured}' is set but no plugin registered that name. "
638
+ f"Run `hermes plugins list` to see available image gen backends.", "provider_not_registered")
639
+ pname = getattr(provider, "name", "?")
640
+ kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio}
641
+ try:
642
+ _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale,
643
+ model=_read_configured_image_model())
644
+ result = provider.generate(**kwargs)
645
+ except Exception as exc:
646
+ # A TypeError from generate() predating image_url support (third-party plugin not yet
647
+ # updated): text-to-image keeps working; surface a clear note when an edit was requested.
648
+ is_type_error = isinstance(exc, TypeError)
649
+ if is_type_error and ("image_url" in kwargs or "reference_image_urls" in kwargs):
650
+ logger.warning("image_gen provider '%s' rejected image-to-image kwargs "
651
+ "(signature too narrow): %s", pname, exc)
652
+ return _provider_error(
653
+ f"Provider '{pname}' does not support image-to-image / editing (its generate() "
654
+ f"signature is out of date with the image_generate schema). Omit image_url for "
655
+ f"text-to-image, or pick a backend that supports editing via `hermes tools` → "
656
+ f"Image Generation.", "modality_unsupported")
657
+ logger.warning("Image gen provider '%s' raised%s: %s", pname,
658
+ " TypeError" if is_type_error else "", exc)
659
+ return _provider_error(f"Provider '{pname}' error: {exc}", "provider_exception")
660
+ return _provider_result(result, "Provider returned a non-dict result")
661
+
662
+
663
+ # Native ``krea-2-*`` ids are served by the Krea managed gateway (managed mode only —
664
+ # direct/BYO users keep their pipeline); ``fal-ai/krea/v2/*`` catalog ids stay on FAL.
665
+ _KREA_NATIVE_MODELS = {"krea-2-medium", "krea-2-large", "krea-2-medium-turbo"}
666
+
667
+
668
+ def _normalize_krea_model(model_id: Optional[str]) -> Optional[str]:
669
+ """Return the native Krea plugin model id when ``model_id`` is ``krea-2-*``."""
670
+ candidate = model_id.strip() if isinstance(model_id, str) else None
671
+ return candidate if candidate in _KREA_NATIVE_MODELS else None
672
+
673
+
674
+ def _maybe_route_managed_krea(
675
+ prompt: str, aspect_ratio: str, image_url: Optional[str] = None,
676
+ reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None) -> Optional[str]:
677
+ """JSON result from the managed Krea gateway, or ``None`` to fall through.
678
+
679
+ Fires only for a native ``krea-2-*`` model with no ``image_gen.provider`` other than
680
+ ``"nous"`` stored (a picker choice dispatches normally) and a resolvable Krea gateway.
681
+ """
682
+ configured_provider = _read_configured_image_provider()
683
+ if configured_provider is not None and configured_provider != NOUS_MANAGED_PROVIDER:
684
+ return None
685
+ normalized = _normalize_krea_model(_read_configured_image_model())
686
+ if normalized is None:
687
+ return None
688
+ try:
689
+ from plugins.image_gen.krea import _resolve_managed_krea_gateway
690
+ if _resolve_managed_krea_gateway() is None:
691
+ return None
692
+ provider = _get_plugin_provider("krea")
693
+ except Exception as exc: # noqa: BLE001
694
+ logger.debug("Managed Krea routing unavailable: %s", exc)
695
+ return None
696
+ if provider is None:
697
+ return None
698
+ kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio, "model": normalized}
699
+ try:
700
+ _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale)
701
+ result = provider.generate(**kwargs)
702
+ except Exception as exc: # noqa: BLE001
703
+ logger.warning("Managed Krea routing failed: %s", exc)
704
+ return _provider_error(f"Managed Krea generation error: {exc}", "provider_exception")
705
+ return _provider_result(result, "Krea provider returned a non-dict result")
706
+
707
+
708
+ def _confine_source_images(image_url, reference_image_urls, task_id, *, permitted: tuple = ("image",)):
709
+ """Resolve path-like sources to ``data:`` URLs under a non-local terminal backend.
710
+
711
+ Routes through ``tools.image_source`` (in-sandbox exec-read, media-cache host reads,
712
+ credential guard) so generation obeys the same confinement as vision. URLs/data: pass
713
+ through; local backend is a no-op. Returns ``(image_url, reference_image_urls, error_json_or_None)``.
714
+ """
715
+ from tools.terminal_scope import terminal_env
716
+ if (terminal_env("TERMINAL_ENV") or "local").strip().lower() in ("", "local"):
717
+ return image_url, reference_image_urls, None
718
+ from model_tools import _run_async
719
+ from tools.image_source import ImageResolutionError, resolve_local_source_to_data_url
720
+
721
+ def resolve(ref):
722
+ return _run_async(resolve_local_source_to_data_url(ref, task_id, permitted=permitted))
723
+ try:
724
+ if isinstance(image_url, str) and image_url.strip():
725
+ image_url = resolve(image_url)
726
+ if isinstance(reference_image_urls, (list, tuple)):
727
+ reference_image_urls = [resolve(r) if isinstance(r, str) else r for r in reference_image_urls]
728
+ except ImageResolutionError as exc:
729
+ return image_url, reference_image_urls, _provider_error(
730
+ f"Could not read source image: {exc}", type(exc).__name__)
731
+ return image_url, reference_image_urls, None
732
+
733
+
734
+ def _handle_image_generate(args, **kw):
735
+ prompt = args.get("prompt", "")
736
+ if not prompt:
737
+ return tool_error("prompt is required for image generation")
738
+ aspect_ratio = args.get("aspect_ratio", DEFAULT_ASPECT_RATIO)
739
+ upscale = args.get("upscale")
740
+ task_id = kw.get("task_id")
741
+ # Confinement chokepoint BEFORE any dispatch: every route receives sandbox-confined bytes.
742
+ image_url, reference_image_urls, confine_error = _confine_source_images(
743
+ args.get("image_url"), args.get("reference_image_urls"), task_id)
744
+ if confine_error is not None:
745
+ return confine_error
746
+ # Order matters: explicit plugin provider (incl. "krea"), then model-driven managed Krea
747
+ # interception (only when no provider is set, so BYO/direct FAL stays untouched), then FAL.
748
+ sources = dict(image_url=image_url, reference_image_urls=reference_image_urls,
749
+ upscale=upscale if isinstance(upscale, bool) else None)
750
+ raw = None
751
+ for route in (_dispatch_to_plugin_provider, _maybe_route_managed_krea, image_generate_tool):
752
+ raw = route(prompt, aspect_ratio, **sources)
753
+ if raw is not None:
754
+ break
755
+ return _postprocess_image_generate_result(raw, task_id=task_id)
756
+
757
+
758
+ # --- Dynamic schema — reflect the active backend's image-to-image capability ---
759
+ # Advertising edit capability up front saves a wasted turn. Memoized by config.yaml mtime in
760
+ # model_tools.get_tool_definitions(), so it rebuilds on switch.
761
+ _NO_CAPABILITIES = {"modalities": ["text"], "max_reference_images": 0, "supports_upscale": False}
762
+
763
+
764
+ def _active_image_capabilities() -> Dict[str, Any]:
765
+ """Best-effort capabilities of the active backend/model; never raises.
766
+
767
+ Mirrors runtime dispatch: a set ``image_gen.provider`` asks that plugin, else the FAL
768
+ catalog. Fail-closed: an undeclared capability is advertised as absent.
769
+ """
770
+ info: Dict[str, Any] = dict(_NO_CAPABILITIES)
771
+ configured_provider = _read_configured_image_provider()
772
+ if configured_provider and configured_provider != "fal":
773
+ try:
774
+ provider = _get_plugin_provider(configured_provider)
775
+ if provider is not None:
776
+ try:
777
+ caps = provider.capabilities() or {}
778
+ except Exception: # noqa: BLE001
779
+ caps = {}
780
+ info["provider"] = provider.display_name
781
+ info["model"] = _read_configured_image_model() or (provider.default_model() or "")
782
+ if caps.get("modalities"):
783
+ info["modalities"] = list(caps["modalities"])
784
+ if caps.get("max_reference_images"):
785
+ info["max_reference_images"] = int(caps["max_reference_images"])
786
+ # Plugins opt in explicitly; absent = no upscale param.
787
+ info["supports_upscale"] = bool(caps.get("supports_upscale"))
788
+ return info
789
+ except Exception: # noqa: BLE001
790
+ pass
791
+ # In-tree FAL path (provider unset or == "fal"); _resolve_fal_model() never raises.
792
+ model_id, meta = _resolve_fal_model()
793
+ can_edit = bool(meta.get("edit_endpoint"))
794
+ info["provider"] = "FAL.ai"
795
+ info["model"] = meta.get("display", model_id)
796
+ info["modalities"] = ["text", "image"] if can_edit else ["text"]
797
+ info["max_reference_images"] = int(meta.get("max_reference_images") or 1) if can_edit else 0
798
+ # Clarity is available on request for ANY catalog model (``upscale`` is only the default).
799
+ info["supports_upscale"] = True
800
+ return info
801
+
802
+
803
+ # Param snippets assembled per-capability by _build_dynamic_image_schema.
804
+ _IMAGE_URL_PARAM = {
805
+ "type": "string",
806
+ "description": (
807
+ "Source image to edit/transform (image-to-image). A public URL or "
808
+ "an absolute local file path from the conversation. Omit for "
809
+ "text-to-image."
810
+ ),
811
+ }
812
+
813
+ _UPSCALE_PARAM = {
814
+ "type": "boolean",
815
+ "description": (
816
+ "Post-generation high-resolution pass (~2x, extra cost/latency), "
817
+ "off by default. A creative enhancer that can alter fine detail "
818
+ "(rendered text, faces) — use only when resolution matters more "
819
+ "than fidelity."
820
+ ),
821
+ }
822
+
823
+
824
+ def _build_dynamic_image_schema() -> Dict[str, Any]:
825
+ """Render description AND params from the active model's capabilities; args it cannot
826
+ honor are NOT advertised (the handler still accepts them for replay compat)."""
827
+ base_desc = (
828
+ "Generate high-quality images from text prompts{edit_clause}. "
829
+ "Returns the result in the `image` field — a URL or an absolute "
830
+ "file path; reference it in your response using the current "
831
+ "platform's file-delivery convention."
832
+ )
833
+ info = _active_image_capabilities()
834
+ max_refs = int(info.get("max_reference_images") or 0)
835
+ can_edit = "image" in set(info.get("modalities") or ["text"])
836
+ static_props = IMAGE_GENERATE_SCHEMA["parameters"]["properties"]
837
+ properties: Dict[str, Any] = {
838
+ "prompt": static_props["prompt"], "aspect_ratio": static_props["aspect_ratio"]}
839
+ if can_edit:
840
+ edit_clause = ", or edit / transform an existing image by passing image_url"
841
+ properties["image_url"] = _IMAGE_URL_PARAM
842
+ if max_refs > 1:
843
+ properties["reference_image_urls"] = {
844
+ "type": "array",
845
+ "items": {"type": "string"},
846
+ "maxItems": max_refs,
847
+ "description": (
848
+ f"Up to {max_refs} additional reference images (style, "
849
+ "character, or composition) guiding an edit. URLs or "
850
+ "absolute local paths."
851
+ ),
852
+ }
853
+ else:
854
+ edit_clause = " (text-to-image only — the active model cannot edit existing images)"
855
+ if info.get("supports_upscale"):
856
+ properties["upscale"] = _UPSCALE_PARAM
857
+ return {"description": base_desc.format(edit_clause=edit_clause),
858
+ "parameters": {"type": "object", "properties": properties, "required": ["prompt"]}}
859
+
860
+
861
+ registry.register(
862
+ name="image_generate", toolset="image_gen", schema=IMAGE_GENERATE_SCHEMA,
863
+ handler=_handle_image_generate, check_fn=check_image_generation_requirements, requires_env=[],
864
+ is_async=False, # sync fal_client API to avoid "Event loop is closed" in gateway
865
+ emoji="🎨", dynamic_schema_overrides=_build_dynamic_image_schema,
866
+ )
867
+
868
+
869
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
870
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
871
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
872
+ # The whole block is removed by reverting the commit that added it.
873
+
874
+ def is_krea_model(model_id: Optional[str]) -> bool:
875
+ """True when ``model_id`` is a native Krea plugin id (``krea-2-*``)."""
876
+ return _normalize_krea_model(model_id) is not None
877
+ # ---- END PLUGIN-COMPAT ----
tools/image_source.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single resolver for every media source (data:/http(s)/file/local/container) -> bytes + mime.
2
+
3
+ Everything funnels through :func:`resolve_image_source` so size and magic-byte checks run
4
+ exactly once. Images are the default; video callers opt in via ``permitted=("video",)``.
5
+ Security (GHSA-gpxw-6wxv-w3qq): under a non-local backend vision is confined like the file
6
+ tools — host-read only inside a media cache (bind-mounted into the sandbox), anything else is
7
+ exec-read *inside the sandbox*, so ``vision_analyze('/etc/passwd')`` never reads the host.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import base64
13
+ import os
14
+ import re
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Optional
18
+
19
+ # Raw-bytes INGEST budget: deliberately the 50MB download cap, NOT the 20MB provider
20
+ # payload cap — that one is enforced post-resize at the call sites.
21
+ _MAX_INGEST_BYTES = 50 * 1024 * 1024
22
+
23
+
24
+ class ImageResolutionError(Exception):
25
+ def __init__(self, message: str, *, src: str = "", origin: str = ""):
26
+ super().__init__(message)
27
+ self.src, self.origin = src, origin
28
+
29
+
30
+ class UnsupportedScheme(ImageResolutionError): ...
31
+ class SourceUnsafe(ImageResolutionError): ... # SSRF / path-allowlist
32
+ class SourceTooLarge(ImageResolutionError): ...
33
+ class SourceNotFound(ImageResolutionError): ...
34
+ class NotAnImage(ImageResolutionError): ...
35
+
36
+
37
+ @dataclass
38
+ class ResolveContext:
39
+ task_id: Optional[str] = None
40
+
41
+
42
+ @dataclass
43
+ class ResolvedImage:
44
+ data: bytes
45
+ mime: str
46
+ origin: str # one of: data | http | file | local | container
47
+
48
+
49
+ # Explicit URL scheme ("ftp://", "s3://"). Bare Windows drive paths lack the "//".
50
+ _SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*://")
51
+
52
+
53
+ async def resolve_image_source(
54
+ src: str, ctx: ResolveContext, *, permitted: tuple = ("image",)) -> ResolvedImage:
55
+ if not isinstance(src, str) or not src.strip():
56
+ raise SourceNotFound("image_url is required", src=str(src))
57
+ s = src.strip()
58
+ if s.startswith("data:"):
59
+ data, mime = _resolve_data_url(s)
60
+ return _finalize(data, mime, "data", s, permitted)
61
+ if s.startswith(("http://", "https://")):
62
+ reason = _http_block_reason(s)
63
+ if reason:
64
+ raise SourceUnsafe(reason, src=s)
65
+ return _finalize(await _download_to_bytes(s), "", "http", s, permitted)
66
+ if _SCHEME_RE.match(s) and not s.lower().startswith("file://"):
67
+ raise UnsupportedScheme(
68
+ "Unrecognized image source scheme. Use an http(s) URL, a local "
69
+ "file path, a file:// URI, or a data: URL.",
70
+ src=s)
71
+ # Everything else is a filesystem path — including bare relative names like "pic.png"
72
+ # (a path-shape gate here regressed them once).
73
+ candidate = s[len("file://"):] if s.lower().startswith("file://") else s
74
+ p = Path(os.path.expanduser(candidate))
75
+ host_target = _permitted_host_read_target(p, ctx)
76
+ if host_target is not None and host_target.is_file():
77
+ _guard_credential_read(host_target, s)
78
+ data = await asyncio.to_thread(host_target.read_bytes)
79
+ return _finalize(data, "", "file", s, permitted)
80
+ if _is_local_terminal_backend():
81
+ # Any path was host-readable, so a miss means the file doesn't exist.
82
+ raise SourceNotFound(f"media file not found: '{p}'", src=s, origin="file")
83
+ return await _resolve_container_fallback(p, ctx, s, permitted)
84
+
85
+
86
+ def _guard_credential_read(host_target: Path, src: str) -> None:
87
+ """Shared credential-read guard: refuse secret-bearing files (.env, auth.json) with a specific
88
+ error. Guard import is best-effort; a real block always propagates."""
89
+ try:
90
+ # Shared credential-read guard (agent.file_safety, #57698): refuse secret-bearing files (.env,
91
+ # auth.json, ...) with an intentional, specific error instead of relying on the magic-byte sniff to
92
+ # reject them incidentally. Same chokepoint the image-gen/video-gen provider plugins enforce on
93
+ # model-supplied local paths. Import is best-effort (guard unavailability must not break image
94
+ # loading); a real block always propagates.
95
+ from agent.file_safety import raise_if_read_blocked
96
+ except Exception: # noqa: BLE001 — guard unavailable: proceed
97
+ return
98
+ try:
99
+ raise_if_read_blocked(str(host_target))
100
+ except ValueError as exc:
101
+ raise SourceUnsafe(str(exc), src=src, origin="file")
102
+
103
+
104
+ def _resolve_data_url(s: str) -> tuple[bytes, str]:
105
+ header, _, payload = s.partition(",")
106
+ if ";base64" not in header:
107
+ raise NotAnImage("data: URL must be base64-encoded", src=s[:64])
108
+ declared = header[len("data:"):].split(";", 1)[0].strip() or "application/octet-stream"
109
+ # Cheap pre-decode size gate on the encoded length (~4/3 expansion).
110
+ if (len(payload) * 3) // 4 > _MAX_INGEST_BYTES:
111
+ raise SourceTooLarge("data: URL exceeds size limit", src=s[:64])
112
+ try:
113
+ data = base64.b64decode(payload, validate=True)
114
+ except Exception as exc:
115
+ raise NotAnImage(f"invalid base64 in data: URL: {exc}", src=s[:64])
116
+ return data, declared # real mime verified in _finalize via magic bytes
117
+
118
+
119
+ def _http_block_reason(url: str) -> Optional[str]:
120
+ """Block reason, or None when allowed. Refuses policy-blocked URLs BEFORE any network I/O;
121
+ ``_download_image`` re-checks per attempt and against the final redirect target (intentional)."""
122
+ from tools.url_safety import is_safe_url
123
+ from tools.website_policy import check_website_access
124
+ if not is_safe_url(url):
125
+ return "blocked: unsafe or private URL"
126
+ if blocked := check_website_access(url):
127
+ return blocked.get("message") or "blocked by website policy"
128
+ return None
129
+
130
+
131
+ async def _download_to_bytes(url: str) -> bytes:
132
+ import tempfile
133
+ from tools.vision_tools import _download_image
134
+ with tempfile.NamedTemporaryFile(suffix=".img", delete=False) as tf:
135
+ tmp = Path(tf.name)
136
+ try:
137
+ # Enforces the 50MB stream cap, redirect SSRF guard, and website policy.
138
+ await _download_image(url, tmp)
139
+ return await asyncio.to_thread(tmp.read_bytes)
140
+ except PermissionError as exc: # website policy block
141
+ raise SourceUnsafe(str(exc), src=url, origin="http")
142
+ finally:
143
+ tmp.unlink(missing_ok=True)
144
+
145
+
146
+ def _is_local_terminal_backend() -> bool:
147
+ """True when the terminal backend runs directly on the host (keys off ``TERMINAL_ENV``, read
148
+ through the per-turn terminal scope so a routed multiplex profile sees ITS backend)."""
149
+ from tools.terminal_scope import terminal_env
150
+ return terminal_env("TERMINAL_ENV", "local").strip().lower() in ("local", "")
151
+
152
+
153
+ # Host-side media caches: the only host paths vision may read under a non-local backend
154
+ # (gateway inbound media + the tools' own download temp dirs).
155
+ _MEDIA_CACHE_SUBDIRS = (
156
+ "cache", # cache/images, cache/vision, cache/video(s), cache/audio
157
+ "images", # desktop/clipboard/PDF uploads (tui_gateway)
158
+ "image_cache", "audio_cache", "video_cache", "temp_vision_images", "temp_video_files")
159
+
160
+
161
+ def _media_cache_roots() -> list:
162
+ from hermes_constants import get_hermes_home
163
+ home = get_hermes_home()
164
+ return [home / sub for sub in _MEDIA_CACHE_SUBDIRS]
165
+
166
+
167
+ def _permitted_host_read_target(p: Path, ctx: ResolveContext) -> Optional[Path]:
168
+ """Host path to read, or ``None`` (caller exec-reads inside the sandbox instead).
169
+
170
+ Local backend: any path. Non-local: only paths inside a media cache root (a
171
+ container-visible cache path is first translated back to its host mount).
172
+ """
173
+ if _is_local_terminal_backend():
174
+ try:
175
+ return p.resolve()
176
+ except Exception: # noqa: BLE001 — unresolved path: let is_file() fail downstream
177
+ return p
178
+ from tools.credential_files import from_agent_visible_cache_path
179
+ try:
180
+ real = Path(from_agent_visible_cache_path(str(p))).resolve()
181
+ except Exception: # noqa: BLE001 — cannot resolve -> not a safe host read
182
+ return None
183
+ if any(real.is_relative_to(root.resolve()) for root in _media_cache_roots()):
184
+ return real
185
+ return None
186
+
187
+
188
+ def _get_active_env(task_id: Optional[str]):
189
+ if not task_id:
190
+ return None
191
+ try:
192
+ from tools.terminal_tool_lifecycle import get_active_env
193
+ return get_active_env(task_id)
194
+ except Exception:
195
+ return None
196
+
197
+
198
+ def _ensure_container_env(task_id: Optional[str]) -> None:
199
+ """Lazily bring up the sandbox before an in-sandbox read (vision may be a session's first
200
+ action). Best-effort: failure leaves the env absent and the caller hits the fail-closed error.
201
+
202
+ Unlike the terminal tool, vision never triggered environment creation, so a session whose first action
203
+ is ``vision_analyze`` on a container-only path under a non-local backend found no active env and failed
204
+ — until a terminal command happened to create one (issue #62825).
205
+ """
206
+ if not task_id:
207
+ return
208
+ try:
209
+ from tools.terminal_tool import ensure_task_env
210
+ ensure_task_env(task_id)
211
+ except Exception:
212
+ pass
213
+
214
+
215
+ async def _resolve_container_fallback(
216
+ p: Path, ctx: ResolveContext, src: str, permitted: tuple = ("image",)) -> ResolvedImage:
217
+ """Read the bytes inside the sandbox; fail-closed when no env exists (a non-cache host
218
+ path under a sandbox must never leak via a host fallback).
219
+
220
+ Cold-start retry: under Docker the first exec against a fresh container can fail (empty
221
+ pipe) while a second succeeds. On final failure the container's output is folded into the
222
+ error so "no such file" / "permission denied" / "never came up" are distinguishable.
223
+
224
+ We retry once with a short delay before giving up, so callers don't see "could not read inside the
225
+ sandbox" on a file that is verifiably readable on the immediate retry. See #76566.
226
+ """
227
+ import shlex
228
+ # Bring the sandbox up on demand: without this, the first vision_analyze of a session (before any
229
+ # terminal command) has no active env to read from under a non-local backend (issue #62825).
230
+ _ensure_container_env(ctx.task_id)
231
+ env = _get_active_env(ctx.task_id)
232
+ if env is None:
233
+ raise SourceNotFound(
234
+ f"'{p}' is not reachable inside the sandbox and no active sandbox "
235
+ f"session is available to read it",
236
+ src=src, origin="container")
237
+ # Bound the read INSIDE the sandbox: head -c caps at ingest-limit+1 (+1 distinguishes "at the
238
+ # cap" from "over") so /dev/zero can't stream unbounded base64 into host memory. The input
239
+ # redirect avoids argv (leading-dash paths); tr -d instead of GNU-only base64 -w0 (BusyBox).
240
+ cmd = f"head -c {_MAX_INGEST_BYTES + 1} < {shlex.quote(str(p))} | base64 | tr -d '\\n'"
241
+ last_res: dict = {"returncode": 1, "output": ""}
242
+ for attempt in range(2):
243
+ last_res = await asyncio.to_thread(env.execute, cmd)
244
+ if last_res.get("returncode", 1) == 0:
245
+ break
246
+ if attempt == 0:
247
+ await asyncio.sleep(0.15) # covers Docker exec warm-up in practice
248
+ if last_res.get("returncode", 1) != 0:
249
+ diag = (last_res.get("output") or "").strip().splitlines()
250
+ first = next((ln.strip() for ln in diag if ln.strip()), "")
251
+ suffix = f" ({first[:200]})" if first else ""
252
+ raise SourceNotFound(f"could not read '{p}' inside the sandbox{suffix}", src=src, origin="container")
253
+ try:
254
+ data = base64.b64decode(last_res.get("output", ""), validate=True)
255
+ except Exception as exc:
256
+ raise NotAnImage(f"sandbox returned non-image data for '{p}': {exc}", src=src)
257
+ if len(data) > _MAX_INGEST_BYTES:
258
+ raise SourceTooLarge("media exceeds size limit", src=src, origin="container")
259
+ return _finalize(data, "", "container", src, permitted)
260
+
261
+
262
+ def _finalize(
263
+ data: bytes, declared_mime: str, origin: str, src: str, permitted: tuple = ("image",)
264
+ ) -> ResolvedImage:
265
+ """Chokepoint: 50MB ingest cap + type check. Images by magic bytes; video (opt-in) by
266
+ extension + mp4 sniff — enough because every downstream consumer re-validates."""
267
+ from tools.vision_tools_image_prep import _detect_image_mime_type_from_bytes
268
+ if len(data) > _MAX_INGEST_BYTES:
269
+ raise SourceTooLarge("media exceeds size limit", src=src, origin=origin)
270
+ sniffed = _detect_image_mime_type_from_bytes(data)
271
+ if sniffed is not None:
272
+ if "image" not in permitted:
273
+ raise NotAnImage("source is an image, but this argument takes a video", src=src, origin=origin)
274
+ return ResolvedImage(data=data, mime=sniffed, origin=origin)
275
+ if "image" in permitted and b"<svg" in data[:4096].lower():
276
+ # Pass SVG through — call sites rasterize it to PNG before embedding.
277
+ return ResolvedImage(data=data, mime="image/svg+xml", origin=origin)
278
+ if "video" in permitted:
279
+ video_mime = _detect_video_mime(data, src)
280
+ if video_mime is not None:
281
+ return ResolvedImage(data=data, mime=video_mime, origin=origin)
282
+ raise NotAnImage("source is not a recognized video (mp4 expected)", src=src, origin=origin)
283
+ raise NotAnImage("source is not a recognized image", src=src, origin=origin)
284
+
285
+
286
+ def _detect_video_mime(data: bytes, src: str) -> Optional[str]:
287
+ """Video MIME from the extension table, else the ISO base-media ``ftyp`` magic at
288
+ offset 4 (covers extensionless data: URLs / query-string URLs)."""
289
+ from urllib.parse import urlsplit
290
+ from tools.vision_tools import _detect_video_mime_type
291
+ path_part = urlsplit(src).path if _SCHEME_RE.match(src) else src
292
+ by_extension = _detect_video_mime_type(Path(path_part))
293
+ if by_extension is not None:
294
+ return by_extension
295
+ if len(data) > 12 and data[4:8] == b"ftyp":
296
+ return "video/mp4"
297
+ return None
298
+
299
+
300
+ async def resolve_local_source_to_data_url(
301
+ src: str, task_id: Optional[str], *, permitted: tuple = ("image",)) -> str:
302
+ """Convert a path-like media source into a ``data:`` URL via the resolver.
303
+
304
+ Dispatch-layer chokepoint for generation tools so providers never read model-supplied paths
305
+ off the HOST under a sandbox. URL-shaped sources pass through; callers apply this only under
306
+ a non-local backend.
307
+ """
308
+ s = (src or "").strip()
309
+ if not s or s.lower().startswith(("http://", "https://", "data:")):
310
+ return src
311
+ resolved = await resolve_image_source(s, ResolveContext(task_id=task_id), permitted=permitted)
312
+ encoded = base64.b64encode(resolved.data).decode("ascii")
313
+ mime = resolved.mime or "application/octet-stream"
314
+ return f"data:{mime};base64,{encoded}"
tools/interpreter_shutdown.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared interpreter-shutdown predicate for background threads that can outlive
2
+ process teardown (cron delivery, concurrent tool submission, retry paths).
3
+
4
+ Once finalization starts, ``concurrent.futures`` refuses new work and asyncio's
5
+ default executor is gone, so any further scheduling only produces noise (stray
6
+ prints after the TUI exited, tracebacks in ``errors.log``, futile retries).
7
+ CPython raises ``cannot schedule new futures after interpreter shutdown``
8
+ (module-global flag) or ``... after shutdown`` (a pool whose ``shutdown()`` ran);
9
+ the short prefix catches both — safe here because every pool involved is a
10
+ module-global daemon or a ``with``-scoped local only finalization can shut down.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import sys
16
+ from typing import Optional
17
+
18
+
19
+ def interpreter_shutting_down(exc: Optional[BaseException] = None) -> bool:
20
+ """True when the interpreter is finalizing. ``exc`` lets a caller treat an
21
+ already-raised scheduling error as a shutdown signal: the ``concurrent.futures``
22
+ flag can be set a hair before ``sys.is_finalizing()`` flips."""
23
+ if sys.is_finalizing():
24
+ return True
25
+ return exc is not None and "cannot schedule new futures" in str(exc).lower()
tools/interrupt.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-thread interrupt signaling for all tools: thread-scoped so interrupting one
2
+ agent session does not kill tools in other sessions (the gateway runs many agents in one
3
+ process). The agent passes its execution thread id to set_interrupt(); tools call
4
+ is_interrupted(), which checks the CURRENT thread."""
5
+
6
+ import logging
7
+ import os
8
+ import threading
9
+ from collections.abc import Callable
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ # Opt-in debug tracing — pairs with HERMES_DEBUG_INTERRUPT in tools/environments/base.py.
14
+ _DEBUG_INTERRUPT = bool(os.getenv("HERMES_DEBUG_INTERRUPT"))
15
+ if _DEBUG_INTERRUPT:
16
+ # AIAgent's quiet_mode forces the `tools` logger to ERROR on CLI startup;
17
+ # force ours back to INFO so the trace is visible in agent.log.
18
+ logger.setLevel(logging.INFO)
19
+
20
+ # Interrupted thread idents + optional user-safe cause (never the user's message text).
21
+ _interrupted_threads: set[int] = set()
22
+ _interrupt_reasons: dict[int, str] = {}
23
+ # Threads asked to YIELD: hand a long-running foreground command to the background
24
+ # instead of killing it, so a mid-turn user message is not parked behind it.
25
+ _yield_threads: set[int] = set()
26
+ _lock = threading.Lock()
27
+
28
+
29
+ def set_interrupt(active: bool, thread_id: int | None = None, *, reason: str | None = None) -> None:
30
+ """Set or clear the interrupt for *thread_id* (default: current thread); ``reason`` is
31
+ an optional user-safe cause. Clearing also drops a pending yield request."""
32
+ tid = thread_id if thread_id is not None else threading.current_thread().ident
33
+ with _lock:
34
+ (_interrupted_threads.add if active else _interrupted_threads.discard)(tid)
35
+ if active and reason:
36
+ _interrupt_reasons[tid] = reason
37
+ else:
38
+ _interrupt_reasons.pop(tid, None)
39
+ if not active:
40
+ _yield_threads.discard(tid)
41
+ _snapshot = set(_interrupted_threads) if _DEBUG_INTERRUPT else None
42
+ if _DEBUG_INTERRUPT:
43
+ logger.info(
44
+ "[interrupt-debug] set_interrupt(active=%s, target_tid=%s) "
45
+ "called_from_tid=%s current_set=%s",
46
+ active, tid, threading.current_thread().ident, _snapshot)
47
+
48
+
49
+ def is_interrupted() -> bool:
50
+ return is_thread_interrupted(threading.current_thread().ident)
51
+
52
+
53
+ def is_thread_interrupted(thread_id: int | None) -> bool:
54
+ """Whether *thread_id* has an interrupt bit set (``None`` never is). Used when
55
+ a wait moves onto a deadline worker (``run_bounded_sync``) so ``/stop``
56
+ targeting the original tool-worker tid still kills the subprocess.
57
+
58
+ See #94285.
59
+ """
60
+ if thread_id is None:
61
+ return False
62
+ with _lock:
63
+ return thread_id in _interrupted_threads
64
+
65
+
66
+ def request_yield(thread_id: int) -> None:
67
+ """Ask the tool running on *thread_id* to yield: a foreground terminal command hands
68
+ its live process to the background registry and returns at once, so a user's mid-turn
69
+ message (``redirect()`` during tool execution) is delivered instead of parked behind it.
70
+ The command itself is never killed; that is what ``set_interrupt`` is for."""
71
+ with _lock:
72
+ _yield_threads.add(thread_id)
73
+
74
+
75
+ def is_thread_yield_requested(thread_id: int | None) -> bool:
76
+ """Whether a yield is pending for *thread_id* (``None`` never is)."""
77
+ if thread_id is None:
78
+ return False
79
+ with _lock:
80
+ return thread_id in _yield_threads
81
+
82
+
83
+ def consume_yield(thread_id: int | None) -> bool:
84
+ """Atomically take the pending yield for *thread_id*; True if one was pending."""
85
+ if thread_id is None:
86
+ return False
87
+ with _lock:
88
+ if thread_id in _yield_threads:
89
+ _yield_threads.discard(thread_id)
90
+ return True
91
+ return False
92
+
93
+
94
+ def run_if_not_interrupted(callback: Callable[[], None]) -> bool:
95
+ """Run a state transition atomically with current-thread interruption.
96
+
97
+ Returns ``False`` without calling ``callback`` when the current thread is
98
+ already interrupted. The callback runs under the interrupt lock and must
99
+ not block or re-enter any interrupt API.
100
+ """
101
+ tid = threading.current_thread().ident
102
+ with _lock:
103
+ if tid in _interrupted_threads:
104
+ return False
105
+ callback()
106
+ return True
107
+
108
+
109
+ def get_interrupt_reason() -> str | None:
110
+ """User-safe interrupt cause for the current thread, if known."""
111
+ with _lock:
112
+ return _interrupt_reasons.get(threading.current_thread().ident)
113
+
114
+
115
+ def clear_current_thread_interrupt() -> None:
116
+ """Clear any interrupt bit on the CURRENT thread: gives a user-approved command a clean
117
+ slate right before it spawns its child, so a stale bit that landed during the blocking
118
+ approval-wait cannot SIGINT the just-approved run. A *genuine* interrupt arriving after
119
+ this call re-sets the bit and is still observed by the executor's poll loop. Call
120
+ directly on the executing thread."""
121
+ set_interrupt(False)
tools/kanban_tools_schemas.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tool schemas for tools.kanban_tools (model-facing; strings are byte-frozen)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+ _DESC_TASK_ID_DEFAULT = (
7
+ "Task id. If omitted, defaults to HERMES_KANBAN_TASK from the env "
8
+ "(the task the dispatcher spawned you to work on)."
9
+ )
10
+
11
+ _DESC_BOARD = (
12
+ "Kanban board slug to target. When omitted, the call resolves the "
13
+ "active board the usual way: HERMES_KANBAN_DB env → "
14
+ "HERMES_KANBAN_BOARD env → the 'current' symlink under the kanban "
15
+ "home → 'default'. Pass an explicit slug only when the caller (e.g. "
16
+ "a Telegram routing layer) needs to override the env-pinned active "
17
+ "board for this one call."
18
+ )
19
+
20
+
21
+ def _prop(type_: str, description: str) -> dict[str, str]:
22
+ return {"type": type_, "description": description}
23
+
24
+
25
+ def _board_schema_prop() -> dict[str, str]:
26
+ """Schema fragment for the optional ``board`` parameter (one place to tweak)."""
27
+ return _prop("string", _DESC_BOARD)
28
+
29
+
30
+ def _schema(name: str, description: str, properties: dict[str, Any], required: list[str]) -> dict[str, Any]:
31
+ """Build a tool schema; every kanban tool takes an optional trailing ``board``."""
32
+ return {
33
+ "name": name,
34
+ "description": description,
35
+ "parameters": {
36
+ "type": "object",
37
+ "properties": {**properties, "board": _board_schema_prop()},
38
+ "required": required,
39
+ },
40
+ }
41
+
42
+
43
+ KANBAN_SHOW_SCHEMA = _schema(
44
+ "kanban_show",
45
+ (
46
+ "Read a task's full state — title, body, assignee, parent task "
47
+ "handoffs, your prior attempts on this task if any, comments, "
48
+ "and recent events. Use this to (re)orient yourself before "
49
+ "starting work, especially on retries. The response includes a "
50
+ "pre-formatted ``worker_context`` string suitable for inclusion "
51
+ "verbatim in your reasoning."
52
+ ),
53
+ {
54
+ "task_id": _prop("string", _DESC_TASK_ID_DEFAULT),
55
+ },
56
+ [],
57
+ )
58
+
59
+ KANBAN_LIST_SCHEMA = _schema(
60
+ "kanban_list",
61
+ (
62
+ "List Kanban task summaries so an orchestrator profile can discover "
63
+ "work to route. Supports the same core filters as the CLI: assignee, "
64
+ "status, tenant, include_archived, and limit. Returns compact rows "
65
+ "with ids, title, status, assignee, priority, parent/child ids, and "
66
+ "counts. Bounded to 50 rows by default, 200 max, with truncation "
67
+ "metadata. Also recomputes ready tasks before listing, matching the "
68
+ "CLI. Orchestrator-only — dispatcher-spawned task workers never see "
69
+ "this tool."
70
+ ),
71
+ {
72
+ "assignee": _prop("string", "Optional assignee/profile filter."),
73
+ "status": {
74
+ "type": "string",
75
+ "enum": [
76
+ "triage", "todo", "ready", "running",
77
+ "blocked", "done", "archived",
78
+ ],
79
+ "description": "Optional task status filter.",
80
+ },
81
+ "tenant": _prop("string", "Optional tenant/project namespace filter."),
82
+ "include_archived": _prop("boolean", "Include archived tasks. Defaults to false."),
83
+ "limit": _prop("integer", "Optional maximum rows to return (default 50, max 200)."),
84
+ },
85
+ [],
86
+ )
87
+
88
+ KANBAN_COMPLETE_SCHEMA = _schema(
89
+ "kanban_complete",
90
+ (
91
+ "Mark your current task done with a structured handoff for "
92
+ "downstream workers and humans. Prefer ``summary`` for a "
93
+ "human-readable 1-3 sentence description of what you did; put "
94
+ "machine-readable facts in ``metadata`` (changed_files, "
95
+ "tests_run, decisions, findings, etc). At least one of "
96
+ "``summary`` or ``result`` is required. If you created new "
97
+ "tasks via ``kanban_create`` during this run, list their ids "
98
+ "in ``created_cards`` — the kernel verifies them so phantom "
99
+ "references are caught before they leak into downstream "
100
+ "automation. If you produced deliverable files (charts, PDFs, "
101
+ "spreadsheets, generated images), list their absolute paths "
102
+ "in ``artifacts`` — the gateway notifier will upload them as "
103
+ "native attachments to the human who subscribed to the task, "
104
+ "so the deliverable lands in their chat alongside the summary "
105
+ "instead of being a path they have to fetch by hand."
106
+ ),
107
+ {
108
+ "task_id": _prop("string", _DESC_TASK_ID_DEFAULT),
109
+ "summary": _prop("string", (
110
+ "Human-readable handoff, 1-3 sentences. Appears in "
111
+ "Run History on the dashboard and in downstream "
112
+ "workers' context."
113
+ )),
114
+ "metadata": _prop("object", (
115
+ "Free-form dict of structured facts about this "
116
+ "attempt — {\"changed_files\": [...], \"tests_run\": 12, "
117
+ "\"findings\": [...]}. Surfaced to downstream "
118
+ "workers alongside ``summary``."
119
+ )),
120
+ "result": _prop("string", (
121
+ "Short result log line (legacy field, maps to "
122
+ "task.result). Use ``summary`` instead when "
123
+ "possible; this exists for compatibility with "
124
+ "callers that still set --result on the CLI."
125
+ )),
126
+ "created_cards": {
127
+ "type": "array",
128
+ "items": {"type": "string"},
129
+ "description": (
130
+ "Optional structured manifest of task ids you "
131
+ "created via ``kanban_create`` during this run. "
132
+ "The kernel verifies each id exists and was "
133
+ "created by this worker's profile; any phantom "
134
+ "id blocks the completion with an error listing "
135
+ "what went wrong (auditable in the task's events). "
136
+ "Only list ids you got back from a successful "
137
+ "``kanban_create`` call — do not invent or "
138
+ "remember ids from prose. Omit the field if you "
139
+ "did not create any cards."
140
+ ),
141
+ },
142
+ "artifacts": {
143
+ "type": "array",
144
+ "items": {"type": "string"},
145
+ "description": (
146
+ "Optional list of absolute paths to deliverable "
147
+ "files you produced during this run — generated "
148
+ "charts, PDFs, spreadsheets, images, archives. "
149
+ "Examples: [\"/tmp/q3-revenue.png\", "
150
+ "\"/tmp/report.pdf\"]. The gateway notifier "
151
+ "uploads each path as a native attachment to the "
152
+ "subscribed chat (images embed inline, everything "
153
+ "else uploads as a file) so the deliverable "
154
+ "lands with the completion notification. Skip "
155
+ "intermediate scratch files and references that "
156
+ "are not the deliverable. The path must exist "
157
+ "on disk at completion. Files inside a managed scratch "
158
+ "workspace are copied to durable task attachments before "
159
+ "cleanup; a missing declared scratch artifact keeps the "
160
+ "task in-flight so you can fix the path and retry."
161
+ ),
162
+ },
163
+ },
164
+ [],
165
+ )
166
+
167
+ KANBAN_BLOCK_SCHEMA = _schema(
168
+ "kanban_block",
169
+ (
170
+ "Stop work on this task and route it according to WHY you're stuck. "
171
+ "Set ``kind`` to say which: 'dependency' (waiting on another task — "
172
+ "goes to todo and auto-resumes when that task finishes, no human "
173
+ "needed), 'needs_input' (you need a human decision/answer), "
174
+ "'capability' (a hard wall: no access, missing credentials, an action "
175
+ "no agent can do), or 'transient' (a flaky failure that may clear). "
176
+ "``reason`` is shown to the human on the board. If a task keeps "
177
+ "getting unblocked and re-blocked for the same reason, it is "
178
+ "auto-escalated to triage. Use for genuine blockers only — don't "
179
+ "block on things you can resolve yourself."
180
+ ),
181
+ {
182
+ "task_id": _prop("string", _DESC_TASK_ID_DEFAULT),
183
+ "reason": _prop("string", (
184
+ "What you need answered or what stopped you, in one or "
185
+ "two sentences. Don't paste the whole conversation; the "
186
+ "human has the board and can ask follow-ups via comments."
187
+ )),
188
+ "kind": {
189
+ "type": "string",
190
+ "enum": ["dependency", "needs_input", "capability", "transient"],
191
+ "description": (
192
+ "Why you're blocked. 'dependency' waits in todo and "
193
+ "resumes automatically; the others surface to a human. "
194
+ "Omit only if none apply."
195
+ ),
196
+ },
197
+ },
198
+ ["reason"],
199
+ )
200
+
201
+ KANBAN_REQUEST_REVIEW_SCHEMA = _schema(
202
+ "kanban_request_review",
203
+ (
204
+ "Hand the task off for review: implementation, self-review, and "
205
+ "verification are complete and you want a human (or reviewer) to "
206
+ "look before it is marked done. Moves the task to the 'review' "
207
+ "column and notifies the subscriber. Unlike ``kanban_block`` this is "
208
+ "NOT a blocker — it never counts toward unblock-loop detection, so a "
209
+ "task can cycle through review across follow-ups without ever being "
210
+ "falsely escalated to triage. Use this instead of blocking with a "
211
+ "free-form 'review-required:' reason."
212
+ ),
213
+ {
214
+ "task_id": _prop("string", _DESC_TASK_ID_DEFAULT),
215
+ "summary": _prop("string", (
216
+ "What was implemented and how it was verified, in one or "
217
+ "two sentences — shown to the reviewer. Don't paste "
218
+ "the whole diff; the reviewer has the board and the PR."
219
+ )),
220
+ "reviewer": _prop("string", (
221
+ "Optional reviewer profile. When provided, the task is "
222
+ "reassigned to that profile before review dispatch."
223
+ )),
224
+ "metadata": {
225
+ "type": "object",
226
+ "description": (
227
+ "Optional structured handoff facts for the reviewer, such "
228
+ "as changed_files, tests_run, commit, or decisions."
229
+ ),
230
+ "additionalProperties": True,
231
+ },
232
+ "artifacts": {
233
+ "type": "array",
234
+ "items": {"type": "string"},
235
+ "description": (
236
+ "Optional list of absolute paths to deliverable "
237
+ "files this handoff names — generated charts, "
238
+ "PDFs, spreadsheets, images, archives. Examples: "
239
+ "['/tmp/q3-revenue.png', '/tmp/report.pdf']. "
240
+ "A review handoff is the last implementer "
241
+ "transition, so the kernel copies these into the "
242
+ "task's durable attachments before the reviewer's "
243
+ "completion cleans the scratch workspace up, and "
244
+ "the gateway notifier uploads them as native "
245
+ "attachments to the subscribed chat. A missing "
246
+ "declared scratch artifact keeps the task in place "
247
+ "so you can fix the path and retry."
248
+ ),
249
+ },
250
+ },
251
+ ["summary"],
252
+ )
253
+
254
+ KANBAN_REQUEST_CHANGES_SCHEMA = _schema(
255
+ "kanban_request_changes",
256
+ (
257
+ "Reviewer verdict: return the current review run to the original "
258
+ "implementer with concrete required changes. This closes the review "
259
+ "run, reapplies parent dependency gating, and requeues the task without "
260
+ "using block-loop accounting. Only use from a task claimed from the "
261
+ "review column; use kanban_block only for a genuine external blocker."
262
+ ),
263
+ {
264
+ "task_id": _prop("string", _DESC_TASK_ID_DEFAULT),
265
+ "reason": _prop("string", (
266
+ "Specific, actionable changes the implementer must make "
267
+ "before requesting another review."
268
+ )),
269
+ },
270
+ ["reason"],
271
+ )
272
+
273
+ KANBAN_HEARTBEAT_SCHEMA = _schema(
274
+ "kanban_heartbeat",
275
+ (
276
+ "Signal that you're still alive during a long operation "
277
+ "(training, encoding, large crawls). Call every few minutes so "
278
+ "humans see liveness separately from PID checks. Pure side "
279
+ "effect — no work changes."
280
+ ),
281
+ {
282
+ "task_id": _prop("string", _DESC_TASK_ID_DEFAULT),
283
+ "note": _prop("string", (
284
+ "Optional short note describing current progress. "
285
+ "Shown in the event log."
286
+ )),
287
+ },
288
+ [],
289
+ )
290
+
291
+ KANBAN_COMMENT_SCHEMA = _schema(
292
+ "kanban_comment",
293
+ (
294
+ "Append a comment to a task's thread. Use for durable notes "
295
+ "that should outlive this run (questions for the next worker, "
296
+ "partial findings, rationale). Ephemeral reasoning doesn't "
297
+ "belong here — use your normal response instead."
298
+ ),
299
+ {
300
+ "task_id": _prop("string", (
301
+ "Task id. Required (may be your own task or "
302
+ "another's — comment threads are per-task)."
303
+ )),
304
+ "body": _prop("string", "Markdown-supported comment body."),
305
+ },
306
+ ["task_id", "body"],
307
+ )
308
+
309
+ KANBAN_ATTACH_SCHEMA = _schema(
310
+ "kanban_attach",
311
+ (
312
+ "Attach a file to a task by passing its bytes inline (base64). "
313
+ "Use for genuine file artifacts the next worker or a human should "
314
+ "be able to download — generated reports, images, exports. The "
315
+ "file is stored as a real attachment (not a comment link) under "
316
+ "the task's attachments dir, capped at 25 MB. Prefer "
317
+ "kanban_attach_url when you only have a URL."
318
+ ),
319
+ {
320
+ "task_id": _prop("string", _DESC_TASK_ID_DEFAULT),
321
+ "filename": _prop("string", (
322
+ "File name to store it under (e.g. 'report.pdf'). "
323
+ "Directory components are stripped; only the leaf is kept."
324
+ )),
325
+ "content_base64": {
326
+ "type": "string",
327
+ "description": "The file contents, base64-encoded. Max 25 MB decoded.",
328
+ },
329
+ "content_type": _prop("string", "Optional MIME type (e.g. 'application/pdf')."),
330
+ },
331
+ ["filename", "content_base64"],
332
+ )
333
+
334
+ KANBAN_ATTACH_URL_SCHEMA = _schema(
335
+ "kanban_attach_url",
336
+ (
337
+ "Attach a file to a task by URL — Hermes downloads it server-side "
338
+ "and stores it as a real attachment (capped at 25 MB). Use when "
339
+ "you have a link rather than the bytes. Only http/https URLs are "
340
+ "accepted."
341
+ ),
342
+ {
343
+ "task_id": _prop("string", _DESC_TASK_ID_DEFAULT),
344
+ "url": _prop("string", "http(s) URL to fetch and store."),
345
+ "filename": _prop("string", (
346
+ "Optional name to store it under. Defaults to the URL "
347
+ "path's leaf component."
348
+ )),
349
+ "content_type": _prop("string", (
350
+ "Optional MIME type override. Defaults to the "
351
+ "Content-Type the server returns."
352
+ )),
353
+ },
354
+ ["url"],
355
+ )
356
+
357
+ KANBAN_ATTACHMENTS_SCHEMA = _schema(
358
+ "kanban_attachments",
359
+ (
360
+ "List the files attached to a task: id, filename, content_type, "
361
+ "size, who uploaded it, and the absolute on-disk path you can read."
362
+ ),
363
+ {
364
+ "task_id": _prop("string", _DESC_TASK_ID_DEFAULT),
365
+ },
366
+ [],
367
+ )
368
+
369
+ KANBAN_CREATE_SCHEMA = _schema(
370
+ "kanban_create",
371
+ (
372
+ "Create a new kanban task, optionally as a child of the current "
373
+ "one (pass the current task id in ``parents``). Used by "
374
+ "orchestrator workers to fan out — decompose work into child "
375
+ "tasks with specific assignees, link them into a pipeline, "
376
+ "then complete your own task. The dispatcher picks up the new "
377
+ "tasks on its next tick and spawns the assigned profiles."
378
+ ),
379
+ {
380
+ "title": _prop("string", "Short task title (required)."),
381
+ "assignee": _prop("string", (
382
+ "Profile name that should execute this task "
383
+ "(e.g. 'researcher-a', 'reviewer', 'writer'). "
384
+ "Required — tasks without an assignee are never "
385
+ "dispatched."
386
+ )),
387
+ "body": _prop("string", (
388
+ "Opening post: full spec, acceptance criteria, "
389
+ "links. The assigned worker reads this as part of "
390
+ "its context."
391
+ )),
392
+ "parents": {
393
+ "type": "array",
394
+ "items": {"type": "string"},
395
+ "description": (
396
+ "Parent task ids. The new task stays in 'todo' "
397
+ "until every parent reaches 'done'; then it "
398
+ "auto-promotes to 'ready'. Typical fan-in: list "
399
+ "all the researcher task ids when creating a "
400
+ "synthesizer task."
401
+ ),
402
+ },
403
+ "tenant": _prop("string", (
404
+ "Optional namespace for multi-project isolation. "
405
+ "Defaults to HERMES_TENANT env if set."
406
+ )),
407
+ "priority": _prop("integer", (
408
+ "Dispatcher tiebreaker. Higher = picked sooner "
409
+ "when multiple ready tasks share an assignee."
410
+ )),
411
+ "workspace_kind": {
412
+ "type": "string",
413
+ "enum": ["scratch", "dir", "worktree"],
414
+ "description": (
415
+ "Workspace flavor: 'scratch' (fresh tmp dir, "
416
+ "default), 'dir' (shared directory, requires "
417
+ "absolute workspace_path), 'worktree' (git worktree)."
418
+ ),
419
+ },
420
+ "workspace_path": _prop("string", (
421
+ "Absolute path for 'dir' or 'worktree' workspace. "
422
+ "Relative paths are rejected at dispatch."
423
+ )),
424
+ "project": _prop("string", (
425
+ "Optional project id or slug to link the task to. When "
426
+ "set, the task becomes a git worktree under the project's "
427
+ "primary repo with a deterministic branch (project slug + "
428
+ "task id), instead of a random branch."
429
+ )),
430
+ "triage": _prop("boolean", (
431
+ "If true, task lands in 'triage' instead of 'todo' "
432
+ "— a specifier profile is expected to flesh out "
433
+ "the body before work starts."
434
+ )),
435
+ "idempotency_key": _prop("string", (
436
+ "If a non-archived task with this key already "
437
+ "exists, return that task's id instead of creating "
438
+ "a duplicate. Useful for retry-safe automation."
439
+ )),
440
+ "max_runtime_seconds": _prop("integer", (
441
+ "Per-task runtime cap. When exceeded, the "
442
+ "dispatcher SIGTERMs the worker and re-queues the "
443
+ "task with outcome='timed_out'."
444
+ )),
445
+ "initial_status": {
446
+ "type": "string",
447
+ "enum": ["running", "blocked"],
448
+ "description": (
449
+ "Initial card status. Use 'blocked' for tasks that "
450
+ "require immediate human ops (R3 gate) to skip the "
451
+ "brief running-to-blocked transition. Defaults to "
452
+ "'running', which preserves the usual dispatch path."
453
+ ),
454
+ },
455
+ "skills": {
456
+ "type": "array",
457
+ "items": {"type": "string"},
458
+ "description": (
459
+ "Skill names to force-load into the dispatched "
460
+ "worker. The kanban lifecycle is already injected "
461
+ "automatically; use this to pin a task to a specialist "
462
+ "context — e.g. ['translation'] for a translation "
463
+ "task, ['github-code-review'] for a reviewer task. "
464
+ "The names must match skills installed on the "
465
+ "assignee's profile."
466
+ ),
467
+ },
468
+ "goal_mode": _prop("boolean", (
469
+ "Run the dispatched worker in a goal loop. When true, "
470
+ "after each turn an auxiliary judge checks the worker's "
471
+ "response against this card's title/body; if the work "
472
+ "isn't done and budget remains, the worker keeps going "
473
+ "in the same session until the judge agrees it's "
474
+ "complete (or the goal-turn budget is exhausted, which "
475
+ "blocks the task for human review). Use this for "
476
+ "open-ended cards where one shot rarely finishes the "
477
+ "work. Defaults to false (classic single-shot worker)."
478
+ )),
479
+ "completion_contract": _prop("string", (
480
+ "Declare at creation: local-only (default), OWNER/REPO for PR publication, or an exact GitHub PR URL. "
481
+ "PR tasks cannot complete until repository-required exact-head CI passes. On publication pass metadata.published_pr."
482
+ )),
483
+ "goal_max_turns": _prop("integer", (
484
+ "Turn budget for goal_mode workers. Caps how many "
485
+ "continuation turns the worker may take before the task "
486
+ "is blocked for review. Ignored unless goal_mode is "
487
+ "true. Defaults to the goal-engine default (20)."
488
+ )),
489
+ "model": _prop("string", (
490
+ "Pin the dispatched worker to this model instead of "
491
+ "the assignee profile's configured model. Use the "
492
+ "exact model name the target provider expects. Omit "
493
+ "to use the profile default."
494
+ )),
495
+ "provider": _prop("string", (
496
+ "Provider the 'model' belongs to (e.g. 'openrouter', "
497
+ "'anthropic', 'nous'). Set this whenever the model "
498
+ "is not from the assignee profile's configured "
499
+ "provider — a model name alone is resolved against "
500
+ "the profile's provider and will fail if it belongs "
501
+ "to a different one. Requires 'model'."
502
+ )),
503
+ },
504
+ ["title", "assignee"],
505
+ )
506
+
507
+ KANBAN_UNBLOCK_SCHEMA = _schema(
508
+ "kanban_unblock",
509
+ (
510
+ "Unblock a Kanban task. It moves to ready when all parents are done, "
511
+ "or todo while any parent remains open. Orchestrator-only — only "
512
+ "profiles with the kanban toolset can unblock routed work; "
513
+ "dispatcher-spawned task workers never see this tool."
514
+ ),
515
+ {
516
+ "task_id": _prop("string", "Blocked task id to move to ready or parent-gated todo."),
517
+ },
518
+ ["task_id"],
519
+ )
520
+
521
+ KANBAN_LINK_SCHEMA = _schema(
522
+ "kanban_link",
523
+ (
524
+ "Add a parent→child dependency edge after both tasks already "
525
+ "exist. The child won't promote to 'ready' until all parents "
526
+ "are 'done'. Cycles and self-links are rejected."
527
+ ),
528
+ {
529
+ "parent_id": {"type": "string", "description": "Parent task id."},
530
+ "child_id": {"type": "string", "description": "Child task id."},
531
+ },
532
+ ["parent_id", "child_id"],
533
+ )
tools/kanban_toolset_context.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit Kanban selection during one model-schema build.
2
+
3
+ The registry's ordinary availability cache is profile-wide, while a gateway
4
+ can build schemas for several platforms in the same profile concurrently.
5
+ Carry only the explicit selection through a ContextVar, never process env.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from contextlib import contextmanager
10
+ from contextvars import ContextVar
11
+ from typing import Iterable, Iterator, Optional
12
+
13
+ _requested: ContextVar[Optional[bool]] = ContextVar("kanban_toolset_requested", default=None)
14
+
15
+
16
+ def kanban_toolset_requested() -> Optional[bool]:
17
+ """None outside schema assembly; otherwise whether Kanban was named explicitly."""
18
+ return _requested.get()
19
+
20
+
21
+ @contextmanager
22
+ def scoped_kanban_toolset_selection(toolsets: Optional[Iterable[str]]) -> Iterator[None]:
23
+ """An all/default selection is not an explicit workflow opt-in."""
24
+ token = _requested.set("kanban" in (toolsets or ()))
25
+ try:
26
+ yield
27
+ finally:
28
+ _requested.reset(token)
tools/lazy_deps.py ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lazy dependency installer for opt-in Hermes backends.
2
+
3
+ Backends call :func:`ensure(feature)` on first import; missing packages are installed into the
4
+ active venv (or the durable target) unless ``security.allow_lazy_installs: false``, in which
5
+ case :class:`FeatureUnavailable` carries a remediation hint. Security model: venv-scoped
6
+ (never system Python); durable-target mode (``HERMES_LAZY_INSTALL_TARGET``, sealed images)
7
+ APPENDS the target to ``sys.path`` so core site-packages wins every collision and a lazy
8
+ package can only add modules, never shadow core; PyPI-by-name specs only (``_spec_is_safe``);
9
+ ``ensure`` accepts only the :data:`LAZY_DEPS` allowlist; failures surface pip's stderr, no retry.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import logging
16
+ import os
17
+ import re
18
+ import shutil
19
+ import site
20
+ import subprocess
21
+ import sys
22
+ import sysconfig
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Any, Callable, Optional
26
+
27
+ from hermes_cli._subprocess_compat import windows_hide_flags
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ # Allowlist: "namespace.backend" -> pip specs matching the pyproject extra. Pins are exact
33
+ # (security posture); bump here AND in pyproject. Shared patched floors (aiohttp==3.14.3,
34
+ # starlette==1.3.1) are literals in every feature: tests/test_packaging_metadata.py checks by AST.
35
+ LAZY_DEPS: dict[str, tuple[str, ...]] = {
36
+ # ─── Inference providers ───────────────────────────────────────────────
37
+ # Native Anthropic SDK (provider=anthropic; aggregators use the openai SDK).
38
+ "provider.anthropic": ("anthropic==0.87.0",), # CVE-2026-34450, CVE-2026-34452
39
+ "provider.bedrock": ("boto3==1.42.89",),
40
+ # Vertex OAuth2 token minting; google-auth is NOT in [all] on purpose.
41
+ "provider.vertex": (
42
+ "google-auth==2.55.1",
43
+ "pyasn1==0.6.4",
44
+ ),
45
+ # Foundry Entra ID auth; only when model.auth_mode=entra_id.
46
+ "provider.azure_identity": ("azure-identity==1.25.3",),
47
+
48
+ # ─── Web search backends ───────────────────────────────────────────────
49
+ "search.exa": ("exa-py==2.10.2",),
50
+ "search.firecrawl": ("firecrawl-py==4.17.0",),
51
+ "search.parallel": ("parallel-web==0.4.2",),
52
+
53
+ # ─── Monitoring ─────────────────────────────────────────────────────────
54
+ # OTLP export; tracks the `otlp` extra.
55
+ "export.otlp": (
56
+ "opentelemetry-sdk==1.39.1",
57
+ "opentelemetry-exporter-otlp-proto-http==1.39.1",
58
+ ),
59
+
60
+ # ─── TTS providers ─────────────────────────────────────────────────────
61
+ # mistralai: 2.4.6 was a malicious quarantined release — never pin below 2.4.7.
62
+ # Voxtral STT + TTS share the SDK.
63
+ "tts.mistral": ("mistralai==2.4.8",),
64
+ "tts.edge": ("edge-tts==7.2.7",),
65
+ "tts.elevenlabs": ("elevenlabs==1.59.0",),
66
+
67
+ # ─── Speech-to-text providers ──────────────────────────────────────────
68
+ "stt.mistral": ("mistralai==2.4.8",),
69
+ "stt.faster_whisper": (
70
+ "faster-whisper==1.2.1",
71
+ "sounddevice==0.5.5",
72
+ "numpy==2.4.3",
73
+ ),
74
+ # SILK voice-note decoding (WeChat/QQ); silk-v3 codec binding.
75
+ "stt.silk": ("pilk==0.2.4",),
76
+
77
+ # ─── Wake word ("Hey Hermes") engines (sync with the `wake` extra) ──────
78
+ # openWakeWord's ONNX model scores ~0 on macOS ARM64, so macOS uses the tflite backend
79
+ # (ai-edge-litert, bridged in tools/wake_word.py). Separate feature because specs cannot
80
+ # carry PEP 508 markers (";" is rejected) — the caller applies the platform gate.
81
+ "wake.openwakeword.tflite": (
82
+ "ai-edge-litert==2.1.6",
83
+ ),
84
+ "wake.openwakeword": (
85
+ "openwakeword==0.6.0",
86
+ "onnxruntime==1.27.0",
87
+ "sounddevice==0.5.5",
88
+ "numpy==2.4.3",
89
+ ),
90
+ # Open-vocabulary keyword spotting. sentencepiece is needed by
91
+ # sherpa_onnx.text2token but undeclared by sherpa-onnx.
92
+ "wake.sherpa": (
93
+ "sherpa-onnx==1.13.4",
94
+ "sentencepiece==0.2.2",
95
+ "sounddevice==0.5.5",
96
+ "numpy==2.4.3",
97
+ ),
98
+ "wake.porcupine": (
99
+ "pvporcupine==4.0.3",
100
+ "sounddevice==0.5.5",
101
+ "numpy==2.4.3",
102
+ ),
103
+
104
+ # ─── Image generation backends ─────────────────────────────────────────
105
+ "image.fal": ("fal-client==0.13.1",),
106
+
107
+ # ─── Memory providers ────────────────────────────────────────────��─────
108
+ "memory.honcho": ("honcho-ai==2.2.0",),
109
+ "memory.hindsight": ("hindsight-client==0.6.1",),
110
+ # Cloud memory SDKs MUST be allowlisted + ensure()'d at the import site, or they never
111
+ # install on the sealed Docker image (durable-target only).
112
+ "memory.supermemory": ("supermemory==3.50.0",),
113
+ "memory.mem0": ("mem0ai==2.0.10",),
114
+
115
+ # ─── Messaging platforms (lazy-installable on demand) ──────────────────
116
+ "platform.telegram": ("python-telegram-bot[webhooks]==22.8",),
117
+ # brotlicffi: aiohttp needs its 2-arg Decompressor for Discord CDN Brotli attachments
118
+ # (google's 1-arg `Brotli` fails "Can not decode br"). aiohttp is only capped transitively
119
+ # by these adapters, so pin the patched floor explicitly.
120
+ # Without it, aiohttp falls back to google's `Brotli` package (1-arg API), and any .txt/.md/.doc
121
+ # uploaded to the Discord gateway fails to decode at att.read() with "Can not decode content-encoding:
122
+ # br" — see #12511 / #15744.
123
+ "platform.discord": (
124
+ "discord.py[voice]==2.7.1",
125
+ "brotlicffi==1.2.0.2",
126
+ "aiohttp==3.14.3",
127
+ ),
128
+ "platform.slack": (
129
+ "slack-bolt==1.30.0",
130
+ "slack-sdk==3.44.1",
131
+ "aiohttp==3.14.3",
132
+ ),
133
+ "platform.matrix": (
134
+ "mautrix[encryption]==0.21.1",
135
+ "aiosqlite==0.22.1",
136
+ "asyncpg==0.31.0",
137
+ "aiohttp-socks==0.11.0",
138
+ "aiohttp==3.14.3",
139
+ ),
140
+ "platform.dingtalk": (
141
+ "dingtalk-stream==0.24.3",
142
+ "alibabacloud-dingtalk==2.2.42",
143
+ "qrcode==7.4.2",
144
+ ),
145
+ "platform.feishu": (
146
+ "lark-oapi==1.6.8",
147
+ "qrcode==7.4.2",
148
+ ),
149
+ # WeCom callback adapter parses untrusted XML POST bodies -> defusedxml.
150
+ "platform.wecom_callback": ("defusedxml==0.7.1",),
151
+ # Teams pulls a heavy tree (msal, dependency-injector); also the `teams` extra.
152
+ "platform.teams": ("microsoft-teams-apps==2.0.13.4", "aiohttp==3.14.3"),
153
+ # Google Chat — Pub/Sub + Chat API. Not in [all]; Docker bakes `--extra google-chat`
154
+ # so hosted/immutable images do not have to write the sealed venv.
155
+ "platform.google_chat": (
156
+ "google-cloud-pubsub==2.39.0",
157
+ "google-api-python-client==2.194.0",
158
+ "google-auth==2.55.1",
159
+ "google-auth-oauthlib==1.3.1",
160
+ "google-auth-httplib2==0.3.1",
161
+ "httplib2==0.32.0",
162
+ "pyasn1==0.6.4",
163
+ ),
164
+
165
+ # ─── Terminal backends ─────────────────────────────────────────────────
166
+ "terminal.modal": ("modal==1.3.4",),
167
+ "terminal.daytona": ("daytona==0.155.0",),
168
+ "terminal.vercel": ("vercel==0.7.2",),
169
+
170
+ # ─── Skills ────────────────────────────────────────────────────────────
171
+ "skill.google_workspace": (
172
+ "google-api-python-client==2.194.0",
173
+ "google-auth==2.55.1",
174
+ "google-auth-oauthlib==1.3.1",
175
+ "google-auth-httplib2==0.3.1",
176
+ # Explicit transitive pins: httplib2 <0.32 has a decompression-bomb DoS.
177
+ "httplib2==0.32.0",
178
+ "pyasn1==0.6.4",
179
+ ),
180
+ "skill.youtube": ("youtube-transcript-api==1.2.4",),
181
+
182
+ # ─── Tools ─────────────────────────────────────────────────────────────
183
+ # ACP adapter (VS Code / Zed / JetBrains)
184
+ "tool.acp": ("agent-client-protocol==0.9.0",),
185
+ "tool.dashboard": (
186
+ "fastapi==0.133.1",
187
+ "uvicorn[standard]==0.41.0",
188
+ "starlette==1.3.1",
189
+ "python-multipart==0.0.32", # FastAPI UploadFile/Form streaming uploads
190
+ ),
191
+ # Pillow and firecrawl-anydoc are CORE deps; these entries self-heal lean/partial installs.
192
+ # Call sites use prompt=False so read_file / vision never block on input() mid-session.
193
+ # Vision image-resize recovery (Pillow). Pillow is now a CORE dependency (pyproject `dependencies`), so
194
+ # this entry is a belt-and-suspenders fallback for stripped/source-build installs that somehow dropped
195
+ # it. See #40490.
196
+ "tool.vision": ("Pillow==12.3.0",),
197
+ "tool.doc_extract": ("firecrawl-anydoc==0.2.4",), # imports as `anydoc`; lockstep with pyproject
198
+ # MCP client SDK for the cua-driver, so computer_use never dead-ends on `No module named 'mcp'`.
199
+ "tool.computer_use": (
200
+ "mcp==2.0.0",
201
+ "httpx2==2.7.0", # mcp 2.x HTTP stack — sync with pyproject [computer-use]
202
+ "starlette==1.3.1",
203
+ ),
204
+ # huggingface-hub is SHARED with transformers (>=1.5.0,<2 via Hindsight) and marked active
205
+ # on mere presence, so `hermes update` re-asserts this pin everywhere hub exists. MUST stay
206
+ # inside transformers' window and match uv.lock (tests/test_project_metadata.py enforces).
207
+ # HF Agent Trace Viewer upload (hermes trace upload / /upload-trace). huggingface-hub is a SHARED
208
+ # dependency: transformers (pulled by sentence-transformers for local Hindsight embeddings) requires
209
+ # >=1.5.0,<2, and faster-whisper/tokenizers depend on it transitively. Because active_features() marks a
210
+ # feature active from mere package presence, the `hermes update` lazy-refresh pass re-asserts THIS pin
211
+ # on every install where hub is present — so an exact pin below 1.5.0 force-downgrades the shared
212
+ # package and breaks Hindsight startup (#60783). Policy: keep the exact pin (no ranges — security
213
+ # posture), but it MUST stay inside transformers' accepted window and MUST match uv.lock so the whole
214
+ # tree converges on ONE hub version (tests/test_project_metadata.py enforces both). When bumping: update
215
+ # here AND `uv lock --upgrade-package huggingface-hub` in lockstep.
216
+ "tool.trace_upload": ("huggingface-hub==1.24.0",),
217
+ }
218
+
219
+
220
+ # Spec validation: name[extras]specifier only — no URLs, paths, or shell metachars.
221
+ _NAME_RE = r"[A-Za-z0-9_][A-Za-z0-9_.\-]*"
222
+ _NAME_EXTRAS_RE = re.compile(rf"^{_NAME_RE}(?:\[[A-Za-z0-9_,\-]+\])?")
223
+ _SAFE_SPEC = re.compile(rf"^{_NAME_RE}(?:\[[A-Za-z0-9_,\-]+\])?(?:[<>=!~]=?[A-Za-z0-9_.\-+,*<>=!~]+)?$")
224
+
225
+
226
+ class FeatureUnavailable(RuntimeError):
227
+ """A lazily-installable feature is missing and cannot be made available (installs disabled or failed)."""
228
+
229
+ def __init__(self, feature: str, missing: tuple[str, ...], reason: str):
230
+ self.feature, self.missing, self.reason = feature, missing, reason
231
+ spec_list = " ".join(repr(s) for s in missing)
232
+ super().__init__(
233
+ f"Feature {feature!r} unavailable: {reason}. "
234
+ f"To enable manually: uv pip install {spec_list} (or: pip install {spec_list}).")
235
+
236
+
237
+ @dataclass(frozen=True)
238
+ class _InstallResult:
239
+ success: bool
240
+ stdout: str
241
+ stderr: str
242
+
243
+
244
+ # Internal bridge var (set by the Docker image, not user config) redirecting lazy installs from the
245
+ # sealed venv to a writable durable volume.
246
+ _LAZY_TARGET_ENV = "HERMES_LAZY_INSTALL_TARGET"
247
+ # Stamp of the Python X.Y + ABI the target was populated for; a mismatch after an image rebuild
248
+ # wipes the store so stale .so files are never imported.
249
+ _TARGET_STAMP_NAME = ".python-abi"
250
+
251
+ _SUBPROCESS_KW = dict(capture_output=True, text=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
252
+
253
+
254
+ def _python_abi_tag() -> str:
255
+ """X.Y + EXT_SUFFIX (ABI tag + platform); interpreters sharing compiled wheels match."""
256
+ return f"{sys.version_info.major}.{sys.version_info.minor}:{sysconfig.get_config_var('EXT_SUFFIX') or ''}"
257
+
258
+
259
+ def _lazy_install_target() -> Optional[Path]:
260
+ """Durable install-target dir (:data:`_LAZY_TARGET_ENV`), or None for venv-scoped mode."""
261
+ raw = os.environ.get(_LAZY_TARGET_ENV, "").strip()
262
+ return Path(raw) if raw else None
263
+
264
+
265
+ def _ensure_target_ready(target: Path) -> Optional[str]:
266
+ """Create the target dir and validate its ABI stamp; a different-ABI stamp wipes the contents
267
+ first (stale .so must never import). None on success, else an error string."""
268
+ want = _python_abi_tag()
269
+ stamp = target / _TARGET_STAMP_NAME
270
+ try:
271
+ if target.exists():
272
+ have = ""
273
+ with contextlib.suppress(OSError):
274
+ have = stamp.read_text(encoding="utf-8").strip()
275
+ if have and have != want:
276
+ logger.info("Lazy install target %s was built for ABI %r but running ABI is %r; wiping stale packages.", target, have, want)
277
+ for child in target.iterdir():
278
+ if child.is_dir() and not child.is_symlink():
279
+ shutil.rmtree(child, ignore_errors=True)
280
+ else:
281
+ with contextlib.suppress(OSError):
282
+ child.unlink()
283
+ target.mkdir(parents=True, exist_ok=True)
284
+ stamp.write_text(want, encoding="utf-8")
285
+ except OSError as e:
286
+ return f"lazy install target {target} is not writable: {e}"
287
+ return None
288
+
289
+
290
+ def _activate_target_on_syspath(target: Path) -> None:
291
+ """Append the durable target to ``sys.path`` (idempotent). ``site.addsitedir`` honours ``.pth``
292
+ files but inserts near the front, so new entries are moved to the END — core venv site-packages must win collisions."""
293
+ target_str = str(target)
294
+ before = list(sys.path)
295
+ if target_str not in before:
296
+ site.addsitedir(target_str)
297
+ new_entries = [p for p in sys.path if p not in before]
298
+ if new_entries:
299
+ sys.path[:] = [p for p in sys.path if p not in new_entries] + new_entries
300
+ _invalidate_import_caches()
301
+
302
+
303
+ def _invalidate_import_caches() -> None:
304
+ """Make just-installed dists visible to importers and importlib.metadata in this process."""
305
+ with contextlib.suppress(Exception):
306
+ import importlib
307
+ importlib.invalidate_caches()
308
+ import importlib.metadata as _md
309
+ if hasattr(_md, "_cache_clear"):
310
+ _md._cache_clear() # type: ignore[attr-defined]
311
+
312
+
313
+ def activate_durable_lazy_target() -> None:
314
+ """Wire the durable target onto ``sys.path`` at startup so packages installed on a previous run
315
+ import on this one. No-op when unset or absent. Never raises."""
316
+ target = _lazy_install_target()
317
+ try:
318
+ if target is not None and target.exists():
319
+ _activate_target_on_syspath(target)
320
+ except Exception as e: # pragma: no cover - defensive
321
+ logger.debug("Failed to activate durable lazy target %s: %s", target, e)
322
+
323
+
324
+ def _allow_lazy_installs() -> bool:
325
+ """Whether lazy installs are permitted: (1) ``security.allow_lazy_installs: false`` blocks in BOTH
326
+ modes; (2) the sealed venv (``HERMES_DISABLE_LAZY_INSTALLS=1``) blocks only without a durable
327
+ target to redirect into. Unreadable config fails OPEN — blocking is an explicit opt-in."""
328
+ cfg = None
329
+ with contextlib.suppress(Exception):
330
+ from hermes_cli.config import load_config
331
+ cfg = load_config()
332
+ if cfg is not None and not bool((cfg.get("security") or {}).get("allow_lazy_installs", True)):
333
+ return False
334
+ if os.environ.get("HERMES_DISABLE_LAZY_INSTALLS") == "1":
335
+ return _lazy_install_target() is not None
336
+ return True
337
+
338
+
339
+ def _unsupported_feature_reason(feature: str) -> Optional[str]:
340
+ """Platform capability gate (not policy): why a feature cannot work on this host, or None."""
341
+ if sys.platform == "win32" and feature == "platform.matrix":
342
+ return ("unsupported on Windows: Matrix E2EE depends on python-olm, which has no Windows wheel and "
343
+ "requires make + libolm to build from sdist. Run Hermes under WSL to use Matrix on Windows.")
344
+ return None
345
+
346
+
347
+ def _spec_is_safe(spec: str) -> bool:
348
+ """Reject pip specs that contain URLs, paths, or shell metacharacters."""
349
+ return bool(spec and len(spec) <= 200
350
+ and not any(ch in spec for ch in (";", "|", "&", "`", "$", "\n", "\r", "\t", "\\"))
351
+ and not spec.startswith(("-", "/", ".")) and "://" not in spec and "@" not in spec
352
+ and _SAFE_SPEC.match(spec))
353
+
354
+
355
+ def _pkg_name_from_spec(spec: str) -> str:
356
+ """``"mautrix[encryption]>=0.20"`` -> ``"mautrix"``."""
357
+ m = re.match(rf"^({_NAME_RE})", spec)
358
+ return m.group(1) if m else spec
359
+
360
+
361
+ def _specifier_from_spec(spec: str) -> str:
362
+ """``"mautrix[encryption]>=0.20,<1"`` -> ``">=0.20,<1"``; ``""`` if unconstrained."""
363
+ m = _NAME_EXTRAS_RE.match(spec)
364
+ return spec[m.end():] if m else ""
365
+
366
+
367
+ def _installed_version(spec: str) -> Optional[str]:
368
+ """Installed version of the spec's package, or None when absent."""
369
+ try:
370
+ from importlib.metadata import version
371
+
372
+ return version(_pkg_name_from_spec(spec))
373
+ except Exception:
374
+ return None
375
+
376
+
377
+ def _is_satisfied(spec: str) -> bool:
378
+ """Present AND inside the spec's version range, so ``hermes update`` propagates pin bumps to
379
+ installed backends. Unparseable specs/versions or a missing ``packaging`` count as satisfied — err
380
+ toward "don't churn"."""
381
+ installed = _installed_version(spec)
382
+ if installed is None:
383
+ return False
384
+ if not (spec_tail := _specifier_from_spec(spec)):
385
+ return True
386
+ try:
387
+ from packaging.specifiers import SpecifierSet
388
+ from packaging.version import Version
389
+
390
+ return Version(installed) in SpecifierSet(spec_tail)
391
+ except Exception:
392
+ return True
393
+
394
+
395
+ def _is_present(spec: str) -> bool:
396
+ """Presence-only check (any version) — how :func:`active_features` detects activated backends."""
397
+ return _installed_version(spec) is not None
398
+
399
+
400
+ def _core_constraints_file() -> Optional[Path]:
401
+ """Temp ``--constraint`` file pinning every core-venv package to its installed version for
402
+ durable-target installs: shared deps resolve as satisfied (store stays minimal) and a conflicting
403
+ backend fails loudly instead of installing a shadowed copy that can never win on sys.path. None if
404
+ enumeration failed (install unconstrained)."""
405
+ try:
406
+ import tempfile
407
+ from importlib.metadata import distributions
408
+
409
+ pins: dict[str, str] = {}
410
+ for dist in distributions():
411
+ name = dist.metadata["Name"] if dist.metadata else None
412
+ if name and dist.version and name.lower() not in pins:
413
+ pins[name.lower()] = f"{name}=={dist.version}"
414
+ if not pins:
415
+ return None
416
+ fd, path = tempfile.mkstemp(prefix="hermes-core-constraints-", suffix=".txt")
417
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
418
+ f.write("\n".join(sorted(pins.values())) + "\n")
419
+ return Path(path)
420
+ except Exception as e:
421
+ logger.debug("Could not build core constraints file: %s", e)
422
+ return None
423
+
424
+
425
+ def _installed_dist_roots(spec: str, target: Optional[Path]) -> set[Path]:
426
+ """Package dirs a freshly installed *spec* owns, from the dist's file list (``python-telegram-bot``
427
+ ships ``telegram``; some ship several)."""
428
+ name = _pkg_name_from_spec(spec)
429
+ roots: set[Path] = set()
430
+ try:
431
+ import importlib.metadata as _md
432
+
433
+ dist = next(iter(_md.distributions(name=name, path=[str(target)])), None) if target is not None else _md.distribution(name)
434
+ for entry in dist.files or () if dist is not None else ():
435
+ top = entry.parts[0] if entry.parts else ""
436
+ # Skip hidden entries, __pycache__ and metadata dirs (no importable code).
437
+ if not top or top.startswith(".") or top == "__pycache__" or top.endswith((".dist-info", ".egg-info")):
438
+ continue
439
+ root = Path(dist.locate_file(top))
440
+ if root.is_dir():
441
+ roots.add(root)
442
+ except Exception:
443
+ return set()
444
+ return roots
445
+
446
+
447
+ def _warm_installed_bytecode(specs: tuple[str, ...], target: Optional[Path]) -> None:
448
+ """Byte-compile what was just installed: a fresh install writes no ``__pycache__``, so the next
449
+ import (often a user request, ~2-10s for a big SDK, reading as a hang) would pay the compile. Pay
450
+ it here while the caller already waits. Best-effort; never fails the install.
451
+
452
+ A pip/uv install writes ``.py`` sources and no ``__pycache__`` — and an install of the *same* version
453
+ still deletes the cache the old copy had. Whoever imports the package next pays the whole compile: for
454
+ ``anthropic==0.87.0`` (541 modules) on cpython-3.12.13 that measured 2.2-2.7s cold against 0.7-1.0s
455
+ warm, and 10.5s cold under concurrent load. That bill lands wherever the first import happens, and for a
456
+ lazily-installed backend that is the foreground of a user request (#100461) — with nothing printed while
457
+ it runs, so it reads as a hang. Worse, N per-profile daemons cold-starting together each pay it in full
458
+ before any of them has written the cache.
459
+ """
460
+ if sys.dont_write_bytecode:
461
+ return
462
+ try:
463
+ import compileall
464
+ except Exception: # pragma: no cover — stdlib, but never break an install
465
+ return
466
+ for spec in specs:
467
+ try:
468
+ for root in _installed_dist_roots(spec, target):
469
+ try:
470
+ compileall.compile_dir(str(root), quiet=2, force=False, workers=1)
471
+ except Exception as exc:
472
+ logger.debug("Bytecode warm skipped for %s: %s", root, exc)
473
+ except Exception as exc:
474
+ logger.debug("Bytecode warm skipped for %s: %s", spec, exc)
475
+
476
+
477
+ def _run_installer(cmd: list[str], **kw) -> subprocess.CompletedProcess:
478
+ # _SUBPROCESS_KW carries stdin=DEVNULL # noqa: subprocess-stdin
479
+ return subprocess.run(cmd, **_SUBPROCESS_KW, creationflags=windows_hide_flags(), **kw)
480
+
481
+
482
+ def _uv_binary() -> Optional[str]:
483
+ """Managed uv first ($HERMES_HOME/bin is never on PATH), then PATH. A lookup, not ensure_uv():
484
+ downloading uv mid-turn is more than the caller asked for; pip covers no-uv."""
485
+ try:
486
+ from hermes_cli.managed_uv import resolve_uv
487
+
488
+ return resolve_uv() or shutil.which("uv")
489
+ except Exception:
490
+ return shutil.which("uv")
491
+
492
+
493
+ def _venv_pip_install(specs: tuple[str, ...], *, timeout: int = 300) -> _InstallResult:
494
+ """Install ``specs`` via the uv -> pip -> ensurepip ladder, venv-scoped or into the durable
495
+ ``--target`` (constrained to core versions) when :data:`_LAZY_TARGET_ENV` is set. Independent of
496
+ ``hermes_cli.tools_config._pip_install`` (no CLI dependency)."""
497
+ if not specs:
498
+ return _InstallResult(True, "", "")
499
+ target = _lazy_install_target()
500
+ constraints: Optional[Path] = None
501
+ extra_args: list[str] = []
502
+ if target is not None:
503
+ if err := _ensure_target_ready(target):
504
+ return _InstallResult(False, "", err)
505
+ constraints = _core_constraints_file()
506
+ extra_args += ["--target", str(target)]
507
+ if constraints is not None:
508
+ extra_args += ["--constraint", str(constraints)]
509
+
510
+ def _finish(r: subprocess.CompletedProcess) -> _InstallResult:
511
+ if r.returncode == 0:
512
+ if target is not None:
513
+ _activate_target_on_syspath(target)
514
+ _warm_installed_bytecode(specs, target)
515
+ return _InstallResult(r.returncode == 0, r.stdout or "", r.stderr or "")
516
+
517
+ try:
518
+ from tools.environments.local import hermes_subprocess_env
519
+ uv_env = hermes_subprocess_env(inherit_credentials=False)
520
+ uv_env["VIRTUAL_ENV"] = str(Path(sys.executable).parent.parent)
521
+ # Tier 1: uv. --compile-bytecode because uv writes no __pycache__ by default, so the first
522
+ # import would recompile the backend AND its transitives (_warm_installed_bytecode is the
523
+ # belt-and-braces pass for the spec's own roots on any tier).
524
+ if uv_bin := _uv_binary():
525
+ try:
526
+ r = _run_installer([uv_bin, "pip", "install", "--compile-bytecode", *extra_args, *specs], timeout=timeout, env=uv_env)
527
+ if r.returncode != 0:
528
+ logger.debug("uv pip install failed: %s", r.stderr)
529
+ # A uv resolver failure is authoritative: falling through to pip would discard uv
530
+ # policy (exclude-newer) and could install a quarantined release.
531
+ return _finish(r)
532
+ except subprocess.TimeoutExpired as e:
533
+ logger.debug("uv invocation failed: %s", e)
534
+ return _InstallResult(False, "", f"uv pip install timed out: {e}")
535
+ except FileNotFoundError as e: # uv vanished between lookup and spawn; it never evaluated the requirements
536
+ logger.debug("uv invocation failed: %s", e)
537
+ # Tier 2: python -m pip (ensurepip bootstrap if needed)
538
+ pip_cmd = [sys.executable, "-m", "pip"]
539
+ try:
540
+ if _run_installer(pip_cmd + ["--version"], timeout=15).returncode != 0:
541
+ raise FileNotFoundError("pip not in venv")
542
+ except (subprocess.TimeoutExpired, FileNotFoundError):
543
+ try:
544
+ _run_installer([sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"], timeout=120, check=True)
545
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
546
+ return _InstallResult(False, "", f"pip not available and ensurepip failed: {e}")
547
+ try:
548
+ return _finish(_run_installer(pip_cmd + ["install", *extra_args, *specs], timeout=timeout))
549
+ except subprocess.TimeoutExpired as e:
550
+ return _InstallResult(False, "", f"pip install timed out: {e}")
551
+ except Exception as e:
552
+ return _InstallResult(False, "", f"pip install failed: {e}")
553
+ finally:
554
+ if constraints is not None:
555
+ with contextlib.suppress(OSError):
556
+ constraints.unlink()
557
+
558
+
559
+ def feature_missing(feature: str) -> tuple[str, ...]:
560
+ """Return the subset of specs for ``feature`` not currently installed."""
561
+ if feature not in LAZY_DEPS:
562
+ raise KeyError(f"Unknown lazy feature: {feature!r}")
563
+ return tuple(s for s in LAZY_DEPS[feature] if not _is_satisfied(s))
564
+
565
+
566
+ def _prompt_toolkit_active() -> bool:
567
+ """A bare input() deadlocks while a prompt_toolkit app owns the terminal, so ensure() skips the
568
+ confirmation under the TUI — reaching it is already gated by security.allow_lazy_installs."""
569
+ if "prompt_toolkit.application.current" not in sys.modules:
570
+ return False
571
+ try:
572
+ from prompt_toolkit.application.current import get_app_or_none
573
+ return bool(getattr(get_app_or_none(), "is_running", False))
574
+ except Exception:
575
+ return False
576
+
577
+
578
+ def ensure(feature: str, *, prompt: bool = True) -> None:
579
+ """Make every package for ``feature`` importable, installing if needed; raises
580
+ :class:`FeatureUnavailable` when installs are disabled or fail. ``prompt``: confirm on a TTY first
581
+ (non-interactive callers pass False and rely on the config gate)."""
582
+ if feature not in LAZY_DEPS:
583
+ raise FeatureUnavailable(feature, (), f"feature {feature!r} not in LAZY_DEPS allowlist")
584
+ missing = feature_missing(feature)
585
+ if not missing:
586
+ return
587
+ if unsupported := _unsupported_feature_reason(feature):
588
+ raise FeatureUnavailable(feature, missing, unsupported)
589
+ # Package-manager installs (NixOS etc.) have read-only site-packages: fail fast instead of burning
590
+ # ~15s on ensurepip — unless a durable target is configured. The reason MUST start with
591
+ # "unsupported ": _refresh_features classifies skips by that prefix.
592
+ if _lazy_install_target() is None:
593
+ managed_by = "" # config unreadable — proceed with the install
594
+ with contextlib.suppress(Exception):
595
+ from hermes_cli.config import get_managed_system
596
+ managed_by = get_managed_system()
597
+ if managed_by:
598
+ raise FeatureUnavailable(
599
+ feature, missing,
600
+ f"unsupported on {managed_by}-managed installs: this build's packages come from {managed_by}, "
601
+ f"so Hermes cannot install them at runtime. Add the dependencies for {feature!r} via "
602
+ f"{managed_by} (or run a pip/uv install of Hermes instead).")
603
+ for spec in missing: # belt and braces on top of the allowlist
604
+ if not _spec_is_safe(spec):
605
+ raise FeatureUnavailable(feature, missing, f"refusing to install unsafe spec {spec!r}")
606
+ if not _allow_lazy_installs():
607
+ raise FeatureUnavailable(feature, missing, "lazy installs disabled (security.allow_lazy_installs=false)")
608
+ if prompt and not _prompt_toolkit_active() and sys.stdin.isatty() and sys.stdout.isatty():
609
+ try:
610
+ answer = input(f"\nFeature {feature!r} requires: {', '.join(missing)}\nInstall into the active venv now? [Y/n] ").strip().lower()
611
+ except (EOFError, KeyboardInterrupt):
612
+ answer = "n"
613
+ if answer and answer not in {"y", "yes"}:
614
+ raise FeatureUnavailable(feature, missing, "user declined install at prompt")
615
+ logger.info("Lazy-installing %s for feature %r", " ".join(missing), feature)
616
+ result = _venv_pip_install(missing)
617
+ if not result.success: # surface pip's own error (quarantine 404, network), tail-clipped
618
+ snippet = (result.stderr or result.stdout or "").strip()[-2000:]
619
+ raise FeatureUnavailable(feature, missing, f"pip install failed: {snippet or 'no error output'}")
620
+ _invalidate_import_caches()
621
+ if still_missing := feature_missing(feature):
622
+ raise FeatureUnavailable(feature, still_missing, "install reported success but packages still not importable (may require Python restart)")
623
+ logger.info("Lazy install complete for feature %r", feature)
624
+
625
+
626
+ def is_available(feature: str) -> bool:
627
+ """Return True if the feature's deps are already satisfied."""
628
+ return feature in LAZY_DEPS and not feature_missing(feature)
629
+
630
+
631
+ def feature_install_command(feature: str, *, venv_pip: bool = False) -> Optional[str]:
632
+ """Manual install command for a feature, or None. ``venv_pip=True`` uses ``{sys.executable} -m pip``
633
+ — immune to PEP 668 failures a bare ``pip install`` invites."""
634
+ if feature not in LAZY_DEPS:
635
+ return None
636
+ joined = " ".join(repr(s) for s in LAZY_DEPS[feature])
637
+ return f"{sys.executable} -m pip install {joined}" if venv_pip else "uv pip install " + joined
638
+
639
+
640
+ @dataclass
641
+ class InstallSpecsResult:
642
+ """Outcome of :func:`install_specs` for one batch of pip specs. ``blocked`` means installs are gated
643
+ off (config kill switch, sealed venv without a durable target) or a spec failed validation — nothing
644
+ was executed, ``reason`` says why. ``command`` is the human-readable description of what ran."""
645
+ ok: bool
646
+ blocked: bool = False
647
+ reason: str = ""
648
+ command: str = ""
649
+ stdout: str = ""
650
+ stderr: str = ""
651
+
652
+
653
+ def install_specs(specs: list[str] | tuple[str, ...], *, timeout: int = 300) -> InstallSpecsResult:
654
+ """Install data-driven pip specs (plugin manifest ``pip_dependencies``) with the same routing and
655
+ gating as :func:`ensure`, but unknown packages are allowed — the caller owns manifest trust, this
656
+ owns spec hygiene. Never raises; inspect the :class:`InstallSpecsResult`."""
657
+ cleaned = tuple(str(s).strip() for s in specs if str(s).strip())
658
+ if not cleaned:
659
+ return InstallSpecsResult(ok=True, command="")
660
+ for spec in cleaned:
661
+ if not _spec_is_safe(spec):
662
+ return InstallSpecsResult(ok=False, blocked=True, reason=f"refusing to install unsafe spec {spec!r}")
663
+ target = _lazy_install_target()
664
+ if not _allow_lazy_installs():
665
+ sealed = os.environ.get("HERMES_DISABLE_LAZY_INSTALLS") == "1" and target is None
666
+ reason = ("runtime installs are disabled on this deployment: the agent environment is immutable "
667
+ "and no writable install target is configured (HERMES_LAZY_INSTALL_TARGET)"
668
+ ) if sealed else "runtime installs disabled (security.allow_lazy_installs=false)"
669
+ return InstallSpecsResult(ok=False, blocked=True, reason=reason)
670
+ display = "uv pip install " + (f"--target {target} " if target is not None else "") + " ".join(cleaned)
671
+ logger.info("Installing pip specs %s (target=%s)", " ".join(cleaned), target or "venv")
672
+ try:
673
+ result = _venv_pip_install(cleaned, timeout=timeout)
674
+ except Exception as exc:
675
+ logger.warning("install_specs failed unexpectedly: %s", exc)
676
+ return InstallSpecsResult(ok=False, command=display, stderr=f"install failed: {exc}")
677
+
678
+ _invalidate_import_caches() # dashboard rechecks availability inline
679
+ return InstallSpecsResult(ok=result.success, command=display, stdout=result.stdout, stderr=result.stderr)
680
+
681
+
682
+ def active_features() -> list[str]:
683
+ """Features whose ANCHOR package (first spec) is present at any version — shared helpers like
684
+ asyncpg are deliberately not proof a backend was enabled. Drives ``hermes update``."""
685
+ return [f for f, specs in LAZY_DEPS.items() if specs and _is_present(specs[0])]
686
+
687
+
688
+ def refresh_active_features(*, prompt: bool = False) -> dict[str, str]:
689
+ """Re-run ``ensure`` for every active feature (``hermes update``); returns
690
+ ``{feature: "current" | "refreshed" | "failed: <reason>" | "skipped: <reason>"}``. Never raises."""
691
+ return _refresh_features(active_features(), prompt=prompt, restoring=False)
692
+
693
+
694
+ def restore_features(features: list[str]) -> dict[str, str]:
695
+ """Restore features captured before a managed-runtime rebuild; opt-out -> "skipped"."""
696
+ return _refresh_features(features, prompt=False, restoring=True)
697
+
698
+
699
+ def _refresh_features(features: list[str], *, prompt: bool, restoring: bool) -> dict[str, str]:
700
+ """Refresh or restore a known set of allowlisted lazy features."""
701
+ results: dict[str, str] = {}
702
+ for feature in features:
703
+ if feature not in LAZY_DEPS:
704
+ continue
705
+ if not feature_missing(feature):
706
+ results[feature] = "current"
707
+ continue
708
+ if unsupported := _unsupported_feature_reason(feature):
709
+ results[feature] = f"skipped: {unsupported}"
710
+ continue
711
+ try:
712
+ ensure(feature, prompt=False if restoring else prompt)
713
+ results[feature] = "restored" if restoring else "refreshed"
714
+ except FeatureUnavailable as e: # opt-outs and platform-incompatible features are skips, not failures
715
+ skip = "lazy installs disabled" in str(e) or "declined" in str(e) or e.reason.startswith("unsupported ")
716
+ results[feature] = f"skipped: {e.reason}" if skip else f"failed: {e.reason}"
717
+ except Exception as e:
718
+ results[feature] = f"failed: {e}"
719
+ return results
720
+
721
+
722
+ def ensure_and_bind(feature: str, importer: Callable[[], dict[str, Any]], target_globals: dict, *, prompt: bool = False) -> bool:
723
+ """:func:`ensure` the feature, then ``target_globals.update(importer())`` so module-level names are
724
+ rebound after a lazy install (``importer`` returns ``{name: obj}`` and runs only after ensure
725
+ succeeds). Returns False (and logs) if deps could not be installed or imported."""
726
+ try:
727
+ ensure(feature, prompt=prompt)
728
+ except FeatureUnavailable as exc:
729
+ logger.warning("%s", exc)
730
+ return False
731
+ except Exception as exc:
732
+ logger.warning("Failed to ensure feature %r: %s", feature, exc)
733
+ return False
734
+ try:
735
+ target_globals.update(importer())
736
+ except ImportError as exc:
737
+ logger.warning("Failed to import feature %r after install: %s", feature, exc)
738
+ return False
739
+ return True
740
+
741
+
742
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
743
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
744
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
745
+ # The whole block is removed by reverting the commit that added it.
746
+
747
+ def feature_specs(feature: str) -> tuple[str, ...]:
748
+ """Return the registered specs for a feature, or raise KeyError."""
749
+ if feature not in LAZY_DEPS:
750
+ raise KeyError(f"Unknown lazy feature: {feature!r}")
751
+ return LAZY_DEPS[feature]
752
+ # ---- END PLUGIN-COMPAT ----
tools/mcp_oauth.py ADDED
@@ -0,0 +1,1194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """MCP OAuth 2.1 client support: browser authorization-code flow with PKCE.
3
+
4
+ The SDK's ``OAuthClientProvider`` does discovery, client identification, PKCE, exchange and
5
+ refresh; this module supplies ``HermesTokenStorage`` (on-disk persistence), the localhost callback
6
+ listener and ``build_oauth_auth()`` (legacy entry point). client_id is Hermes' Client ID Metadata
7
+ Document URL (CIMD) when the server supports it, else RFC 7591 DCR. ``mcp_servers.<name>.oauth`` keys
8
+ (all optional): client_id, client_secret, scope, redirect_port, redirect_uri (proxy callback),
9
+ redirect_host, client_name, client_metadata_url, cimd, user_agent, timeout."""
10
+
11
+ import asyncio
12
+ import contextlib
13
+ import contextvars
14
+ import errno
15
+ import html
16
+ import importlib.util as _importlib_util
17
+ import json
18
+ import logging
19
+ import os
20
+ import re
21
+ import socket
22
+ import stat
23
+ import sys
24
+ import threading
25
+ import time
26
+ import webbrowser
27
+ from functools import partialmethod
28
+
29
+ # Cross-process advisory file locking for the refresh fence. Mirrors
30
+ # cron/jobs.py: fcntl is Unix-only, msvcrt is the Windows fallback.
31
+ try:
32
+ import fcntl
33
+ except ImportError: # pragma: no cover - non-Unix
34
+ fcntl = None
35
+ try:
36
+ import msvcrt
37
+ except ImportError: # pragma: no cover - non-Windows
38
+ msvcrt = None
39
+ from http.server import BaseHTTPRequestHandler, HTTPServer
40
+ from pathlib import Path
41
+ from typing import TYPE_CHECKING, Any
42
+ from urllib.parse import parse_qs, urlparse
43
+
44
+ from hermes_constants import secure_parent_dir
45
+ from utils import atomic_json_write
46
+ from tools.mcp_dashboard_oauth import contextvar_set as _contextvar_set, get_dashboard_oauth_flow
47
+
48
+ if TYPE_CHECKING: # annotations only; the SDK is imported lazily at runtime
49
+ from mcp.client.auth import OAuthClientProvider
50
+ from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthMetadata, OAuthToken
51
+
52
+ logger = logging.getLogger(__name__)
53
+
54
+ # The refresh fence's critical section spans the token-endpoint POST, so it must
55
+ # outlast a slow network round trip. Bounded anyway -- a wedged peer must not
56
+ # strand us forever -- but generous enough that a healthy refresh never trips it.
57
+ _REFRESH_FENCE_TIMEOUT_SECONDS = 60.0
58
+
59
+ class RefreshFenceTimeout(RuntimeError):
60
+ """The refresh fence could not be acquired within its bound.
61
+
62
+ Raised so the caller FAILS CLOSED. Submitting a refresh token we are not
63
+ certain we own is the whole defect class this fence exists to close: on a
64
+ provider with single-use refresh tokens it burns the credential and logs
65
+ the user out of a working session. Aborting this one refresh attempt is
66
+ strictly cheaper -- the next request retries, and by then the peer that
67
+ held the fence has published its replacement.
68
+ """
69
+
70
+
71
+ # POSIX flock: EWOULDBLOCK/EAGAIN, EACCES on some NFS; msvcrt.locking: EACCES/EDEADLK.
72
+ # Same set as cron.scheduler._is_lock_contention_errno (not imported: that module is heavy).
73
+ _FENCE_CONTENTION_ERRNOS = frozenset({errno.EWOULDBLOCK, errno.EAGAIN, errno.EACCES, errno.EDEADLK})
74
+
75
+
76
+ def _refresh_lock_path(path: "Path") -> "Path":
77
+ return path.with_suffix(path.suffix + ".refresh.lock")
78
+
79
+
80
+ async def acquire_refresh_fence(path: "Path", *, timeout: float = _REFRESH_FENCE_TIMEOUT_SECONDS) -> int:
81
+ """Take the fence that owns one refresh generation across read -> POST -> persist.
82
+
83
+ Token files are written atomically (``_write_json``), so a reader never
84
+ sees a torn file; the only cross-process hazard is the read-modify-write
85
+ of a single-use refresh token. The damaging interleaving is:
86
+
87
+ A: get_tokens() -> R1
88
+ B: get_tokens() -> R1
89
+ A: POST R1 -> 200, receives R2
90
+ B: POST R1 -> 400, credential already burned
91
+ B: clear_tokens() -> user is logged out of a live session
92
+
93
+ No lock scoped to one file read or write can prevent it: the fence must
94
+ be held across the POST. It lives in a ``.refresh.lock`` sibling of the
95
+ token file so the holder can still read/write the tokens normally.
96
+
97
+ Entered from the SDK's coroutine-driven auth flow, so the wait is an
98
+ ``asyncio.sleep`` poll on a non-blocking lock: a peer's slow network
99
+ round trip must not freeze every other task on this event loop. No
100
+ in-process lock layer is needed: an advisory lock on a fresh descriptor
101
+ already excludes sibling tasks and threads of the same process.
102
+
103
+ Acquisition failure RAISES. Degrading to "proceed unlocked" would
104
+ reintroduce the exact race. Returns the locked descriptor; the caller
105
+ hands it back to ``release_refresh_fence`` from its own exit path (the
106
+ SDK drives the refresh as a generator, so no single ``with`` block can
107
+ span the critical section).
108
+ """
109
+ lock_path = _refresh_lock_path(path)
110
+ try:
111
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
112
+ secure_parent_dir(lock_path)
113
+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)
114
+ except OSError as exc:
115
+ # No lock file means no ownership proof. Fail closed: see the
116
+ # class docstring for why proceeding is worse than aborting.
117
+ raise RefreshFenceTimeout(
118
+ f"refresh fence unavailable ({lock_path.name}): {exc}"
119
+ ) from exc
120
+
121
+ deadline = time.monotonic() + timeout
122
+ try:
123
+ while True:
124
+ try:
125
+ if fcntl is not None:
126
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
127
+ elif msvcrt is not None:
128
+ getattr(msvcrt, "locking")(fd, getattr(msvcrt, "LK_NBLCK"), 1)
129
+ else: # pragma: no cover - no advisory locking primitive
130
+ raise RefreshFenceTimeout(
131
+ "refresh fence unsupported: no flock/msvcrt on this platform"
132
+ )
133
+ return fd
134
+ except OSError as exc:
135
+ if exc.errno not in _FENCE_CONTENTION_ERRNOS:
136
+ # Not "a peer holds it" but "this filesystem cannot lock"
137
+ # (e.g. some network mounts). Still fail closed, but say so
138
+ # now instead of spinning to the deadline and blaming a peer.
139
+ raise RefreshFenceTimeout(
140
+ f"refresh fence unavailable on this filesystem: {exc}"
141
+ ) from exc
142
+ if time.monotonic() >= deadline:
143
+ raise RefreshFenceTimeout(
144
+ f"refresh fence held by a peer for {timeout:.0f}s ({lock_path.name})"
145
+ ) from None
146
+ await asyncio.sleep(0.05)
147
+ except BaseException:
148
+ os.close(fd)
149
+ raise
150
+
151
+
152
+ def release_refresh_fence(fd: int) -> None:
153
+ """Unlock and close a descriptor returned by ``acquire_refresh_fence``. Never raises."""
154
+ try:
155
+ if fcntl is not None:
156
+ fcntl.flock(fd, fcntl.LOCK_UN)
157
+ elif msvcrt is not None:
158
+ getattr(msvcrt, "locking")(fd, getattr(msvcrt, "LK_UNLCK"), 1)
159
+ except OSError:
160
+ pass
161
+ finally:
162
+ with contextlib.suppress(OSError):
163
+ os.close(fd)
164
+
165
+
166
+ # ---------------------------------------------------------------------------
167
+ # Lazy imports -- MCP SDK with OAuth support is optional
168
+ # ---------------------------------------------------------------------------
169
+
170
+ # SDK availability is detected WITHOUT importing mcp (~170 ms); classes bind lazily via _sdk_class().
171
+ _OAUTH_AVAILABLE = _importlib_util.find_spec("mcp") is not None
172
+ if not _OAUTH_AVAILABLE:
173
+ logger.debug("MCP OAuth types not available -- OAuth MCP auth disabled")
174
+
175
+ _SDK_CLASS_NAMES = ("OAuthClientProvider", "OAuthClientInformationFull", "OAuthClientMetadata", "OAuthMetadata", "OAuthToken")
176
+ _SDK_CLASSES: dict[str, Any] = {}
177
+
178
+
179
+ def _sdk_class(name: str) -> Any:
180
+ """SDK OAuth class *name*, importing the SDK on first call; None when unavailable (a broken SDK is probed once)."""
181
+ global _OAUTH_AVAILABLE
182
+ if not _SDK_CLASSES:
183
+ try:
184
+ from mcp.client import auth as _client_auth
185
+ from mcp.shared import auth as _shared_auth
186
+
187
+ _SDK_CLASSES["OAuthClientProvider"] = _client_auth.OAuthClientProvider
188
+ for _name in _SDK_CLASS_NAMES[1:]:
189
+ _SDK_CLASSES[_name] = getattr(_shared_auth, _name)
190
+ except (ImportError, AttributeError):
191
+ _SDK_CLASSES.update(dict.fromkeys(_SDK_CLASS_NAMES))
192
+ _OAUTH_AVAILABLE = False
193
+ logger.debug("MCP OAuth types not available -- OAuth MCP auth disabled")
194
+ return _SDK_CLASSES.get(name)
195
+
196
+
197
+ try:
198
+ from pydantic import AnyUrl
199
+ except ImportError:
200
+ AnyUrl = None # type: ignore[assignment, misc]
201
+
202
+
203
+ class OAuthNonInteractiveError(RuntimeError):
204
+ """Raised when OAuth requires browser interaction in a non-interactive env."""
205
+
206
+
207
+ # Port of the most recent callback-port resolution. Legacy global; per-flow closures are the
208
+ # real mechanism (concurrent flows must not share it).
209
+ _oauth_port: int | None = None
210
+
211
+ # Interactivity gates for OAuth stdin prompts. ContextVars, NOT threading.local: background
212
+ # discovery sets them on its own thread while connect+OAuth runs on the `mcp-event-loop` thread
213
+ # via run_coroutine_threadsafe, which copies the calling context into the coroutine. `forced`
214
+ # pushes _is_interactive() past the TTY check for GUI-driven flows (dashboard/desktop REST; the
215
+ # paste fallback degrades harmlessly to EOF). Suppression wins — background discovery must never
216
+ # start a browser flow.
217
+ _oauth_interactive_enabled = contextvars.ContextVar("_oauth_interactive_enabled", default=True)
218
+ _oauth_interactive_forced = contextvars.ContextVar("_oauth_interactive_forced", default=False)
219
+
220
+ # Paste-prompt tokens that exit OAuth without auth; the waiter maps the sentinel to
221
+ # OAuthNonInteractiveError("user_skipped") so MCP setup continues without this server.
222
+ _SKIP_TOKENS = frozenset({"skip", "cancel", "s", "n", "no", "q", "quit"})
223
+ _USER_SKIPPED_SENTINEL = "__hermes_user_skipped__"
224
+
225
+
226
+ def _get_token_dir(hermes_home: str | Path | None = None) -> Path:
227
+ """``HERMES_HOME/mcp-tokens/`` — per-profile token directory."""
228
+ from hermes_constants import get_hermes_home
229
+
230
+ return Path(hermes_home if hermes_home is not None else get_hermes_home()) / "mcp-tokens"
231
+
232
+
233
+ def _safe_filename(name: str) -> str:
234
+ """Sanitize a server name for use as a filename (no path separators)."""
235
+ return re.sub(r"[^\w\-]", "_", name).strip("_")[:128] or "default"
236
+
237
+
238
+ # Callback-port reservation: bound-but-not-listening sockets keyed by port, held from selection
239
+ # until the waiter adopts them (closes the select→bind TOCTOU window). Bounded so reconnect loops cannot leak fds.
240
+ # Holding the socket from port-selection time until _wait_for_callback adopts it closes the TOCTOU window
241
+ # where another process could grab the port between _find_free_port() closing its probe socket and
242
+ # HTTPServer binding minutes later (#22161).
243
+ _reserved_sockets: "dict[int, socket.socket]" = {}
244
+ _MAX_RESERVED_SOCKETS = 8
245
+
246
+
247
+ def _bind_reserved(port: int) -> int | None:
248
+ """Bind ``127.0.0.1:port`` (0 = ephemeral) and park it until the waiter adopts it; None if taken.
249
+ The cap evicts ephemeral parks only: losing a pinned CIMD port (the only ones the published
250
+ document declares) mid-flow would reopen the race."""
251
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
252
+ try:
253
+ sock.bind(("127.0.0.1", port))
254
+ except OSError:
255
+ sock.close()
256
+ if port:
257
+ return None
258
+ raise
259
+ bound = sock.getsockname()[1]
260
+ while len(_reserved_sockets) >= _MAX_RESERVED_SOCKETS:
261
+ stale_port = next((p for p in _reserved_sockets if p not in _CIMD_PORTS), None)
262
+ if stale_port is None:
263
+ break # only pinned sockets remain — never evict those
264
+ with contextlib.suppress(OSError):
265
+ _reserved_sockets.pop(stale_port).close()
266
+ _reserved_sockets[bound] = sock
267
+ return bound
268
+
269
+
270
+ def _reserve_callback_port() -> int:
271
+ """Pick an ephemeral callback port and keep its socket bound (parked)."""
272
+ return _bind_reserved(0) # type: ignore[return-value] # port 0 never returns None
273
+
274
+
275
+ def _cached_client_info(storage: "HermesTokenStorage | None") -> dict | None:
276
+ """The on-disk client registration for *storage*, or None."""
277
+ try:
278
+ return _read_json(storage._client_info_path()) if storage is not None else None
279
+ except (AttributeError, TypeError, ValueError):
280
+ return None
281
+
282
+
283
+ def _cached_redirect(storage: "HermesTokenStorage | None") -> "tuple[str | None, int | None]":
284
+ """``(https proxy URI, loopback callback port)`` from the cached client registration (None when
285
+ absent): a DCR ``client_id`` is bound to its registered redirect URI, so a new random port under
286
+ it gets ``redirect_uri does not match any registered URIs``."""
287
+ uri = port = None
288
+ for raw in (_cached_client_info(storage) or {}).get("redirect_uris") or []:
289
+ try:
290
+ parsed = urlparse(str(raw))
291
+ except (TypeError, ValueError):
292
+ continue
293
+ if uri is None and parsed.scheme == "https" and parsed.netloc:
294
+ uri = str(raw)
295
+ is_loopback_callback = parsed.scheme == "http" and parsed.path == "/callback" and parsed.hostname in {"127.0.0.1", "localhost"}
296
+ if port is None and is_loopback_callback and parsed.port is not None:
297
+ port = int(parsed.port)
298
+ return uri, port
299
+
300
+
301
+ def _stdin_is_console() -> bool:
302
+ """A human can type on stdin. ``isatty()`` alone is wrong on Windows: the CRT reports True for
303
+ a DEVNULL / detached / CREATE_NO_WINDOW stdin (the gateway's), so a background process looked
304
+ interactive and launched browser OAuth flows nobody could finish. Confirm with the console API
305
+ there: ``GetConsoleMode`` fails on anything that is not a real console handle."""
306
+ try:
307
+ if not sys.stdin.isatty():
308
+ return False
309
+ except (AttributeError, ValueError):
310
+ return False
311
+ if os.name != "nt":
312
+ return True
313
+ try:
314
+ import ctypes
315
+ import msvcrt
316
+ handle = msvcrt.get_osfhandle(sys.stdin.fileno())
317
+ mode = ctypes.c_ulong()
318
+ return bool(ctypes.windll.kernel32.GetConsoleMode(ctypes.c_void_p(handle), ctypes.byref(mode)))
319
+ except Exception:
320
+ return False
321
+
322
+
323
+ def _is_interactive() -> bool:
324
+ """True if we can reasonably expect to interact with a user."""
325
+ if not _oauth_interactive_enabled.get():
326
+ return False
327
+ if _oauth_interactive_forced.get():
328
+ return True
329
+ return _stdin_is_console()
330
+
331
+
332
+ def _raise_if_non_interactive(lead: str) -> None:
333
+ """Raise ``OAuthNonInteractiveError`` unless interactive; *lead* is the boundary-specific first sentence.
334
+
335
+ ``lead`` is the boundary-specific first sentence; this helper appends the shared, actionable ``hermes
336
+ mcp login`` next-step so the guidance wording lives in one place across every non-interactive OAuth
337
+ boundary (#57836).
338
+ """
339
+ if not _is_interactive():
340
+ raise OAuthNonInteractiveError(
341
+ f"{lead} Run `hermes mcp login <server>` interactively to (re)authorize, then restart or reload the gateway."
342
+ )
343
+
344
+
345
+ def force_interactive_oauth():
346
+ """Treat the context as interactive despite no TTY (GUI-driven auth: the user IS present, just not
347
+ on stdin). Crosses the MCP event-loop thread like ``suppress_interactive_oauth``.
348
+
349
+ Opens the browser + localhost callback flow that the TTY heuristic would otherwise refuse. Same
350
+ ContextVar propagation story as suppress_interactive_oauth() (#35927).
351
+ """
352
+ return _contextvar_set(_oauth_interactive_forced, True)
353
+
354
+
355
+ def suppress_interactive_oauth():
356
+ """Disable stdin-based OAuth prompts for the current context; ContextVar-based so a
357
+ background-discovery thread's suppression reaches the coroutine on the MCP event-loop thread.
358
+
359
+ Uses a ContextVar so the suppression propagates from a background-discovery thread onto the coroutine
360
+ scheduled (via run_coroutine_threadsafe) on the dedicated MCP event-loop thread — where the OAuth
361
+ callback actually runs (#35927). A threading.local would not cross that thread boundary.
362
+ """
363
+ return _contextvar_set(_oauth_interactive_enabled, False)
364
+
365
+
366
+ def _can_open_browser() -> bool:
367
+ """True if opening a browser is likely to work."""
368
+ if os.environ.get("SSH_CLIENT") or os.environ.get("SSH_TTY"):
369
+ return False # explicit SSH session → no local display
370
+ if os.name == "nt" or (hasattr(os, "uname") and os.uname().sysname == "Darwin"):
371
+ return True
372
+ return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
373
+
374
+
375
+ def _read_json(path: Path) -> dict | None:
376
+ """Read a JSON file, returning None if it doesn't exist or is invalid."""
377
+ if not path.exists():
378
+ return None
379
+ try:
380
+ return json.loads(path.read_text(encoding="utf-8"))
381
+ except (json.JSONDecodeError, OSError) as exc:
382
+ logger.warning("Failed to read %s: %s", path, exc)
383
+ return None
384
+
385
+
386
+ def _write_json(path: Path, data: dict) -> None:
387
+ """OAuth tokens/client info at 0600 from creation, parent tightened to 0700 (``secure_parent_dir``
388
+ refuses ``/``, top-level dirs and the install tree — #25821, #93050)."""
389
+ path.parent.mkdir(parents=True, exist_ok=True)
390
+ secure_parent_dir(path)
391
+ atomic_json_write(path, data, mode=0o600, default=str)
392
+
393
+
394
+ def _model_json(model: Any) -> dict:
395
+ """The on-disk JSON shape of an SDK pydantic model."""
396
+ return model.model_dump(mode="json", exclude_none=True)
397
+
398
+
399
+ class HermesTokenStorage:
400
+ """Persist OAuth state as ``HERMES_HOME/mcp-tokens/<server_name>`` + ``.json`` (tokens),
401
+ ``.client.json`` (client info), ``.meta.json`` (server metadata), ``.cimd-off`` (CIMD refused)."""
402
+
403
+ def __init__(self, server_name: str, *, hermes_home: str | Path | None = None):
404
+ self._server_name = _safe_filename(server_name)
405
+ self._hermes_home = Path(hermes_home) if hermes_home is not None else None
406
+ # Issuer binding: ``loaded_issuer`` is what the token file on disk recorded (the authorization
407
+ # server that granted the stored refresh token); ``_bound_issuer`` is stamped onto the next
408
+ # ``set_tokens`` write. See ``tools.mcp_oauth_provider.enforce_refresh_token_issuer``.
409
+ self.loaded_issuer: str | None = None
410
+ self._bound_issuer: str | None = None
411
+
412
+ def _path(self, suffix: str) -> Path:
413
+ return _get_token_dir(self._hermes_home) / f"{self._server_name}{suffix}"
414
+
415
+ _tokens_path = partialmethod(_path, ".json")
416
+ _client_info_path = partialmethod(_path, ".client.json")
417
+ _meta_path = partialmethod(_path, ".meta.json")
418
+ _cimd_rejected_path = partialmethod(_path, ".cimd-off")
419
+
420
+ def _state_paths(self) -> tuple[Path, Path, Path]:
421
+ return self._tokens_path(), self._client_info_path(), self._meta_path()
422
+
423
+ @staticmethod
424
+ def _load_model(path: Path, sdk_name: str, label: str, fixup=None):
425
+ """Read *path* into SDK model *sdk_name*; None if absent, no SDK, or corrupt.
426
+ ``fixup(data)`` may rewrite the raw dict before validation."""
427
+ data = _read_json(path)
428
+ cls = _sdk_class(sdk_name) if data is not None else None
429
+ if (cls is not None and sdk_name == "OAuthMetadata" and isinstance(data, dict)
430
+ and data.get("device_authorization_endpoint")):
431
+ from tools.mcp_oauth_device import DeviceOAuthMetadata
432
+ cls = DeviceOAuthMetadata
433
+ if cls is None:
434
+ return None
435
+ if fixup is not None:
436
+ fixup(data)
437
+ try:
438
+ return cls.model_validate(data)
439
+ except (ValueError, TypeError, KeyError) as exc:
440
+ # A pydantic ValidationError's str() echoes the raw input (the token material); log
441
+ # only which fields failed.
442
+ detail = exc
443
+ if hasattr(exc, "errors"): # pydantic ValidationError
444
+ detail = "validation failed for " + ", ".join(
445
+ ".".join(map(str, e.get("loc", ()))) for e in exc.errors(include_input=False))
446
+ logger.warning("Corrupt %s at %s -- ignoring: %s", label, path, detail)
447
+ return None
448
+
449
+ def _rebase_expires_in(self, data: dict) -> None:
450
+ """Rewrite ``expires_in`` to seconds remaining from the stored absolute ``expires_at`` (not an
451
+ SDK field, so stripped): a relative value reloaded after restart would make ``is_token_valid()``
452
+ True for tokens that expired while down. Legacy files without it use the file mtime, clamped
453
+ to zero (self-heals on the next ``set_tokens``)."""
454
+ absolute_expiry = data.pop("expires_at", None)
455
+ if absolute_expiry is not None:
456
+ data["expires_in"] = int(max(absolute_expiry - time.time(), 0))
457
+ elif data.get("expires_in") is not None:
458
+ with contextlib.suppress(OSError, TypeError, ValueError):
459
+ implied_expiry = self._tokens_path().stat().st_mtime + int(data["expires_in"])
460
+ data["expires_in"] = int(max(implied_expiry - time.time(), 0))
461
+
462
+ def _fixup_loaded_tokens(self, data: dict) -> None:
463
+ # ``hermes_issuer`` is Hermes bookkeeping, not an SDK OAuthToken field: pop before validation.
464
+ self.loaded_issuer = data.pop("hermes_issuer", None)
465
+ self._rebase_expires_in(data)
466
+
467
+ async def get_tokens(self) -> "OAuthToken | None":
468
+ self.loaded_issuer = None
469
+ return self._load_model(self._tokens_path(), "OAuthToken", "tokens", self._fixup_loaded_tokens)
470
+
471
+ async def set_tokens(self, tokens: "OAuthToken") -> None:
472
+ payload = _model_json(tokens)
473
+ # Absolute ``expires_at``: see _rebase_expires_in.
474
+ if payload.get("expires_in") is not None:
475
+ with contextlib.suppress(TypeError, ValueError): # mock tokens / odd shapes: skip, don't fail persistence
476
+ payload["expires_at"] = time.time() + int(payload["expires_in"])
477
+ if self._bound_issuer: # which authorization server granted these tokens (never sent on the wire)
478
+ payload["hermes_issuer"] = self._bound_issuer
479
+ self.loaded_issuer = self._bound_issuer
480
+ _write_json(self._tokens_path(), payload)
481
+ logger.debug("OAuth tokens saved for %s", self._server_name)
482
+
483
+ def bind_issuer(self, issuer: str | None) -> None:
484
+ """Set the authorization-server issuer stamped on future token writes."""
485
+ self._bound_issuer = str(issuer) if issuer else None
486
+
487
+ def stamp_issuer(self, issuer: str) -> None:
488
+ """Backfill ``hermes_issuer`` onto a pre-binding token file: adopt the currently discovered
489
+ issuer once instead of forcing a re-login, so the *next* read is protected."""
490
+ data = _read_json(self._tokens_path())
491
+ if data is None or data.get("hermes_issuer"):
492
+ return
493
+ data["hermes_issuer"] = str(issuer)
494
+ try:
495
+ _write_json(self._tokens_path(), data)
496
+ except OSError as exc: # non-fatal — worst case we stamp next time
497
+ logger.debug("Could not stamp issuer on tokens for %s: %s", self._server_name, exc)
498
+ return
499
+ self.loaded_issuer = str(issuer)
500
+
501
+ def strip_refresh_token(self) -> None:
502
+ """Drop the refresh token (and its issuer record) from disk, keeping the access token: the
503
+ unexpired access token may still be used, but a refresh token must never go to a different
504
+ issuer than the one that granted it."""
505
+ data = _read_json(self._tokens_path())
506
+ if data is None or not data.get("refresh_token"):
507
+ return
508
+ data.pop("refresh_token", None)
509
+ data.pop("hermes_issuer", None)
510
+ self.loaded_issuer = None
511
+ try:
512
+ _write_json(self._tokens_path(), data)
513
+ except OSError as exc:
514
+ logger.warning("Could not strip refresh token for %s: %s", self._server_name, exc)
515
+ return
516
+ logger.info("Removed issuer-mismatched refresh token for %s (re-authorization will be required "
517
+ "when the access token expires)", self._server_name)
518
+
519
+ @staticmethod
520
+ def _coerce_secret_auth_method(data: dict) -> bool:
521
+ """Set ``client_secret_post`` when a secret is present but no method is: some DCR providers
522
+ (Supabase) omit ``token_endpoint_auth_method``, the SDK defaults it to ``none`` and the
523
+ exchange fails without the secret."""
524
+ if data.get("client_secret") and data.get("token_endpoint_auth_method") in (None, "none", ""):
525
+ data["token_endpoint_auth_method"] = "client_secret_post"
526
+ return True
527
+ return False
528
+
529
+ async def get_client_info(self) -> "OAuthClientInformationFull | None":
530
+ coerced: list[bool] = []
531
+ info = self._load_model(
532
+ self._client_info_path(), "OAuthClientInformationFull", "client info",
533
+ lambda data: coerced.append(self._coerce_secret_auth_method(data)))
534
+ if info is not None and coerced[0]:
535
+ _write_json(self._client_info_path(), _model_json(info)) # persist so later flows skip the coercion
536
+ return info
537
+
538
+ async def set_client_info(self, client_info: "OAuthClientInformationFull") -> None:
539
+ data = _model_json(client_info)
540
+ self._coerce_secret_auth_method(data)
541
+ _write_json(self._client_info_path(), data)
542
+ logger.debug("OAuth client info saved for %s", self._server_name)
543
+
544
+ def save_oauth_metadata(self, metadata: "OAuthMetadata") -> None:
545
+ """Persist server metadata so a restarted process can refresh without re-discovery;
546
+ otherwise the SDK guesses ``{server_url}/token`` (404) and forces re-auth."""
547
+ _write_json(self._meta_path(), _model_json(metadata))
548
+ logger.debug("OAuth metadata saved for %s", self._server_name)
549
+
550
+ def load_oauth_metadata(self) -> "OAuthMetadata | None":
551
+ return self._load_model(self._meta_path(), "OAuthMetadata", "OAuth metadata")
552
+
553
+ def mark_cimd_rejected(self) -> None:
554
+ """Durably record that this server refused our CIMD document so a restart does not re-present
555
+ the refused client_id. Cleared by ``remove()`` so a fixed document gets a retry."""
556
+ path = self._cimd_rejected_path()
557
+ try:
558
+ path.parent.mkdir(parents=True, exist_ok=True)
559
+ path.touch()
560
+ except OSError as exc: # non-fatal — worst case we retry CIMD later
561
+ logger.debug("Could not record CIMD rejection at %s: %s", path, exc)
562
+
563
+ def cimd_rejected(self) -> bool:
564
+ """True when this server has refused our metadata document before."""
565
+ return self._cimd_rejected_path().exists()
566
+
567
+ def remove(self) -> None:
568
+ """Delete all stored OAuth state for this server."""
569
+ # The ``.refresh.lock`` sidecar is deliberately kept: flock is inode-bound, so unlinking it
570
+ # while a peer holds the fence would let the next acquirer lock a fresh inode (two holders).
571
+ for p in (*self._state_paths(), self._cimd_rejected_path()):
572
+ p.unlink(missing_ok=True)
573
+
574
+ def snapshot(self) -> dict[str, bytes]:
575
+ """filename -> bytes of the existing state files; ``restore()`` it to undo a ``remove()`` after
576
+ a failed re-auth so a valid token survives."""
577
+ snap: dict[str, bytes] = {}
578
+ for p in self._state_paths():
579
+ with contextlib.suppress(OSError):
580
+ snap[p.name] = p.read_bytes()
581
+ return snap
582
+
583
+ def restore(self, snapshot: dict[str, bytes], *, only_if_absent: bool = False) -> None:
584
+ """Revert to a snapshot without overwriting a concurrent successful write."""
585
+ if only_if_absent and any(path.exists() for path in self._state_paths()):
586
+ logger.info("Skipping OAuth rollback for %s because newer state exists", self._server_name)
587
+ return
588
+ self.remove()
589
+ if not snapshot:
590
+ return
591
+ token_dir = _get_token_dir(self._hermes_home)
592
+ token_dir.mkdir(parents=True, exist_ok=True)
593
+ for fname, data in snapshot.items():
594
+ try:
595
+ fd = os.open(str(token_dir / fname), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, stat.S_IRUSR | stat.S_IWUSR)
596
+ with os.fdopen(fd, "wb") as fh:
597
+ fh.write(data)
598
+ except OSError as exc:
599
+ logger.warning("Failed to restore OAuth state %s: %s", fname, exc)
600
+
601
+ def poison_client_registration(self) -> bool:
602
+ """Discard a dead DCR client (``invalid_client`` at the token endpoint) plus stale ``meta.json``
603
+ so the SDK re-registers next flow; tokens are kept (a valid refresh token survives if
604
+ re-registration never completes). Keeps one ``.bak``. True if a client file was removed."""
605
+ client_path = self._client_info_path()
606
+ if not client_path.exists():
607
+ return False
608
+ backup = client_path.with_name(client_path.name + ".bak")
609
+ try:
610
+ backup.write_bytes(client_path.read_bytes())
611
+ except OSError as exc: # non-fatal — proceed with the removal anyway
612
+ logger.warning("Could not back up client info at %s: %s", client_path, exc)
613
+ client_path.unlink(missing_ok=True)
614
+ self._meta_path().unlink(missing_ok=True)
615
+ logger.warning(
616
+ "MCP OAuth '%s': cached client registration rejected as invalid_client; "
617
+ "removed client.json + meta.json (backup at %s) to force re-registration",
618
+ self._server_name, backup.name)
619
+ return True
620
+
621
+ def has_cached_tokens(self) -> bool:
622
+ """True if we have tokens on disk (may be expired)."""
623
+ return self._tokens_path().exists()
624
+
625
+
626
+ # Callback capture: the HTTP listener and the stdin paste reader share one result dict.
627
+ def _authorization_code_result(code: str, state: "str | None", iss: "str | None" = None):
628
+ """Redirect parameters in the shape the installed SDK expects: mcp 2.0's ``callback_handler``
629
+ returns an ``AuthorizationCodeResult`` (the SDK reads ``.state``/``.iss`` off it); older SDKs take a tuple."""
630
+ try:
631
+ from mcp.shared.auth import AuthorizationCodeResult
632
+ except ImportError: # mcp < 2.0
633
+ return code, state
634
+ return AuthorizationCodeResult(code=code, state=state, iss=iss)
635
+
636
+
637
+ def _parse_redirect_query(query: str) -> dict[str, Any]:
638
+ """code/state/error/iss from a redirect query string. ``iss`` (RFC 9207 issuer) is kept: mcp 2.0
639
+ rejects a response omitting it when the server advertised ``authorization_response_iss_parameter_supported``."""
640
+ params = parse_qs(query)
641
+ return {k: params.get(k, [None])[0] for k in ("code", "state", "error", "iss")}
642
+
643
+
644
+ def _result_taken(result: dict) -> bool:
645
+ return result.get("auth_code") is not None or result.get("error") is not None
646
+
647
+
648
+ def _make_callback_handler() -> tuple[type, dict]:
649
+ """Fresh ``(HandlerClass, result_dict)`` per flow so concurrent flows don't stomp on each other."""
650
+ result: dict[str, Any] = {"auth_code": None, "state": None, "error": None, "iss": None}
651
+
652
+ class _Handler(BaseHTTPRequestHandler):
653
+ def do_GET(self) -> None: # noqa: N802
654
+ parsed = _parse_redirect_query(urlparse(self.path).query)
655
+ result.update(auth_code=parsed["code"], state=parsed["state"], error=parsed["error"], iss=parsed["iss"])
656
+ body = ("<h2>Authorization Successful</h2><p>You can close this tab and return to Hermes.</p>" if parsed["code"]
657
+ else f"<h2>Authorization Failed</h2><p>Error: {html.escape(parsed['error'] or 'unknown')}</p>")
658
+ self.send_response(200)
659
+ self.send_header("Content-Type", "text/html; charset=utf-8")
660
+ self.end_headers()
661
+ self.wfile.write(f"<html><body>{body}</body></html>".encode())
662
+
663
+ def log_message(self, fmt: str, *args: Any) -> None:
664
+ logger.debug("OAuth callback: %s", fmt % args)
665
+
666
+ return _Handler, result
667
+
668
+
669
+ def _paste_callback_reader(result: dict) -> None:
670
+ """Read one stdin line as an OAuth redirect (full URL, bare query, or a ``_SKIP_TOKENS`` word that
671
+ exits without auth) into *result*. Parse failures, EOF and interrupts are swallowed — best-effort
672
+ fallback racing the HTTP listener, which stays primary."""
673
+ try:
674
+ line = sys.stdin.readline()
675
+ except (KeyboardInterrupt, OSError, ValueError):
676
+ return
677
+ line = (line or "").strip()
678
+ if not line or _result_taken(result):
679
+ return # EOF / blank, or the HTTP listener already won
680
+ if line.lower() in _SKIP_TOKENS:
681
+ result["error"] = _USER_SKIPPED_SENTINEL
682
+ print(
683
+ " OAuth skipped. Run `hermes mcp login <server>` later to authenticate, "
684
+ "or set ``enabled: false`` on that server in config.yaml to disable persistently.",
685
+ file=sys.stderr)
686
+ return
687
+ # Full URL or "?code=...": take everything after the first "?".
688
+ query = line.split("?", 1)[1] if "?" in line else line
689
+ try:
690
+ parsed = _parse_redirect_query(query.removeprefix("?"))
691
+ except (ValueError, TypeError):
692
+ print(" Could not parse pasted input as an OAuth redirect — ignoring.", file=sys.stderr)
693
+ return
694
+ if not parsed["code"] and not parsed["error"]:
695
+ print(" Pasted input did not contain ``code=`` or ``error=`` — ignoring.", file=sys.stderr)
696
+ return
697
+ if _result_taken(result): # one more race-check before writing
698
+ return
699
+ result.update(auth_code=parsed["code"], state=parsed["state"], error=parsed["error"], iss=parsed["iss"])
700
+ if parsed["code"]:
701
+ print(" Got authorization code from paste — completing flow.", file=sys.stderr)
702
+
703
+
704
+ # Remote-session hints printed under the authorization URL: a proxy callback forwards the redirect
705
+ # here (no tunnel needed); on loopback it misses this machine, so the user pastes the URL back or SSH-forwards the port.
706
+ _SSH_HINT_PROXY = (
707
+ " Remote session detected. After you authorize, the provider redirects to\n"
708
+ " {redirect_uri}\n"
709
+ " which forwards to the callback listener on this machine — no SSH tunnel needed.\n")
710
+ _SSH_HINT_LOOPBACK = (
711
+ " Remote session detected. After you authorize, the provider redirects to\n"
712
+ " http://127.0.0.1:{port}/callback\n"
713
+ " which only the listener on THIS machine can receive. Two options:\n"
714
+ "\n"
715
+ " 1. Easiest — when your browser shows a connection error after\n"
716
+ " authorizing, copy the full URL from the address bar and paste\n"
717
+ " it at the prompt below. The pasted ``code=...&state=...`` is\n"
718
+ " enough to complete the flow.\n"
719
+ "\n"
720
+ " 2. Or forward the port first in a separate terminal:\n"
721
+ " ssh -N -L {port}:127.0.0.1:{port} <user>@<this-host>\n"
722
+ " then open the URL above and let it redirect normally.\n"
723
+ "\n"
724
+ " See: https://hermes-agent.nousresearch.com/docs/guides/oauth-over-ssh\n")
725
+
726
+
727
+ def _announce_authorization_url(authorization_url: str, port: int, redirect_uri: str | None) -> None:
728
+ """Print the URL (always, as the fallback) and open the browser when possible."""
729
+ print(f"\n MCP OAuth: authorization required.\n Open this URL in your browser:\n\n {authorization_url}\n", file=sys.stderr)
730
+ if os.getenv("SSH_CLIENT") or os.getenv("SSH_TTY"):
731
+ if redirect_uri:
732
+ print(_SSH_HINT_PROXY.format(redirect_uri=redirect_uri), file=sys.stderr)
733
+ elif port:
734
+ print(_SSH_HINT_LOOPBACK.format(port=port), file=sys.stderr)
735
+ if not _can_open_browser():
736
+ note = "Headless environment detected — open the URL manually."
737
+ else:
738
+ opened = False
739
+ with contextlib.suppress(Exception):
740
+ opened = webbrowser.open(authorization_url)
741
+ note = "Browser opened automatically." if opened else "Could not open browser — please open the URL manually."
742
+ print(f" ({note})\n", file=sys.stderr)
743
+
744
+
745
+ def _make_redirect_handler(port: int, redirect_uri: str | None = None):
746
+ """Redirect handler closing over this flow's port (a closure, not ``_oauth_port``, keeps concurrent
747
+ flows isolated). ``redirect_uri`` is a configured proxy callback (None for loopback) and only tailors the hint.
748
+
749
+ Using a closure instead of reading the module-level ``_oauth_port`` avoids cross-server state pollution
750
+ when multiple MCP servers run OAuth concurrently (fixes #44588).
751
+ """
752
+ async def _redirect_handler(authorization_url: str) -> None:
753
+ dashboard_flow = get_dashboard_oauth_flow()
754
+ if dashboard_flow is not None:
755
+ await dashboard_flow.publish_authorization_url(authorization_url)
756
+ return
757
+ # Fail fast when non-interactive: a cached-but-unusable token makes the SDK fall through to the
758
+ # authorization-code flow past the token-file guard, and the waiter would block for the full timeout.
759
+ # Fail fast at the authorization boundary in non-interactive contexts (systemd gateway, cron,
760
+ # background MCP discovery). Without this check we would print a URL and launch a browser flow no
761
+ # operator can complete, then block in _wait_for_callback for the full timeout. Raise before
762
+ # launching so gateway adapters start promptly and the caller can skip this server with an
763
+ # actionable warning. This intentionally re-checks interactivity here rather than trusting the
764
+ # token-file existence guard alone. See #57836.
765
+ _raise_if_non_interactive(
766
+ "MCP OAuth requires browser authorization but no interactive session is available (non-interactive/background context)."
767
+ )
768
+ _announce_authorization_url(authorization_url, port, redirect_uri)
769
+
770
+ return _redirect_handler
771
+
772
+
773
+ def _start_callback_server(port: int, handler_cls: type) -> HTTPServer:
774
+ """Bind the callback listener on *port*, adopting a parked reserved socket (closes the select→bind
775
+ TOCTOU window). ``allow_reuse_address`` is set BEFORE binding (a no-op afterwards) so a lingering
776
+ TIME_WAIT socket from a previous flow cannot block the next."""
777
+ try:
778
+ server = HTTPServer(("127.0.0.1", port), handler_cls, bind_and_activate=False)
779
+ reserved = _reserved_sockets.pop(port, None)
780
+ if reserved is not None:
781
+ server.socket.close()
782
+ server.socket, server.server_address = reserved, reserved.getsockname()
783
+ else:
784
+ server.allow_reuse_address = True
785
+ server.server_bind()
786
+ server.server_activate()
787
+ except OSError as exc: # genuinely in use (concurrent flow / leftover listener / colliding redirect_port): say so, not "timed out"
788
+ raise OAuthNonInteractiveError(
789
+ f"OAuth callback port {port} is already in use ({exc}). Close any other in-progress login, "
790
+ "or set a free `oauth.redirect_port` in the server config, then retry."
791
+ ) from exc
792
+ return server
793
+
794
+
795
+ def _callback_outcome(result: dict, cimd_url: str | None):
796
+ """Turn a filled/empty result dict into the SDK's callback value, or raise."""
797
+ if result["error"] == _USER_SKIPPED_SENTINEL:
798
+ raise OAuthNonInteractiveError("user_skipped")
799
+ if result["error"]:
800
+ raise RuntimeError(f"OAuth authorization failed: {result['error']}")
801
+ if result["auth_code"] is None:
802
+ hint = (
803
+ " If the browser showed an invalid-client error instead of an approval prompt, the authorization "
804
+ f"server rejected Hermes' Client ID Metadata Document ({cimd_url}); set ``cimd: false`` under that "
805
+ "server's ``oauth:`` block in config.yaml to authorize via dynamic client registration instead."
806
+ ) if cimd_url else ""
807
+ raise OAuthNonInteractiveError(
808
+ "OAuth callback timed out — no authorization code received. Ensure you completed the browser authorization flow." + hint
809
+ )
810
+ return _authorization_code_result(result["auth_code"], result["state"], result.get("iss"))
811
+
812
+
813
+ def _make_callback_waiter(port: int, cimd_url: str | None = None, timeout: float = 300.0):
814
+ """Callback waiter bound to one flow's port. ``timeout`` is where ``oauth.timeout`` applies (mcp 2.0
815
+ dropped the provider's own). ``cimd_url`` only tailors the timeout message: a server refusing the
816
+ document aborts at the authorization endpoint, so no redirect arrives and a bare "timed out" would
817
+ hide the cause. Raises ``OAuthNonInteractiveError`` on timeout or when non-interactive.
818
+
819
+ Closing over the port (instead of reading the module-level ``_oauth_port``) keeps concurrent OAuth flows
820
+ isolated: flow A's waiter listens on flow A's port even when flow B's ``_configure_callback_port``
821
+ overwrites the legacy global afterwards (#34260, the callback-side sibling of the #44588
822
+ redirect-handler fix).
823
+ """
824
+ async def _wait():
825
+ dashboard_flow = get_dashboard_oauth_flow()
826
+ if dashboard_flow is not None:
827
+ # Dashboard flow speaks the legacy tuple; normalize to one shape.
828
+ return _authorization_code_result(*await dashboard_flow.wait_for_callback())
829
+ # The SDK entered the authorization-code flow, so any cached token is unusable. Reject BEFORE
830
+ # binding: binding would block for the full timeout and collide with the TIME_WAIT port on retry.
831
+ # Reject before binding the callback listener in non-interactive contexts. Reaching here means the
832
+ # SDK entered the authorization-code flow (a valid or refreshable token would never call the
833
+ # callback handler), so a cached token file is present but unusable. Binding the listener here would
834
+ # block for the full 300s timeout and — on the next connection retry — collide with the
835
+ # still-bound/TIME_WAIT port, surfacing as ``OSError: [Errno 98] Address already in use``. Failing
836
+ # fast keeps gateway startup independent of an unusable optional MCP server. This guard holds
837
+ # "regardless of whether a token file exists" — the point the build_oauth_auth token-file guard
838
+ # cannot cover. See #57836.
839
+ _raise_if_non_interactive(
840
+ "OAuth callback requires an interactive session but none is available (non-interactive/background "
841
+ "context); skipping browser authorization without binding a callback listener.")
842
+ handler_cls, result = _make_callback_handler()
843
+ server = _start_callback_server(port, handler_cls)
844
+ threading.Thread(target=server.handle_request, daemon=True).start()
845
+ # Paste fallback races the HTTP listener; whichever fills result first wins.
846
+ if _is_interactive():
847
+ print(
848
+ "\n Or paste the redirect URL here (or the ``?code=...&state=...`` portion) and press Enter. "
849
+ "Type ``skip`` + Enter to continue without this server:",
850
+ file=sys.stderr, flush=True)
851
+ threading.Thread(target=_paste_callback_reader, args=(result,), daemon=True).start()
852
+ elapsed = 0.0
853
+ try:
854
+ while elapsed < timeout and not _result_taken(result):
855
+ await asyncio.sleep(0.5)
856
+ elapsed += 0.5
857
+ finally:
858
+ server.server_close()
859
+ return _callback_outcome(result, cimd_url)
860
+
861
+ return _wait
862
+
863
+
864
+ # Legacy build_oauth_auth provider class, built lazily (SDK) and cached here.
865
+ HermesOAuthClientProvider: Any = None
866
+
867
+
868
+ def remove_oauth_tokens(server_name: str, *, hermes_home: str | Path | None = None) -> None:
869
+ """Delete stored OAuth tokens and client info for a server."""
870
+ HermesTokenStorage(server_name, hermes_home=hermes_home).remove()
871
+ logger.info("OAuth tokens removed for '%s'", server_name)
872
+
873
+
874
+ # CIMD (OAuth Client ID Metadata Documents): the client_id IS an HTTPS URL the server fetches for our
875
+ # name/logo/redirect URIs, replacing per-install DCR. The SDK does the protocol; Hermes only decides
876
+ # eligibility. Published from ``website/static/oauth/client-metadata.json``; the github.io origin is
877
+ # deliberate — servers MUST NOT follow redirects when fetching it, and hermes-agent.nousresearch.com/docs/* 301s here.
878
+ _CIMD_CLIENT_METADATA_URL = "https://nousresearch.github.io/hermes-agent/docs/oauth/client-metadata.json"
879
+ # Loopback ports/hosts declared in that document (exact match, so no ephemeral port under CIMD);
880
+ # below Linux's 32768 ephemeral floor. tests/tools/test_mcp_cimd.py keeps them in sync.
881
+ _CIMD_PORTS = (27890, 27891, 27892, 27893, 27894)
882
+ _CIMD_REDIRECT_HOSTS = frozenset({"127.0.0.1", "localhost"})
883
+
884
+
885
+ def _is_valid_cimd_url(url: str) -> bool:
886
+ """True when *url* is usable as a CIMD client_id on the installed SDK (ImportError = SDK predates
887
+ CIMD → DCR only). The SDK checks only https + non-root path; userinfo, fragments and dot segments
888
+ are rejected here because they fail mid-browser-flow as an opaque invalid-client page."""
889
+ try:
890
+ from mcp.client.auth.utils import is_valid_client_metadata_url
891
+ if not is_valid_client_metadata_url(url):
892
+ return False
893
+ parsed = urlparse(url)
894
+ has_userinfo = bool(parsed.username or parsed.password) # netloc parse can raise
895
+ except (ImportError, ValueError):
896
+ return False
897
+ return not (has_userinfo or parsed.fragment or any(seg in {".", ".."} for seg in parsed.path.split("/")))
898
+
899
+
900
+ # Pinned ports this process committed to (never released: a provider keeps its port for the process
901
+ # lifetime), including ports restored from a cached registration.
902
+ # Includes a port restored from a cached client registration, so a sibling server is never handed a port
903
+ # another one is already registered on (#34260).
904
+ _assigned_cimd_ports: "list[int]" = []
905
+
906
+
907
+ def _pick_cimd_port() -> int | None:
908
+ """Reserve a pinned CIMD callback port, or None when none is usable. Holding the bound socket makes
909
+ contention cooperative: a sibling finds the bind refused and moves down the range. Once every pinned
910
+ port belongs to this process the range wraps rather than falling back to DCR — a reused port only
911
+ bites if both servers authorize at the same moment (reported by the waiter); DCR may be unsupported entirely.
912
+
913
+ Holding the bound socket until ``_wait_for_callback`` adopts it does the same job here as
914
+ ``_reserve_callback_port`` does for ephemeral ports (#22161): a fixed port is just as stealable in the
915
+ minutes between selection and the browser redirect arriving.
916
+ """
917
+ for port in _CIMD_PORTS:
918
+ if port not in _assigned_cimd_ports and _bind_reserved(port) is not None:
919
+ _assigned_cimd_ports.append(port)
920
+ return port
921
+ return _assigned_cimd_ports[0] if _assigned_cimd_ports else None
922
+
923
+
924
+ def _server_declined_cimd(storage: "HermesTokenStorage | None") -> bool:
925
+ """True when cached metadata shows this server doesn't advertise CIMD. The SDK decides CIMD vs DCR
926
+ in its 401 branch — after Hermes must fix the redirect URI — so cached metadata closes the gap;
927
+ only a genuinely unknown server pays the optimistic pin."""
928
+ try:
929
+ metadata = storage.load_oauth_metadata() if storage is not None else None
930
+ except (AttributeError, TypeError, ValueError):
931
+ return False
932
+ return metadata is not None and getattr(metadata, "client_id_metadata_document_supported", None) is not True
933
+
934
+
935
+ def _maybe_use_cimd(cfg: dict, storage: "HermesTokenStorage | None" = None) -> "tuple[str, int] | None":
936
+ """``(client_id URL, pinned callback port)``, or None to use DCR. Each ineligibility case means the
937
+ redirect URI is not one the document declares, the client identity is already settled, or the
938
+ server is known not to want a document — a metadata URL would be rejected."""
939
+ url = cfg.get("client_metadata_url") or _CIMD_CLIENT_METADATA_URL
940
+ ineligible = (
941
+ cfg.get("cimd") is False
942
+ or not _is_valid_cimd_url(url)
943
+ # pinned client = explicit choice; a secret = confidential client, which the document forbids
944
+ or cfg.get("client_id") or cfg.get("client_secret")
945
+ # the document supplies name + auth method; setting either asks for an identity CIMD can't present
946
+ or cfg.get("client_name") or (cfg.get("token_endpoint_auth_method") or "none") != "none"
947
+ # dashboard/desktop flows redirect to a deployment-specific URL no static document declares
948
+ or get_dashboard_oauth_flow() is not None
949
+ or cfg.get("redirect_uri") or cfg.get("redirect_port")
950
+ or (cfg.get("redirect_host") or "127.0.0.1") not in _CIMD_REDIRECT_HOSTS
951
+ # an existing registration is bound to its redirect URI; swapping client_id would drop tokens
952
+ or _cached_client_info(storage) is not None
953
+ or (storage is not None and storage.cimd_rejected())
954
+ or _server_declined_cimd(storage))
955
+ port = None if ineligible else _pick_cimd_port()
956
+ return None if port is None else (url, port)
957
+
958
+
959
+ def cimd_provider_kwargs(cfg: dict) -> dict[str, Any]:
960
+ """``client_metadata_url=`` kwargs for ``OAuthClientProvider`` when CIMD applies; omitted entirely
961
+ on a DCR flow because an SDK too old for CIMD rejects the keyword outright."""
962
+ url = cfg.get("_cimd_url")
963
+ return {"client_metadata_url": url} if url else {}
964
+
965
+
966
+ def token_request_user_agent(cfg: dict) -> str | None:
967
+ """Configured ``oauth.user_agent`` for token-endpoint requests (exchange + refresh only, never MCP
968
+ traffic or discovery), or None; a null/empty YAML value never sends a blank header. No other
969
+ headers are configurable (secrets would land in config.yaml)."""
970
+ ua = cfg.get("user_agent")
971
+ return ua.strip() if isinstance(ua, str) and ua.strip() else None
972
+
973
+
974
+ def _configure_callback_port(cfg: dict, storage: "HermesTokenStorage | None" = None) -> int:
975
+ """Resolve the callback port into ``cfg['_resolved_port']`` (0 = non-loopback URI). Precedence:
976
+ dashboard flow / cached https redirect URI → CIMD pinned port (sets ``cfg['_cimd_url']``) →
977
+ ``oauth.redirect_port`` → cached registration port → fresh ephemeral port (the only parked one).
978
+ Also sets the legacy ``_oauth_port``.
979
+
980
+ NOTE: also sets the legacy module-level ``_oauth_port`` so existing calls to ``_wait_for_callback`` keep
981
+ working. The legacy global is the root cause of issue #5344 (port collision on concurrent OAuth flows);
982
+ replacing it with a ContextVar is out of scope for this consolidation PR.
983
+ """
984
+ global _oauth_port
985
+ dashboard_flow = get_dashboard_oauth_flow()
986
+ if dashboard_flow is not None:
987
+ cfg["_resolved_port"] = 0
988
+ cfg["redirect_uri"] = cfg.get("redirect_uri") or dashboard_flow.redirect_uri
989
+ return 0
990
+ cached_uri, cached_port = _cached_redirect(storage)
991
+ if cached_uri and not cfg.get("redirect_uri"):
992
+ cfg["redirect_uri"] = cached_uri
993
+ cfg["_resolved_port"] = 0
994
+ return 0
995
+ cimd = _maybe_use_cimd(cfg, storage)
996
+ if cimd is not None:
997
+ cfg["_cimd_url"], port = cimd
998
+ else:
999
+ port = int(cfg.get("redirect_port", 0)) or cached_port or _reserve_callback_port()
1000
+ # A cached port may be a pinned CIMD port from an earlier login; claim it from siblings.
1001
+ if port in _CIMD_PORTS and port not in _assigned_cimd_ports:
1002
+ _assigned_cimd_ports.append(port)
1003
+ # Precedence: explicit config port → cached client-registration port → fresh ephemeral port. The cached
1004
+ # port keeps re-auth consistent with the redirect URI pinned at dynamic client registration (providers
1005
+ # reject a mismatched URI). Only a truly fresh ephemeral pick goes through _reserve_callback_port(),
1006
+ # which keeps the socket bound until _wait_for_callback adopts it — closing the select→bind TOCTOU race
1007
+ # (#22161). Explicit and cached ports are fixed, known values and bind via the reuse_address path
1008
+ # instead.
1009
+ cfg["_resolved_port"] = port
1010
+ _oauth_port = port
1011
+ return port
1012
+
1013
+
1014
+ def _resolve_redirect_uri(cfg: dict, port: int) -> str:
1015
+ """Configured ``redirect_uri`` (proxy) or ``http://<redirect_host>:<port>/callback``; the single
1016
+ derivation so client metadata and pre-registered info stay identical. ``redirect_host`` only changes
1017
+ the hostname (some WAFs reject a literal ``127.0.0.1``); the listener still binds ``127.0.0.1``."""
1018
+ return cfg.get("redirect_uri") or f"http://{cfg.get('redirect_host') or '127.0.0.1'}:{port}/callback"
1019
+
1020
+
1021
+ # Figma's remote MCP allowlists DCR by client_name ("Claude Code"/"Codex" register, others 403);
1022
+ # register under an allowlisted name so the flow can start. oauth.client_name overrides.
1023
+ _FIGMA_DCR_CLIENT_NAME = "Claude Code"
1024
+ _FIGMA_DEFAULT_SCOPE = "mcp:connect"
1025
+
1026
+
1027
+ def _is_figma_remote_mcp(server_name: str | None = None, server_url: str | None = None) -> bool:
1028
+ """True when this MCP server is Figma's hosted remote endpoint."""
1029
+ from utils import base_url_host_matches, base_url_hostname
1030
+ url = (server_url or "").lower()
1031
+ if base_url_host_matches(url, "mcp.figma.com") or (base_url_host_matches(url, "figma.com") and "/mcp" in url):
1032
+ return True
1033
+ # Name-only match only when the URL isn't some other host called figma-*.
1034
+ return "figma" in (server_name or "").lower() and (not url or "figma" in base_url_hostname(url))
1035
+
1036
+
1037
+ def apply_oauth_provider_defaults(cfg: dict, *, server_name: str = "", server_url: str | None = None) -> dict:
1038
+ """Mutate *cfg* with provider-specific OAuth workarounds (before building client metadata /
1039
+ pre-registering); returns *cfg*. Only fills keys the user left unset — explicit values win."""
1040
+ if _is_figma_remote_mcp(server_name, server_url):
1041
+ if not cfg.get("client_name"):
1042
+ cfg["client_name"] = _FIGMA_DCR_CLIENT_NAME
1043
+ logger.info(
1044
+ "MCP OAuth '%s': Figma DCR allowlist — registering as client_name=%r (override via oauth.client_name)",
1045
+ server_name or server_url, _FIGMA_DCR_CLIENT_NAME)
1046
+ if not cfg.get("scope"):
1047
+ cfg["scope"] = _FIGMA_DEFAULT_SCOPE
1048
+ # Figma advertises auth_method=none yet demands the returned client_secret at the token
1049
+ # endpoint; request a confidential registration so the SDK posts it.
1050
+ cfg["token_endpoint_auth_method"] = cfg.get("token_endpoint_auth_method") or "client_secret_post"
1051
+ return cfg
1052
+
1053
+
1054
+ def _build_client_metadata(cfg: dict) -> "OAuthClientMetadata":
1055
+ """Build OAuthClientMetadata; requires ``_configure_callback_port`` first."""
1056
+ port = cfg.get("_resolved_port")
1057
+ if port is None:
1058
+ raise ValueError("_configure_callback_port() must be called before _build_client_metadata()")
1059
+ metadata_cls = _sdk_class("OAuthClientMetadata")
1060
+ # Public client by default; confidential only with a known secret or a provider (Figma) needing confidential-style token posts.
1061
+ auth_method = cfg.get("token_endpoint_auth_method") or ("client_secret_post" if cfg.get("client_secret") else "none")
1062
+ metadata_kwargs: dict[str, Any] = {
1063
+ "client_name": cfg.get("client_name", "Hermes Agent"),
1064
+ "redirect_uris": [AnyUrl(_resolve_redirect_uri(cfg, port))],
1065
+ "grant_types": ["authorization_code", "refresh_token"],
1066
+ "response_types": ["code"],
1067
+ "token_endpoint_auth_method": auth_method,
1068
+ # SEP-837: OIDC-strict servers need application_type to accept loopback redirects; "native"
1069
+ # for a CLI/desktop app, overridable for a hosted https dashboard.
1070
+ "application_type": cfg.get("application_type", "native")}
1071
+ if cfg.get("scope"):
1072
+ metadata_kwargs["scope"] = cfg["scope"]
1073
+ try:
1074
+ return metadata_cls.model_validate(metadata_kwargs)
1075
+ except Exception: # mcp 1.x metadata models predate SEP-837 and reject the unknown field
1076
+ metadata_kwargs.pop("application_type", None)
1077
+ return metadata_cls.model_validate(metadata_kwargs)
1078
+
1079
+
1080
+ def _invalidate_tokens_on_client_change(
1081
+ storage: "HermesTokenStorage", new_client_id: str, new_client_secret: str | None) -> None:
1082
+ """Drop cached tokens when the configured client identity changes: tokens minted under the old
1083
+ ``client_id`` fail refresh with ``invalid_client``, and pre-registered clients are exempt from
1084
+ auto-poison, so stale tokens would wedge every request until a manual wipe. Compares on-disk
1085
+ ``client.json`` BEFORE it is overwritten; a matching identity is a no-op.
1086
+
1087
+ Matching identity is a no-op so live sessions and valid tokens are preserved. Port of
1088
+ cline/cline#12983's "invalidate tokens when OAuth client changes" invariant.
1089
+ """
1090
+ existing = _read_json(storage._client_info_path())
1091
+ old_client_id = existing.get("client_id") if isinstance(existing, dict) else None
1092
+ if not old_client_id or (old_client_id == new_client_id and (existing.get("client_secret") or None) == (new_client_secret or None)):
1093
+ return
1094
+ removed = False
1095
+ for path in (storage._tokens_path(), storage._meta_path()):
1096
+ if not path.exists():
1097
+ continue
1098
+ try:
1099
+ path.unlink()
1100
+ removed = True
1101
+ except OSError as exc: # non-fatal — stale tokens fail later anyway
1102
+ logger.warning("MCP OAuth '%s': could not remove stale %s after client change: %s", storage._server_name, path.name, exc)
1103
+ if removed:
1104
+ logger.warning(
1105
+ "MCP OAuth '%s': configured OAuth client changed (client_id %r -> %r); discarded tokens minted under "
1106
+ "the previous client. Re-authorize with: hermes mcp login %s",
1107
+ storage._server_name, old_client_id, new_client_id, storage._server_name)
1108
+
1109
+
1110
+ def _maybe_preregister_client(storage: "HermesTokenStorage", cfg: dict, client_metadata: "OAuthClientMetadata") -> None:
1111
+ """If cfg has a pre-registered client_id, persist it to storage."""
1112
+ client_id = cfg.get("client_id")
1113
+ if not client_id:
1114
+ return
1115
+ info_cls = _sdk_class("OAuthClientInformationFull")
1116
+ _invalidate_tokens_on_client_change(storage, client_id, cfg.get("client_secret"))
1117
+ info_dict: dict[str, Any] = {
1118
+ "client_id": client_id,
1119
+ "redirect_uris": [_resolve_redirect_uri(cfg, cfg["_resolved_port"])],
1120
+ "grant_types": client_metadata.grant_types,
1121
+ "response_types": client_metadata.response_types,
1122
+ "token_endpoint_auth_method": client_metadata.token_endpoint_auth_method,
1123
+ **{key: cfg[key] for key in ("client_secret", "client_name", "scope") if cfg.get(key)}}
1124
+ _write_json(storage._client_info_path(), _model_json(info_cls.model_validate(info_dict)))
1125
+ logger.debug("Pre-registered client_id=%s for '%s'", client_id, storage._server_name)
1126
+
1127
+
1128
+ def humanize_oauth_registration_error(
1129
+ server_name: str, exc: BaseException | str, *, server_url: str | None = None) -> str | None:
1130
+ """Turn a DCR 403/Forbidden into a useful next step; None for anything else so the caller keeps the
1131
+ original text. Figma gates DCR on exact ``client_name`` (auto-set to ``Claude Code``), so this fires
1132
+ when the user overrode it or an older Hermes is running."""
1133
+ msg = str(exc)
1134
+ lowered = msg.lower()
1135
+ looks_like_registration = ("403" in msg or "forbidden" in lowered) and (
1136
+ any(k in lowered for k in ("regist", "dcr", "dynamic client"))
1137
+ or lowered.strip() in {"forbidden", "403 forbidden", "http 403: forbidden"}
1138
+ or ("403" in msg and "forbidden" in lowered))
1139
+ if not looks_like_registration:
1140
+ return None
1141
+ if _is_figma_remote_mcp(server_name, server_url):
1142
+ return (
1143
+ f"'{server_name}' is Figma's remote MCP — DCR is allowlisted by exact client_name "
1144
+ f"(\"{_FIGMA_DCR_CLIENT_NAME}\" and \"Codex\" work; most other names 403). Hermes defaults to "
1145
+ f"client_name: {_FIGMA_DCR_CLIENT_NAME!r} automatically. If you set oauth.client_name yourself, "
1146
+ f"change it to one of those, or clear it and re-run:\n hermes mcp login {server_name}")
1147
+ return (
1148
+ f"'{server_name}' only allows pre-approved OAuth clients — it rejected client registration (403), so no "
1149
+ "browser flow can start. Options: set oauth.client_name to a name the provider allowlists, add a "
1150
+ "pre-registered client (oauth: {client_id: ..., client_secret: ...}), or use the provider's stdio / "
1151
+ "API-key / local server instead.")
1152
+
1153
+
1154
+ def build_oauth_auth(server_name: str, server_url: str, oauth_config: dict | None = None) -> "OAuthClientProvider | None":
1155
+ """``httpx.Auth`` OAuth handler for an MCP server; None if the SDK lacks OAuth. Legacy API — new code
1156
+ uses :func:`tools.mcp_oauth_manager.get_manager` so state is shared across config-time, runtime and reconnect paths."""
1157
+ global HermesOAuthClientProvider
1158
+ if not _OAUTH_AVAILABLE or _sdk_class("OAuthClientProvider") is None:
1159
+ logger.warning("MCP OAuth requested for '%s' but SDK auth types are not available. Install with: pip install 'mcp>=1.26.0'", server_name)
1160
+ return None
1161
+ from tools.mcp_oauth_provider import build_provider_kwargs, prepare_oauth_config
1162
+
1163
+ cfg, storage = prepare_oauth_config(server_name, server_url, oauth_config)
1164
+ if not _is_interactive() and not storage.has_cached_tokens():
1165
+ raise OAuthNonInteractiveError(
1166
+ f"MCP OAuth for '{server_name}': non-interactive environment and no cached tokens found. The OAuth flow "
1167
+ f"requires browser authorization. Run `hermes mcp login {server_name}` interactively first to complete "
1168
+ "initial authorization, then cached tokens will be reused.")
1169
+ kwargs = build_provider_kwargs(cfg, storage, ssh_proxy_hint=True)
1170
+ if HermesOAuthClientProvider is None:
1171
+ from tools.mcp_oauth_provider import HermesProviderMixin
1172
+
1173
+ HermesOAuthClientProvider = type("HermesOAuthClientProvider", (HermesProviderMixin, _sdk_class("OAuthClientProvider")), {
1174
+ "__doc__": "SDK provider plus Hermes' token-endpoint fixes (see ``HermesProviderMixin``).",
1175
+ "__module__": __name__, "_hermes_logger": logger})
1176
+ return HermesOAuthClientProvider(server_url=server_url, **kwargs)
1177
+
1178
+
1179
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
1180
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
1181
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
1182
+ # The whole block is removed by reverting the commit that added it.
1183
+ from contextlib import contextmanager # noqa: F401,E402
1184
+
1185
+ OAuthClientInformationFull: Any = None
1186
+
1187
+ OAuthClientMetadata: Any = None
1188
+
1189
+ OAuthClientProvider: Any = None
1190
+
1191
+ OAuthMetadata: Any = None
1192
+
1193
+ OAuthToken: Any = None
1194
+ # ---- END PLUGIN-COMPAT ----
tools/mcp_oauth_device.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explicit RFC 8628 MCP login, sharing SDK discovery, client auth and token storage.
2
+
3
+ The SDK still owns runtime requests and refresh. Device authorization is only
4
+ started by `hermes mcp login/reauth`, never a background reconnect.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import math
10
+ import sys
11
+ import time
12
+
13
+ from mcp.shared.auth import OAuthMetadata
14
+ from pydantic import AnyHttpUrl
15
+
16
+ DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
17
+
18
+
19
+ class DeviceOAuthMetadata(OAuthMetadata):
20
+ # RFC 8414 makes authorization_endpoint optional for grants not using it.
21
+ authorization_endpoint: AnyHttpUrl | None = None
22
+ device_authorization_endpoint: AnyHttpUrl
23
+
24
+
25
+ async def _discover(client, provider):
26
+ from mcp.client.auth.utils import (
27
+ build_oauth_authorization_server_metadata_discovery_urls,
28
+ build_protected_resource_metadata_discovery_urls,
29
+ extract_resource_metadata_from_www_auth,
30
+ handle_protected_resource_response,
31
+ validate_metadata_issuer,
32
+ )
33
+ context = provider.context
34
+ response = await client.get(context.server_url)
35
+ challenge = extract_resource_metadata_from_www_auth(response)
36
+ for url in build_protected_resource_metadata_discovery_urls(challenge, context.server_url):
37
+ response = await client.get(url)
38
+ prm = await handle_protected_resource_response(response)
39
+ if prm:
40
+ await provider._validate_resource_match(prm)
41
+ context.protected_resource_metadata = prm
42
+ context.auth_server_url = str(prm.authorization_servers[0])
43
+ break
44
+ for url in build_oauth_authorization_server_metadata_discovery_urls(context.auth_server_url, context.server_url):
45
+ response = await client.get(url)
46
+ if response.status_code == 404:
47
+ continue
48
+ data = _payload(response, "OAuth metadata")
49
+ if not data.get("device_authorization_endpoint"):
50
+ raise RuntimeError("Server does not advertise device authorization; use --flow browser if supported")
51
+ metadata = DeviceOAuthMetadata.model_validate(data)
52
+ if context.auth_server_url:
53
+ validate_metadata_issuer(metadata, context.auth_server_url)
54
+ grants = metadata.grant_types_supported
55
+ if grants is not None and DEVICE_GRANT not in grants:
56
+ raise RuntimeError("Server does not advertise the device_code grant")
57
+ context.oauth_metadata = metadata
58
+ return
59
+ raise RuntimeError("No OAuth authorization server metadata found")
60
+
61
+
62
+ def _payload(response, label):
63
+ try:
64
+ data = response.json()
65
+ except ValueError:
66
+ raise RuntimeError(f"{label}: invalid JSON response") from None
67
+ if not isinstance(data, dict):
68
+ raise RuntimeError(f"{label}: expected a JSON object")
69
+ if not 200 <= response.status_code < 300:
70
+ # Descriptions and arbitrary error values may contain credentials.
71
+ raise RuntimeError(f"{label} failed (HTTP {response.status_code})")
72
+ return data
73
+
74
+
75
+ async def _register(client, provider, cfg):
76
+ from mcp.shared.auth import OAuthClientInformationFull
77
+ from mcp.client.auth.oauth2 import OAuthRegistrationError, check_registration_usable
78
+
79
+ context = provider.context
80
+ metadata = context.client_metadata.model_dump(mode="json", exclude_none=True)
81
+ metadata.update(grant_types=[DEVICE_GRANT, "refresh_token"], response_types=[])
82
+ if cfg.get("client_id"):
83
+ data = {**metadata, "client_id": cfg["client_id"]}
84
+ if cfg.get("client_secret"):
85
+ data["client_secret"] = cfg["client_secret"]
86
+ else:
87
+ endpoint = context.oauth_metadata.registration_endpoint
88
+ if not endpoint:
89
+ raise RuntimeError("Server has no registration endpoint; configure oauth.client_id (and client_secret if required)")
90
+ response = await client.post(str(endpoint), json=metadata)
91
+ data = _payload(response, "Client registration")
92
+ data["issuer"] = str(context.oauth_metadata.issuer)
93
+ context.client_info = OAuthClientInformationFull.model_validate(data)
94
+ provider._coerce_client_secret_post()
95
+ try:
96
+ check_registration_usable(context.client_info)
97
+ except OAuthRegistrationError:
98
+ raise RuntimeError("Device OAuth client has unsupported or incomplete token endpoint authentication") from None
99
+
100
+
101
+ def _positive_seconds(value, label):
102
+ value = float(value)
103
+ if not math.isfinite(value) or value <= 0:
104
+ raise RuntimeError(f"Device authorization has invalid {label}")
105
+ return value
106
+
107
+
108
+ async def _authorize(client, provider, cfg):
109
+ from tools.mcp_tool import sdk_httpx
110
+
111
+ context = provider.context
112
+ resource = context.get_resource_url()
113
+ data = {"client_id": context.client_info.client_id, "resource": resource}
114
+ if context.client_metadata.scope:
115
+ data["scope"] = context.client_metadata.scope
116
+ data, headers = context.prepare_token_auth(data, {})
117
+ response = await client.post(str(context.oauth_metadata.device_authorization_endpoint), data=data, headers=headers)
118
+ authorization = _payload(response, "Device authorization")
119
+ for key in ("device_code", "user_code", "verification_uri"):
120
+ if not isinstance(authorization.get(key), str) or not authorization[key]:
121
+ raise RuntimeError(f"Device authorization is missing {key}")
122
+ verification = AnyHttpUrl(authorization["verification_uri"])
123
+ interval = _positive_seconds(authorization.get("interval", 5), "interval")
124
+ deadline = time.monotonic() + min(_positive_seconds(authorization["expires_in"], "expires_in"),
125
+ _positive_seconds(cfg.get("timeout", 300), "timeout"))
126
+ print(f"\n MCP OAuth: open {verification} on any device.\n Code: {authorization['user_code']}\n"
127
+ " Waiting for approval...\n", file=sys.stderr, flush=True)
128
+ token_data = {"client_id": context.client_info.client_id, "device_code": authorization["device_code"],
129
+ "grant_type": DEVICE_GRANT, "resource": resource}
130
+ token_data, headers = context.prepare_token_auth(token_data, {})
131
+ httpx = sdk_httpx()
132
+ while True:
133
+ remaining = deadline - time.monotonic()
134
+ if remaining <= interval:
135
+ raise RuntimeError("Device authorization expired before approval; run login again")
136
+ await asyncio.sleep(interval)
137
+ request = provider._prepare_token_request(httpx.Request("POST", str(context.oauth_metadata.token_endpoint),
138
+ data=token_data, headers=headers))
139
+ try:
140
+ response = await asyncio.wait_for(client.send(request), timeout=deadline - time.monotonic())
141
+ except (TimeoutError, httpx.TimeoutException):
142
+ # RFC 8628 requires reducing polling frequency after connection timeouts.
143
+ interval *= 2
144
+ continue
145
+ if 200 <= response.status_code < 300:
146
+ from mcp.shared.auth import OAuthToken
147
+ tokens = OAuthToken.model_validate(_payload(response, "Device token"))
148
+ if not tokens.access_token:
149
+ raise RuntimeError("Device token response has no access token")
150
+ if tokens.scope is None:
151
+ tokens.scope = context.client_metadata.scope
152
+ return tokens
153
+ try:
154
+ error = response.json().get("error")
155
+ except (ValueError, AttributeError):
156
+ error = None
157
+ if error == "authorization_pending":
158
+ continue
159
+ if error == "slow_down":
160
+ interval += 5
161
+ continue
162
+ safe_error = error if error in {"access_denied", "expired_token"} else f"HTTP {response.status_code}"
163
+ raise RuntimeError(f"Device authorization failed: {safe_error}")
164
+
165
+
166
+ async def login_device(name, server_url, oauth_config):
167
+ """Authorize then commit state in the active profile; failed grants preserve old state."""
168
+ from tools.mcp_oauth import _build_client_metadata
169
+ from tools.mcp_oauth_manager import HermesMCPOAuthProvider, get_manager
170
+ from tools.mcp_oauth_provider import prepare_oauth_config
171
+ from tools.mcp_tool import sdk_httpx
172
+
173
+ cfg, storage = prepare_oauth_config(name, server_url, oauth_config)
174
+ # Device flow never binds a callback socket or uses the hosted browser CIMD.
175
+ cfg["_resolved_port"] = cfg.get("redirect_port", 8420)
176
+ provider = HermesMCPOAuthProvider(server_url=server_url, server_name=name, storage=storage,
177
+ client_metadata=_build_client_metadata(cfg),
178
+ token_user_agent=cfg.get("user_agent"))
179
+ httpx = sdk_httpx()
180
+ try:
181
+ async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client:
182
+ await _discover(client, provider)
183
+ await _register(client, provider, cfg)
184
+ tokens = await _authorize(client, provider, cfg)
185
+ except (ValueError, TypeError, KeyError):
186
+ raise RuntimeError("Device OAuth response has invalid fields") from None
187
+ except httpx.HTTPError:
188
+ raise RuntimeError("Device OAuth network request failed") from None
189
+ # Validate the entire grant before touching disk; reuse the existing scoped store.
190
+ previous = storage.snapshot()
191
+ try:
192
+ await storage.set_client_info(provider.context.client_info)
193
+ storage.save_oauth_metadata(provider.context.oauth_metadata)
194
+ await storage.set_tokens(tokens)
195
+ except OSError:
196
+ storage.restore(previous)
197
+ raise
198
+ get_manager().evict(name)
tools/mcp_oauth_provider.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared ``OAuthClientProvider`` customizations for Hermes MCP OAuth.
2
+
3
+ Two code paths build an SDK provider — ``tools.mcp_oauth.build_oauth_auth`` (legacy public
4
+ API) and ``tools.mcp_oauth_manager.MCPOAuthManager`` — and both need the same real-world
5
+ fixes and config → constructor-kwargs plumbing. This module holds that core once; the origin
6
+ modules keep their own subclass (logger name, disk-watch hooks) on top of it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from typing import TYPE_CHECKING, Any
13
+
14
+ if TYPE_CHECKING:
15
+ from tools.mcp_oauth import HermesTokenStorage
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+
20
+ class _RefreshCompletedByPeer(Exception):
21
+ """Restart the SDK auth flow: a peer rotated the grant we were about to present."""
22
+
23
+ class HermesProviderMixin:
24
+ """Token-endpoint fixes layered over the SDK's ``OAuthClientProvider`` (must precede it in
25
+ the MRO; subclasses set ``_hermes_logger`` to keep their own logger name).
26
+
27
+ - Supabase-style dynamic registration returns a ``client_secret`` but omits
28
+ ``token_endpoint_auth_method``; the SDK then treats the client as public and the token
29
+ endpoint rejects the exchange (looping the browser page) — coerce ``client_secret_post``.
30
+ - ``token_user_agent`` (``oauth.user_agent``) is stamped onto token-endpoint requests only
31
+ (some authorization servers/WAFs reject httpx's default).
32
+ - Any 2xx token/refresh response is accepted; token bodies never leak into errors/logs."""
33
+
34
+ _hermes_logger: logging.Logger = logger
35
+
36
+ def __init__(self, *args: Any, token_user_agent: str | None = None, oauth_flow: str = "browser", **kwargs: Any):
37
+ super().__init__(*args, **kwargs)
38
+ self._hermes_oauth_flow = oauth_flow
39
+ # oauth.user_agent — stamped onto token-endpoint requests only; some authorization servers/WAFs
40
+ # reject httpx's default (#75576).
41
+ self._hermes_token_user_agent = token_user_agent
42
+
43
+ async def _perform_authorization(self):
44
+ info = self.context.client_info
45
+ grants = getattr(info, "grant_types", None) or []
46
+ if (getattr(self, "_hermes_oauth_flow", "browser") == "device"
47
+ or ("urn:ietf:params:oauth:grant-type:device_code" in grants and "authorization_code" not in grants)):
48
+ from tools.mcp_oauth import OAuthNonInteractiveError
49
+ raise OAuthNonInteractiveError(
50
+ "MCP device authorization requires `hermes mcp login <server> --flow device`; "
51
+ "background reconnects cannot start a device login")
52
+ return await super()._perform_authorization()
53
+
54
+ def _prepare_token_request(self, request):
55
+ """Stamp the configured User-Agent onto a token/refresh request."""
56
+ ua = getattr(self, "_hermes_token_user_agent", None) # tests build via __new__
57
+ if ua:
58
+ request.headers["User-Agent"] = ua
59
+ return request
60
+
61
+ def _coerce_client_secret_post(self) -> None:
62
+ """Same rule as ``HermesTokenStorage._coerce_secret_auth_method``, applied to the
63
+ in-memory client info BEFORE the SDK builds a token-endpoint request from it."""
64
+ info = self.context.client_info
65
+ if not info:
66
+ return
67
+ from mcp.shared.auth import OAuthClientInformationFull
68
+ from tools.mcp_oauth import HermesTokenStorage
69
+ data = info.model_dump(mode="json", exclude_none=True)
70
+ if HermesTokenStorage._coerce_secret_auth_method(data):
71
+ self.context.client_info = OAuthClientInformationFull.model_validate(data)
72
+
73
+ async def _exchange_token_authorization_code(self, *args: Any, **kwargs: Any):
74
+ self._coerce_client_secret_post()
75
+ return self._prepare_token_request(await super()._exchange_token_authorization_code(*args, **kwargs))
76
+
77
+ # Locked descriptor while this provider owns the refresh fence; cleared by
78
+ # _hermes_release_refresh_fence. Never shared across instances.
79
+ _hermes_fence: int | None = None
80
+
81
+ async def async_auth_flow(self, request):
82
+ """Guarantee fence release even if the auth generator is abandoned.
83
+
84
+ The SDK drives the refresh as a generator: ``_refresh_token`` yields a
85
+ request and ``_handle_refresh_response`` consumes the response. If the
86
+ caller cancels in between (timeout, task cancellation, transport
87
+ teardown), GeneratorExit/CancelledError is raised at the yield and
88
+ ``_handle_refresh_response`` never runs. Without this wrapper the fence
89
+ file would stay locked for the life of the process and every later
90
+ refresh would fail closed -- trading a race for a deadlock.
91
+
92
+ When a peer already rotated the grant while we waited for the fence,
93
+ ``_refresh_token`` adopts it and raises ``_RefreshCompletedByPeer``;
94
+ the SDK flow is then restarted so it re-evaluates validity and sends
95
+ the original request with the winner's access token, never POSTing
96
+ the burned refresh token.
97
+ """
98
+ while True:
99
+ inner = super().async_auth_flow(request)
100
+ try:
101
+ sent, thrown = None, None
102
+ while True:
103
+ try:
104
+ if thrown is not None:
105
+ exc, thrown = thrown, None
106
+ out = await inner.athrow(exc)
107
+ else:
108
+ out = await inner.asend(sent)
109
+ except StopAsyncIteration:
110
+ return
111
+ except _RefreshCompletedByPeer:
112
+ break
113
+ # Full bidirectional delegation: the SDK drives this flow with
114
+ # asend(response), so `async for` would swallow the response and
115
+ # feed the inner generator None. Async generators have no
116
+ # `yield from`, hence the manual pump.
117
+ try:
118
+ sent = yield out
119
+ except GeneratorExit:
120
+ await inner.aclose()
121
+ raise
122
+ except BaseException as exc:
123
+ sent, thrown = None, exc
124
+ finally:
125
+ await self._hermes_release_refresh_fence()
126
+
127
+ async def _refresh_token(self):
128
+ """Take the refresh fence, then build the request from the token we own.
129
+
130
+ The fence is acquired BEFORE the final read of the refresh token and is
131
+ released only after _handle_refresh_response has persisted the
132
+ replacement, so one refresh generation is consumed by exactly one
133
+ process. See tools.mcp_oauth.acquire_refresh_fence for the interleaving this
134
+ closes.
135
+
136
+ Holding a lock across ``yield`` in the SDK's generator-based auth flow
137
+ is safe here because the SDK already serializes the whole flow under
138
+ ``self.context.lock``: the generator is always driven to completion (or
139
+ aborted) by one task, and async_auth_flow cannot interleave two
140
+ refreshes inside one process.
141
+ """
142
+ self._coerce_client_secret_post()
143
+ await self._hermes_acquire_refresh_fence()
144
+ try:
145
+ # Re-read under the fence: a peer may have rotated while we waited
146
+ # for it, in which case the token we were about to POST is dead.
147
+ # If disk already holds a different refresh token, the peer that held
148
+ # the fence before us won this generation; its value is the only one
149
+ # the provider will still accept, so install it even when its access
150
+ # token has already expired (the POST we build needs the new grant).
151
+ candidate = await self._hermes_rotated_candidate()
152
+ if candidate is not None:
153
+ if not self._hermes_install_disk_pair(candidate):
154
+ # Issuer binding stripped the peer's refresh token: nothing
155
+ # left to POST. Restart the flow so the SDK lands in 401 ->
156
+ # full authorization instead of raising over a dead grant.
157
+ raise _RefreshCompletedByPeer
158
+ if self._hermes_live_ttl() and self.context.is_token_valid():
159
+ # The peer's access token is live: presenting our copy of the
160
+ # refresh token would only burn a generation on a single-use
161
+ # provider. Skip the POST and let the flow restart.
162
+ raise _RefreshCompletedByPeer
163
+ return self._prepare_token_request(await super()._refresh_token())
164
+ except BaseException:
165
+ # Never hold the fence when no POST will follow.
166
+ await self._hermes_release_refresh_fence()
167
+ raise
168
+
169
+ def _hermes_live_ttl(self) -> bool:
170
+ """True when the installed token is not known to be past due.
171
+
172
+ Storage clamps a past-due token to ``expires_in == 0`` on read (see
173
+ HermesTokenStorage.get_tokens); the SDK's is_token_valid() compares
174
+ ``time.time() <= expiry`` and still reports True for that boundary,
175
+ which would make us adopt a token the server rejects immediately.
176
+ ``expires_in`` is optional in RFC 6749: None means no expiry was
177
+ issued, which the SDK treats as valid, so it counts as live here too.
178
+ """
179
+ if self.context.current_tokens is None:
180
+ return False
181
+ exp = getattr(self.context.current_tokens, "expires_in", None)
182
+ return exp is None or int(exp) > 0
183
+
184
+ async def _hermes_acquire_refresh_fence(self) -> None:
185
+ """Enter the fence, or let RefreshFenceTimeout abort this attempt.
186
+
187
+ Fails closed on purpose: a refresh we are not certain we own must not
188
+ be POSTed. A stale fence from an aborted attempt is replaced rather
189
+ than stacked, so a crashed generator cannot leak ownership.
190
+ """
191
+ from tools.mcp_oauth import acquire_refresh_fence
192
+
193
+ await self._hermes_release_refresh_fence()
194
+ storage = self.context.storage
195
+ tokens_path = getattr(storage, "_tokens_path", None)
196
+ if tokens_path is None: # pragma: no cover - non-Hermes storage
197
+ return
198
+ self._hermes_fence = await acquire_refresh_fence(tokens_path())
199
+
200
+ async def _hermes_release_refresh_fence(self) -> None:
201
+ """Release the fence if held. Idempotent and never raises."""
202
+ from tools.mcp_oauth import release_refresh_fence
203
+
204
+ fd, self._hermes_fence = self._hermes_fence, None
205
+ if fd is not None:
206
+ release_refresh_fence(fd)
207
+
208
+ async def _hermes_rotated_candidate(self):
209
+ """The on-disk pair, if a peer rotated it past the one we hold.
210
+
211
+ A candidate must carry a refresh token different from ours (same
212
+ token: disk has nothing newer) and a non-empty access token. A disk
213
+ entry with no refresh token is never adopted: its access token may
214
+ still be inside its TTL, but taking it trades an explicit reauth now
215
+ for a silent one at expiry with no way to refresh in between.
216
+ ``get_tokens`` already returns None for absent or corrupt files.
217
+ """
218
+ stored = await self.context.storage.get_tokens()
219
+ if stored is None:
220
+ return None
221
+ current = self.context.current_tokens
222
+ stored_refresh = getattr(stored, "refresh_token", None)
223
+ if not stored_refresh or not getattr(stored, "access_token", None):
224
+ return None
225
+ if stored_refresh == getattr(current, "refresh_token", None):
226
+ return None
227
+ return stored
228
+
229
+ def _hermes_install_disk_pair(self, tokens) -> bool:
230
+ """Publish a disk pair to the context and re-run issuer binding on it.
231
+
232
+ Returns False when the enforcer strips the refresh token (the pair was
233
+ minted by a different issuer): there is nothing left to refresh with,
234
+ and each caller decides what that means for its own flow.
235
+ """
236
+ self.context.current_tokens = tokens
237
+ self.context.update_token_expiry(tokens)
238
+ enforce_refresh_token_issuer(self.context)
239
+ return bool(getattr(self.context.current_tokens, "refresh_token", None))
240
+
241
+ async def _initialize(self) -> None:
242
+ """Load stored state, restore persisted server metadata when the SDK has none (so the issuer
243
+ check and any refresh see the discovered ``issuer``/``token_endpoint`` instead of SDK guesses),
244
+ then enforce refresh-token issuer binding."""
245
+ await super()._initialize()
246
+ storage = self.context.storage
247
+ from tools.mcp_oauth import HermesTokenStorage
248
+ if isinstance(storage, HermesTokenStorage) and self.context.oauth_metadata is None:
249
+ meta = storage.load_oauth_metadata()
250
+ if meta is not None:
251
+ self.context.oauth_metadata = meta
252
+ enforce_refresh_token_issuer(self.context)
253
+
254
+ async def _store_tokens(self, token_response) -> None:
255
+ self.context.current_tokens = token_response
256
+ self.context.update_token_expiry(token_response)
257
+ bind_issuer_from_context(self.context)
258
+ await self.context.storage.set_tokens(token_response)
259
+
260
+ async def _handle_token_response(self, response):
261
+ """Accept any 2xx token response; never echo the body into errors."""
262
+ from mcp.client.auth.oauth2 import OAuthTokenError
263
+ if not (200 <= response.status_code < 300):
264
+ raise OAuthTokenError(f"Token exchange failed ({response.status_code})")
265
+ from httpx import HTTPError
266
+ from mcp.client.auth.utils import handle_token_response_scopes
267
+ try:
268
+ token_response = await handle_token_response_scopes(response)
269
+ except (HTTPError, OAuthTokenError):
270
+ raise OAuthTokenError("Invalid token response") from None
271
+ await self._store_tokens(token_response)
272
+
273
+ async def _handle_refresh_response(self, response) -> bool:
274
+ """Accept any 2xx refresh response; never log the body.
275
+
276
+ Always releases the refresh fence: this is the single exit point of the
277
+ fenced section, whatever the outcome.
278
+ """
279
+ try:
280
+ return await self._hermes_handle_refresh_response(response)
281
+ finally:
282
+ await self._hermes_release_refresh_fence()
283
+
284
+ async def _hermes_handle_refresh_response(self, response) -> bool:
285
+ if not (200 <= response.status_code < 300):
286
+ self._hermes_logger.warning("Token refresh failed: %s", response.status_code)
287
+ # A writer outside the fence (interactive `hermes mcp login`, or a
288
+ # pre-fence Hermes sharing this HERMES_HOME) may have rotated the
289
+ # grant and persisted the replacement. Providers issuing single-use
290
+ # refresh tokens reject our stale copy with a 400. Re-read disk
291
+ # before destroying the session.
292
+ if await self._hermes_reload_tokens_after_refresh_failure():
293
+ self._hermes_logger.info(
294
+ "Recovered a peer-rotated refresh token instead of clearing the session"
295
+ )
296
+ return True
297
+ self.context.clear_tokens()
298
+ return False
299
+ from httpx import HTTPError
300
+ from mcp.shared.auth import OAuthToken
301
+ from pydantic import ValidationError
302
+ try:
303
+ token_response = OAuthToken.model_validate_json(await response.aread())
304
+ except (HTTPError, ValidationError):
305
+ self._hermes_logger.warning("Invalid refresh response: %s", response.status_code)
306
+ self.context.clear_tokens()
307
+ return False
308
+ # RFC 6749 §6: a refresh response may omit refresh_token (AS does not rotate) and scope
309
+ # (unchanged). The SDK's own _handle_refresh_response carries both forward; this override
310
+ # must too, or every non-rotating refresh erases the stored refresh_token and the server
311
+ # dies at the NEXT expiry with a forced browser re-auth (#62333).
312
+ prior = self.context.current_tokens
313
+ if prior is not None:
314
+ if token_response.refresh_token is None:
315
+ token_response.refresh_token = prior.refresh_token
316
+ if token_response.scope is None:
317
+ token_response.scope = prior.scope
318
+ await self._store_tokens(token_response)
319
+ return True
320
+
321
+ async def _hermes_reload_tokens_after_refresh_failure(self) -> bool:
322
+ """Re-read tokens from disk after a rejected refresh.
323
+
324
+ Returns True only when disk holds a pair that is BOTH different from
325
+ the one we just failed with AND still live. That is the signature of
326
+ a writer outside the fence (an interactive ``hermes mcp login`` or a
327
+ pre-fence Hermes) having rotated the grant between our read and our
328
+ POST -- a recoverable race, not a dead credential.
329
+
330
+ Returns False for the genuinely-expired case (nobody wrote a newer
331
+ pair), so the caller still clears state and surfaces the reauth
332
+ prompt.
333
+ """
334
+ candidate = await self._hermes_rotated_candidate()
335
+ if candidate is None:
336
+ return False
337
+ # Publish, then restore on rejection. is_token_valid() reads the
338
+ # context rather than taking a token argument, so the candidate has
339
+ # to be installed to be tested; a losing probe must leave the context
340
+ # exactly as it found it.
341
+ previous_tokens = self.context.current_tokens
342
+ if (
343
+ self._hermes_install_disk_pair(candidate)
344
+ and self._hermes_live_ttl()
345
+ and self.context.is_token_valid()
346
+ ):
347
+ return True
348
+ self.context.current_tokens = previous_tokens
349
+ self.context.update_token_expiry(previous_tokens)
350
+ return False
351
+
352
+
353
+ def _metadata_issuer(context: Any) -> str | None:
354
+ """Discovered authorization-server issuer from the SDK auth context, without trailing slash."""
355
+ meta = getattr(context, "oauth_metadata", None)
356
+ issuer = getattr(meta, "issuer", None) if meta is not None else None
357
+ return (str(issuer).rstrip("/") or None) if issuer else None
358
+
359
+
360
+ def bind_issuer_from_context(context: Any) -> None:
361
+ """Record the discovered issuer so the next ``storage.set_tokens`` (exchange or refresh) carries
362
+ it. No-op when metadata is not discovered yet or storage is not Hermes'."""
363
+ from tools.mcp_oauth import HermesTokenStorage
364
+ storage = getattr(context, "storage", None)
365
+ issuer = _metadata_issuer(context)
366
+ if isinstance(storage, HermesTokenStorage) and issuer:
367
+ storage.bind_issuer(issuer)
368
+
369
+
370
+ def enforce_refresh_token_issuer(context: Any) -> None:
371
+ """Refuse to reuse a refresh token minted by a different issuer.
372
+
373
+ The authorization server discovered for an MCP server can change (DNS takeover, protected-resource
374
+ metadata edit, server migration); sending the stored refresh token to the new issuer hands it a
375
+ long-lived credential. On mismatch the refresh token is stripped (memory + disk) while an unexpired
376
+ access token stays usable; full re-authorization happens at expiry. Token files predating the field
377
+ adopt the current issuer once rather than forcing a re-login. Runs after ``_initialize`` restored
378
+ tokens + metadata, before the SDK's ``can_refresh_token()`` decision."""
379
+ from tools.mcp_oauth import HermesTokenStorage
380
+ storage = getattr(context, "storage", None)
381
+ tokens = getattr(context, "current_tokens", None)
382
+ if not isinstance(storage, HermesTokenStorage) or tokens is None or not getattr(tokens, "refresh_token", None):
383
+ return
384
+ current = _metadata_issuer(context)
385
+ if current is None: # not discovered yet; the SDK's 401-branch discovery + _store_tokens stamp it later
386
+ return
387
+ stored = (storage.loaded_issuer or "").rstrip("/") or None
388
+ if stored is None:
389
+ storage.stamp_issuer(current)
390
+ return
391
+ if stored != current:
392
+ logger.warning("MCP OAuth: authorization server issuer changed (%s -> %s); dropping the stored "
393
+ "refresh token rather than sending it to a different issuer", stored, current)
394
+ storage.strip_refresh_token()
395
+ tokens.refresh_token = None
396
+
397
+
398
+ def prepare_oauth_config(server_name: str, server_url: str, oauth_config: dict | None) -> tuple[dict, "HermesTokenStorage"]:
399
+ """Copy the ``oauth:`` block, apply provider defaults, open its token storage. The copy
400
+ matters: later steps record ``_resolved_port`` / ``_cimd_url`` in the dict, which must
401
+ never leak back into the caller's config."""
402
+ from tools import mcp_oauth as mo
403
+ cfg = dict(oauth_config or {})
404
+ mo.apply_oauth_provider_defaults(cfg, server_name=server_name, server_url=server_url)
405
+ return cfg, mo.HermesTokenStorage(server_name)
406
+
407
+
408
+ def build_provider_kwargs(cfg: dict, storage: "HermesTokenStorage", *, ssh_proxy_hint: bool) -> dict[str, Any]:
409
+ """Resolve the callback port and return the shared provider constructor kwargs. Order
410
+ matters: metadata needs the resolved port, pre-registration needs the metadata.
411
+ ``ssh_proxy_hint`` lets the redirect handler tailor its remote-session hint to a configured
412
+ proxy ``redirect_uri``. Helpers are looked up on ``tools.mcp_oauth`` so tests can patch them."""
413
+ from tools import mcp_oauth as mo
414
+ port = mo._configure_callback_port(cfg, storage)
415
+ client_metadata = mo._build_client_metadata(cfg)
416
+ mo._maybe_preregister_client(storage, cfg, client_metadata)
417
+ redirect_uri = (cfg.get("redirect_uri") or None) if ssh_proxy_hint else None
418
+ return {
419
+ "client_metadata": client_metadata,
420
+ "storage": storage,
421
+ "redirect_handler": mo._make_redirect_handler(port, redirect_uri=redirect_uri),
422
+ # mcp 2.0 dropped OAuthClientProvider's own `timeout`; the configured
423
+ # `oauth.timeout` bounds the callback waiter's poll loop instead.
424
+ "callback_handler": mo._make_callback_waiter(port, cfg.get("_cimd_url"), timeout=float(cfg.get("timeout", 300))),
425
+ "token_user_agent": mo.token_request_user_agent(cfg),
426
+ "oauth_flow": cfg.get("flow", "browser"),
427
+ **mo.cimd_provider_kwargs(cfg)}
tools/mcp_schema_cache.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persistent MCP tool-schema cache for lazy server startup: per-server tool manifests on
2
+ disk so Hermes can register MCP tools into the agent snapshot without spawning the stdio
3
+ child at idle dashboard startup. Entries are keyed by server name + a fingerprint of the
4
+ connection config (command/args/url/tools filters)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ import logging
11
+ import threading
12
+ import time
13
+ from pathlib import Path
14
+ from typing import Any, Dict, List, Optional
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ _CACHE_FILENAME = "mcp_schema_cache.json"
19
+ _cache_lock = threading.Lock()
20
+
21
+
22
+ def _cache_path() -> Path:
23
+ from hermes_constants import get_hermes_home
24
+ return get_hermes_home() / "cache" / _CACHE_FILENAME
25
+
26
+
27
+ def config_fingerprint(config: dict) -> str:
28
+ """Stable hash of the connection-defining parts of an MCP server config."""
29
+ tools_filter = config.get("tools") or {}
30
+ payload = {
31
+ "command": config.get("command"),
32
+ "args": config.get("args") or [],
33
+ "url": config.get("url"),
34
+ "transport": config.get("transport"),
35
+ "tools_include": sorted(tools_filter.get("include") or []),
36
+ "tools_exclude": sorted(tools_filter.get("exclude") or [])}
37
+ raw = json.dumps(payload, sort_keys=True, separators=(",", ":"))
38
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
39
+
40
+
41
+ def _load_all() -> Dict[str, Any]:
42
+ path = _cache_path()
43
+ if not path.exists():
44
+ return {}
45
+ try:
46
+ data = json.loads(path.read_text(encoding="utf-8"))
47
+ return data if isinstance(data, dict) else {}
48
+ except Exception as exc:
49
+ logger.debug("Could not read MCP schema cache %s: %s", path, exc)
50
+ return {}
51
+
52
+
53
+ def _save_all(data: Dict[str, Any]) -> None:
54
+ from utils import atomic_json_write
55
+ # 0o600: the cache file is trusted input on the lazy registration path, keep it user-only.
56
+ atomic_json_write(_cache_path(), data, mode=0o600)
57
+
58
+
59
+ def get_cached_entry(server_name: str, fingerprint: str) -> Optional[dict]:
60
+ """Return cached entry when fingerprint matches (and TTL holds), else None. ``tools/list``
61
+ results may carry ``ttlMs`` (SEP-2549); an entry older than a recorded TTL is a miss so the
62
+ next startup re-probes instead of serving a stale manifest forever. Entries without a TTL
63
+ never expire. ``cacheScope`` is irrelevant: this cache is per-user local disk."""
64
+ with _cache_lock:
65
+ entry = _load_all().get(server_name)
66
+ if not isinstance(entry, dict) or entry.get("fingerprint") != fingerprint:
67
+ return None
68
+ ttl_ms = entry.get("ttl_ms")
69
+ written_at = entry.get("written_at")
70
+ expired = (isinstance(ttl_ms, (int, float)) and isinstance(written_at, (int, float))
71
+ and (time.time() - written_at) * 1000.0 >= float(ttl_ms))
72
+ return None if expired else entry
73
+
74
+
75
+ def write_cache_entry(server_name: str, fingerprint: str, *, tools: List[dict],
76
+ utility_tools: Optional[List[dict]] = None, ttl_ms: Optional[float] = None,
77
+ cache_scope: Optional[str] = None) -> None:
78
+ """Persist tool schemas after a successful live connect. ``ttl_ms`` / ``cache_scope`` are
79
+ the server's ``tools/list`` SEP-2549 hints; ``written_at`` anchors TTL expiry."""
80
+ entry = {"fingerprint": fingerprint, "tools": tools, "utility_tools": utility_tools or []}
81
+ if isinstance(ttl_ms, (int, float)):
82
+ entry["ttl_ms"] = ttl_ms
83
+ entry["written_at"] = time.time()
84
+ if cache_scope:
85
+ entry["cache_scope"] = cache_scope
86
+ with _cache_lock:
87
+ data = _load_all()
88
+ # Write-through fires on every registration (reconnects, list_changed); skip the
89
+ # rewrite when the entry is byte-identical on disk. TTL'd entries always rewrite:
90
+ # written_at must advance or the entry would expire at its ORIGINAL write time.
91
+ if "written_at" not in entry and data.get(server_name) == entry:
92
+ return
93
+ data[server_name] = entry
94
+ _save_all(data)
95
+
96
+
97
+ def _list_field(entry: dict, key: str) -> List[dict]:
98
+ value = entry.get(key)
99
+ return list(value) if isinstance(value, list) else []
100
+
101
+
102
+ def tools_from_cache_entry(entry: dict) -> List[dict]:
103
+ """Return cached MCP tool dicts (name, description, inputSchema)."""
104
+ return _list_field(entry, "tools")
105
+
106
+
107
+ def utility_tools_from_cache_entry(entry: dict) -> List[dict]:
108
+ """Return cached ``{schema, handler_key}`` utility rows."""
109
+ return _list_field(entry, "utility_tools")
110
+
111
+
112
+ # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
113
+ # Names external plugins imported from this module before the Sep 2026 decomposition.
114
+ # Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
115
+ # The whole block is removed by reverting the commit that added it.
116
+
117
+ def clear_cache_entry(server_name: str) -> None:
118
+ with _cache_lock:
119
+ data = _load_all()
120
+ if server_name in data:
121
+ del data[server_name]
122
+ _save_all(data)
123
+
124
+ def has_cached_entry(server_name: str, fingerprint: str) -> bool:
125
+ return get_cached_entry(server_name, fingerprint) is not None
126
+ # ---- END PLUGIN-COMPAT ----