diff --git a/docs/architecture/remote-workspace-transport.md b/docs/architecture/remote-workspace-transport.md index 268e9cafef..aed702eae1 100644 --- a/docs/architecture/remote-workspace-transport.md +++ b/docs/architecture/remote-workspace-transport.md @@ -707,8 +707,9 @@ between identical OS credentials. Discover capabilities at the provider/assembly boundary, not with scattered `is_remote` gates in individual tools. Missing target programs, an unavailable interactive desktop, network loss and platform-specific process behavior can -require explicit differences. A local hook executable or MCP command is not -silently relocated to the target. Keep its execution domain and source trust +require explicit differences. User and imported Hook commands remain host +owned; manually configured project Hook commands are explicitly target-owned +when the project gate is enabled. Keep execution domain and source trust explicit; reuse the existing engine and approval mechanism. Remote workspaces do not acquire Detached Dispatch semantics through this diff --git a/docs/features/agent-hooks.md b/docs/features/agent-hooks.md index 2da1702b2b..354f1d71e4 100644 --- a/docs/features/agent-hooks.md +++ b/docs/features/agent-hooks.md @@ -51,6 +51,22 @@ Both layers are additive: every matching handler runs, user handlers first. There is no override or shadowing between them. Changes are picked up without restarting OpenBitFun. +### RTK command rewrite example + +The repository contains a reusable RTK example in +[`examples/rtk`](agent-hooks/examples/rtk/README.md). It includes a Windows +user hook and a POSIX project hook for `ExecCommand`. + +Copy the POSIX files into a target repository's `.openbitfun/` directory when +the workspace runs on Linux, WSL, or an SSH host. The Python script resolves +`~/.local/bin/rtk` before consulting `PATH`, because remote non-interactive +shells may not load `.bashrc`. The Windows template is copied into the user +configuration and is suitable for local workspaces. + +The templates are inactive until copied into one of the documented hook +locations. Project hooks still require `app.hooks.project_hooks_enabled` and +should only be enabled for trusted repositories. + ## Turning hooks on **Settings → Agent Hooks**, or directly under the `app` section of @@ -117,9 +133,9 @@ Import, update, enable, disable, and remove take effect on the next matching Hook event; an already running Hook finishes against the snapshot it started with. OpenBitFun does not re-import on startup, poll, or watch Claude Code/Codex files. Use **Refresh** or `/hooks refresh` to check for source changes, then -review an update explicitly. The management and execution paths are local-only; -remote workspaces return unsupported instead of running local commands against -a remote path. +review an update explicitly. Import management remains controller-owned. Remote +dispatch skips user/imported snapshots and runs only the manually configured +project layer through the target workspace provider. OpenCode plugin Hooks are intentionally excluded. Their JavaScript callbacks need the OpenCode plugin execution domain; the current OpenCode Hook catalog is @@ -208,8 +224,8 @@ metadata. Native `hooks.json` keeps its Codex decision contract. The master `app.hooks.enabled` gate applies. Project skills additionally require `app.hooks.project_hooks_enabled`, including on subsequent dispatch. Activation -without a session/local workspace, or in an SSH/remote workspace, returns an -explicit error; no controller-local fallback executes. Remote control, Peer Device, +without a session/local workspace, or for a skill invocation in an SSH/remote workspace, returns an +explicit error; no controller-local fallback executes. Native project `hooks.json` still runs through the target provider. Remote control, Peer Device, and Detached Dispatch reuse their target runtime's session and permission owners; this change does not introduce a separate client-side hook runner. @@ -289,7 +305,7 @@ Everything not listed here behaves as the Codex documentation describes. | `[features] hooks = false` | use `app.hooks.enabled` | | Plugin-bundled and managed hooks (`PLUGIN_ROOT`, `managed_dir`) | not supported | | `prompt` and `agent` handler types | parsed so shared files stay valid, but skipped — only `type: "command"` executes | -| Remote workspaces | hooks are not dispatched: a local hook process and a remote workspace path do not describe the same filesystem. The skip is reported, not silent: when the host has rules for the event, the first skipped dispatch per session logs a warning, and the hook overview carries `remote_workspace_unsupported` so surfaces can say the configured rules did not run | +| Remote workspaces | user hooks and imported Hook snapshots are skipped; when `app.hooks.project_hooks_enabled` is enabled, the project `hooks.json` is read from the remote workspace and its command handlers run through the target workspace shell with the normal JSON stdin contract. Missing remote providers fail closed without controller-local fallback. | ### Fields not populated yet @@ -342,7 +358,7 @@ every time its event fires. Treat `hooks.json` like a shell profile: | Symptom | Cause | | --- | --- | -| No hook runs at all | `app.hooks.enabled` is `false`, the file is not at the documented path, or the workspace is remote (the log then carries a warning for the first skipped dispatch of each session). | +| No hook runs at all | `app.hooks.enabled` is `false`, the file is not at the documented path, or a remote project Hook cannot read its target-side configuration/provider. Remote user hooks are skipped by design. | | Project hooks do not run | `app.hooks.project_hooks_enabled` is `false` (the default). | | The whole file is ignored | Invalid JSON, or a root key other than `description`/`hooks`. | | One event is ignored | Misspelled event name — the names are case-sensitive. | diff --git a/docs/features/agent-hooks.zh-CN.md b/docs/features/agent-hooks.zh-CN.md index 3bbe0fa99e..8ba6ceb86c 100644 --- a/docs/features/agent-hooks.zh-CN.md +++ b/docs/features/agent-hooks.zh-CN.md @@ -42,6 +42,20 @@ Codex 读 `~/.codex/hooks.json`,OpenBitFun 改为读自己的配置目录。 两个层级是叠加关系:所有匹配的处理器都会执行,用户层优先,层级之间不存在覆盖或 屏蔽。修改后无需重启 OpenBitFun。 +### RTK 命令改写示例 + +仓库提供了可复用的 RTK 示例:[`examples/rtk`](agent-hooks/examples/rtk/README.md)。 +其中包含一个 Windows 用户级 Hook 和一个 POSIX 项目级 Hook,用于改写 +`ExecCommand`。 + +如果工作区运行在 Linux、WSL 或 SSH 主机上,把 POSIX 示例文件复制到目标仓库的 +`.openbitfun/` 目录。Python 脚本会先查找 `~/.local/bin/rtk`,再查找 `PATH`;这是因为 +远程非交互 shell 可能不会加载 `.bashrc`。Windows 示例复制到用户配置目录,适用于 +本地工作区。 + +示例文件不会自动生效,只有复制到文档规定的 Hook 路径后才会加载。项目级 Hook 仍然 +需要开启 `app.hooks.project_hooks_enabled`,并且只应在信任的仓库中启用。 + ## 开启 Hooks **设置 → Agent Hooks**,或直接编辑 `<用户配置目录>/config/app.json` 的 `app` 段: @@ -99,7 +113,7 @@ OpenBitFun 可以把 Claude Code 或 Codex 中兼容的 `type: "command"` Hook 导入、更新、启用、停用和移除会在下一个匹配的 Hook 事件生效;已经开始运行的 Hook 仍使用启动时捕获的快照完成。OpenBitFun 不会在启动时重新导入,也不会轮询或监听 Claude Code/Codex 文件。请使用**刷新**或 `/hooks refresh` 检查来源变化,再显式审阅更新。 -管理与执行均只支持本地工作区;远程工作区会明确返回不支持,不会用本地命令处理远程 +管理仍在控制端;远程工作区跳过 user Hook 和导入快照,仅在开启项目 Hook 时通过远程工作区文件与目标端 shell 读取、执行项目 `hooks.json`,不会回退到控制端本地命令 路径。 OpenCode 插件 Hooks 明确不在本次范围内。其 JavaScript 回调依赖 OpenCode 插件执行域; @@ -244,7 +258,7 @@ sys.exit(0) | `[features] hooks = false` | 使用 `app.hooks.enabled` | | 插件内置与托管 Hooks(`PLUGIN_ROOT`、`managed_dir`) | 不支持 | | `prompt` 与 `agent` 处理器类型 | 会被解析(以便共享配置文件保持有效)但跳过 —— 只有 `type: "command"` 会执行 | -| 远程工作区 | 不派发 Hooks:本地 Hook 进程与远程工作区路径描述的不是同一个文件系统。跳过不是静默的:当宿主为该事件配置了规则时,每个会话第一次跳过会记录一条警告,Hook 概览也带有 `remote_workspace_unsupported`,供界面说明已配置的规则没有运行 | +| 远程工作区 | 跳过 user Hook 和导入快照;开启 `app.hooks.project_hooks_enabled` 后,从远程工作区读取项目 `hooks.json`,并通过目标端 shell 执行命令,stdin/stdout/stderr、超时和取消沿用 Hook 契约。远程 provider 不可用时失败关闭,不回退到控制端 | ### 尚未填充的字段 @@ -293,7 +307,7 @@ Hook 是以你的用户权限运行的任意代码,且每次对应事件触发 | 现象 | 原因 | | --- | --- | -| 完全没有 Hook 运行 | `app.hooks.enabled` 为 `false`、文件不在文档所述路径,或工作区是远程工作区(此时日志会为每个会话第一次跳过的派发记录一条警告)。 | +| 完全没有 Hook 运行 | `app.hooks.enabled` 为 `false`、文件不在文档所述路径,或远程项目 Hook 无法读取目标端配置/provider。远程 user Hook 本来就会跳过;项目 Hook 的配置与命令都在目标端。 | | 项目 Hooks 不运行 | `app.hooks.project_hooks_enabled` 为 `false`(默认值)。 | | 整个文件被忽略 | JSON 无效,或存在 `description`/`hooks` 之外的根级字段。 | | 某个事件被忽略 | 事件名拼写错误 —— 事件名区分大小写。 | diff --git a/docs/features/agent-hooks/examples/rtk/README.md b/docs/features/agent-hooks/examples/rtk/README.md new file mode 100644 index 0000000000..f3378d1645 --- /dev/null +++ b/docs/features/agent-hooks/examples/rtk/README.md @@ -0,0 +1,66 @@ +# RTK command rewrite example + +This example connects [RTK](https://github.com/rtk-ai/rtk) to OpenBitFun's +`PreToolUse` hook for `ExecCommand`. RTK can rewrite a command before it is +sent to the terminal and can reject a command with exit code 2. + +The files in this directory are templates. They are deliberately not stored +under a live `.openbitfun/` directory, so cloning this repository does not +activate a hook in the development checkout. + +## Windows local workspace + +1. Install `rtk` and make sure it is visible to the OpenBitFun process. +2. Copy `rtk-hook.ps1` to `%USERPROFILE%\.openbitfun\hooks\rtk-hook.ps1`. +3. Merge `hooks.windows.user.json` into + `%APPDATA%\openbitfun\config\hooks.json` (merge the `hooks` entries if the + file already contains other hooks). +4. Keep `app.hooks.enabled` enabled. + +The Windows template invokes PowerShell with `-NoProfile`. The script first +honors `RTK_BIN`, then searches `rtk.exe` and +`rtk` on `PATH`. + +## POSIX remote workspace + +Copy both project files into the target repository: + +```text +/.openbitfun/config/hooks.json +/.openbitfun/hooks/rtk-hook.py +``` + +Use `hooks.posix.project.json` as the contents of the project `hooks.json`, or +merge its `PreToolUse` entry into an existing file. Enable +`app.hooks.project_hooks_enabled` in OpenBitFun. + +The command runs on the workspace host: + +```text +python3 .openbitfun/hooks/rtk-hook.py +``` + +The script looks for `~/.local/bin/rtk` before falling back to `PATH`. This is +intentional: SSH non-interactive shells often do not source `.bashrc`, so an +export in `.bashrc` alone is not sufficient. RTK must be installed on the +workspace host, not only on the controller. + +Remote workspaces use the project layer only. User hooks and imported hook +snapshots stay on the controller and are skipped for remote dispatch. + +## Manual check + +From the target workspace, pipe a representative payload to the script: + +```bash +printf '%s\n' '{"tool_name":"ExecCommand","tool_input":{"cmd":"git status"}}' \ + | python3 .openbitfun/hooks/rtk-hook.py +``` + +The script emits a JSON `hookSpecificOutput.updatedInput` document when RTK +rewrites the command. An RTK exit code of 1 means "leave the command alone"; +exit code 2 blocks the tool call and writes the reason to stderr. Exit code 3 +rewrites without adding an `allow` decision. + +Project hooks execute repository code with the target user account. Enable +them only for repositories you trust. diff --git a/docs/features/agent-hooks/examples/rtk/hooks.posix.project.json b/docs/features/agent-hooks/examples/rtk/hooks.posix.project.json new file mode 100644 index 0000000000..2c7818eabb --- /dev/null +++ b/docs/features/agent-hooks/examples/rtk/hooks.posix.project.json @@ -0,0 +1,16 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "^ExecCommand$", + "hooks": [ + { + "type": "command", + "command": "python3 .openbitfun/hooks/rtk-hook.py", + "timeout": 30 + } + ] + } + ] + } +} diff --git a/docs/features/agent-hooks/examples/rtk/hooks.windows.user.json b/docs/features/agent-hooks/examples/rtk/hooks.windows.user.json new file mode 100644 index 0000000000..ef07e49cdf --- /dev/null +++ b/docs/features/agent-hooks/examples/rtk/hooks.windows.user.json @@ -0,0 +1,16 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "^ExecCommand$", + "hooks": [ + { + "type": "command", + "command": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File \"%USERPROFILE%\\.openbitfun\\hooks\\rtk-hook.ps1\"", + "timeout": 30 + } + ] + } + ] + } +} diff --git a/docs/features/agent-hooks/examples/rtk/rtk-hook.ps1 b/docs/features/agent-hooks/examples/rtk/rtk-hook.ps1 new file mode 100644 index 0000000000..7edecf6f9f --- /dev/null +++ b/docs/features/agent-hooks/examples/rtk/rtk-hook.ps1 @@ -0,0 +1,84 @@ +$raw = [Console]::In.ReadToEnd() +$hookInput = $raw | ConvertFrom-Json + +if ( + $hookInput.tool_name -ne 'ExecCommand' -or + $null -eq $hookInput.tool_input -or + $null -eq $hookInput.tool_input.cmd +) { + exit 0 +} + +$rtk = $env:RTK_BIN +if (-not $rtk) { + $rtkCommand = Get-Command rtk.exe -ErrorAction SilentlyContinue + if (-not $rtkCommand) { + $rtkCommand = Get-Command rtk -ErrorAction SilentlyContinue + } + if ($rtkCommand) { + $rtk = $rtkCommand.Source + } +} +if (-not $rtk) { + [Console]::Error.WriteLine('RTK hook: rtk was not found; leaving the command unchanged.') + exit 0 +} + +$stderrPath = [IO.Path]::GetTempFileName() + +try { + $rewrittenLines = @( + & $rtk rewrite -- ([string]$hookInput.tool_input.cmd) 2> $stderrPath + ) + $rtkExit = $LASTEXITCODE + $rtkError = ( + Get-Content -LiteralPath $stderrPath -Raw ` + -ErrorAction SilentlyContinue + ).Trim() +} +finally { + Remove-Item -LiteralPath $stderrPath -Force ` + -ErrorAction SilentlyContinue +} + +switch ($rtkExit) { + 0 { $decision = 'allow' } + 1 { exit 0 } + 2 { + if ($rtkError) { + [Console]::Error.WriteLine($rtkError) + } else { + [Console]::Error.WriteLine('RTK denied this command.') + } + exit 2 + } + 3 { $decision = $null } + default { exit 0 } +} + +$rewritten = ($rewrittenLines -join "`n").Trim() +if (-not $rewritten) { + exit 0 +} + +$updated = [ordered]@{} +foreach ($property in $hookInput.tool_input.PSObject.Properties) { + $updated[$property.Name] = $property.Value +} +$updated['cmd'] = $rewritten + +$specific = [ordered]@{ + hookEventName = 'PreToolUse' + updatedInput = [pscustomobject]$updated +} + +if ($decision) { + $specific.permissionDecision = $decision + $specific.permissionDecisionReason = 'RTK auto-rewrite' +} + +[ordered]@{ + hookSpecificOutput = [pscustomobject]$specific +} | ConvertTo-Json -Compress -Depth 20 + +exit 0 diff --git a/docs/features/agent-hooks/examples/rtk/rtk-hook.py b/docs/features/agent-hooks/examples/rtk/rtk-hook.py new file mode 100644 index 0000000000..5ddd349bda --- /dev/null +++ b/docs/features/agent-hooks/examples/rtk/rtk-hook.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Rewrite OpenBitFun ExecCommand payloads with RTK.""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + + +def find_rtk() -> str | None: + configured = os.environ.get("RTK_BIN") + if configured: + return configured + + # Prefer the common user-local installation explicitly. Remote SSH + # commands frequently do not source .bashrc, so PATH may be incomplete. + for name in ("rtk", "rtk.exe"): + candidate = Path.home() / ".local" / "bin" / name + if candidate.is_file() and os.access(candidate, os.X_OK): + return str(candidate) + + return shutil.which("rtk") or shutil.which("rtk.exe") + + +def main() -> int: + try: + payload = json.load(sys.stdin) + except (json.JSONDecodeError, OSError) as error: + print(f"RTK hook received invalid JSON: {error}", file=sys.stderr) + return 0 + + if not isinstance(payload, dict): + return 0 + + if payload.get("tool_name") != "ExecCommand": + return 0 + + tool_input = payload.get("tool_input") + if not isinstance(tool_input, dict) or not isinstance(tool_input.get("cmd"), str): + return 0 + + rtk = find_rtk() + if not rtk: + print("RTK hook: rtk was not found; leaving the command unchanged", file=sys.stderr) + return 0 + + try: + result = subprocess.run( + [rtk, "rewrite", "--", tool_input["cmd"]], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + except OSError as error: + print(f"RTK hook could not start rtk: {error}", file=sys.stderr) + return 0 + + if result.returncode == 1: + return 0 + if result.returncode == 2: + reason = result.stderr.strip() or "RTK denied this command." + print(reason, file=sys.stderr) + return 2 + if result.returncode not in (0, 3): + return 0 + + rewritten = result.stdout.strip() + if not rewritten: + return 0 + + updated_input = dict(tool_input) + updated_input["cmd"] = rewritten + hook_output = { + "hookEventName": "PreToolUse", + "updatedInput": updated_input, + } + if result.returncode == 0: + hook_output["permissionDecision"] = "allow" + hook_output["permissionDecisionReason"] = "RTK auto-rewrite" + print( + json.dumps( + {"hookSpecificOutput": hook_output}, + separators=(",", ":"), + ) + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/apps/cli/src/modes/chat/native_hooks.rs b/src/apps/cli/src/modes/chat/native_hooks.rs index 1c5a867720..f0afd2735e 100644 --- a/src/apps/cli/src/modes/chat/native_hooks.rs +++ b/src/apps/cli/src/modes/chat/native_hooks.rs @@ -154,7 +154,7 @@ fn project_native_hook_overview( /// English line shown in `/hooks` when the session workspace is remote. const REMOTE_WORKSPACE_HOOKS_NOTICE: &str = - "Hooks are not run for this remote workspace: hooks execute only on the host that owns the workspace filesystem, and none of the rules above ran here."; + "Remote workspace: user and imported Hooks are skipped; enabled project Hooks are read and run on the target workspace host."; fn native_hook_help_text() -> String { [ @@ -342,7 +342,7 @@ mod remote_hook_projection_tests { } #[test] - fn remote_workspace_overview_renders_the_skip_before_configuration_issues() { + fn remote_workspace_overview_renders_target_side_semantics_before_issues() { let workspace = std::path::Path::new("/srv/remote-project"); let projected = project_native_hook_overview(core_overview(true), workspace); assert_eq!( @@ -352,7 +352,9 @@ mod remote_hook_projection_tests { assert_eq!(projected.issues.len(), 2); let text = render_native_hook_overview(&projected); - assert!(text.contains("Hooks are not run for this remote workspace")); + assert!( + text.contains("enabled project Hooks are read and run on the target workspace host") + ); assert!(text.contains("is not a supported event name")); } diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index d805e89287..5d0b43ee24 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -3104,6 +3104,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet session: &'a Session, workspace_root: Option<&'a Path>, is_remote_workspace: bool, + workspace_services: Option<&'a WorkspaceServices>, ) -> NativeHookSessionFacts<'a> { NativeHookSessionFacts { workspace_id: session.config.workspace_id.as_deref(), @@ -3113,6 +3114,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet is_remote_workspace, model: session.config.model_id.as_deref().unwrap_or_default(), bypass_permissions: false, + workspace_services, } } @@ -3131,10 +3133,26 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet /// Run SessionStart hooks. `source` follows the Codex vocabulary: /// `startup` | `resume` | `clear` | `compact`. async fn dispatch_session_start_hooks(session: &Session, source: &str) { - let workspace_root = session.config.workspace_path.as_ref().map(Path::new); + let binding = Self::build_workspace_binding(&session.config).await; + let workspace_root = binding.as_ref().map(|binding| binding.root_path()); let is_remote = Self::session_hooks_are_remote(session).await; + let workspace_services = match Self::build_workspace_services(&binding).await { + Ok(services) => services, + Err(error) => { + warn!( + "SessionStart project Hooks are unavailable for the workspace: {}", + error + ); + None + } + }; native_hooks::dispatch_session_start( - Self::session_hook_facts(session, workspace_root, is_remote), + Self::session_hook_facts( + session, + workspace_root, + is_remote, + workspace_services.as_ref(), + ), source, ) .await; @@ -6853,6 +6871,10 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet } } + // Resolve the workspace provider before UserPromptSubmit so a remote + // project Hook can run on the target before the turn is admitted. + let workspace_services = Self::build_workspace_services(&session_workspace).await?; + // UserPromptSubmit hooks run before any turn state is created, so a // blocking hook rejects the prompt without leaving a partial turn. // Their context (plus buffered SessionStart context) is prepended to @@ -6864,6 +6886,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet &session, session.config.workspace_path.as_deref().map(Path::new), Self::session_hooks_are_remote(&session).await, + workspace_services.as_ref(), ) }, &user_input, @@ -7005,9 +7028,6 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet user_message_metadata = Some(metadata); } - // Build WorkspaceServices based on the workspace type - let workspace_services = Self::build_workspace_services(&session_workspace).await?; - info!( "Dialog turn workspace context: session_id={}, workspace_path={:?}, is_remote={}, workspace_services={}", session_id, @@ -9046,10 +9066,23 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet Self::session_hooks_are_remote(&session).await, session.config.model_id.clone().unwrap_or_default(), session.config.workspace_id.clone(), + match Self::build_workspace_services( + &Self::build_workspace_binding(&session.config).await, + ) + .await + { + Ok(services) => services, + Err(error) => { + warn!("SessionEnd project Hooks are unavailable: {}", error); + None + } + }, )), None => None, }; - if let Some((is_remote_workspace, model, workspace_id)) = session_hook_facts { + if let Some((is_remote_workspace, model, workspace_id, workspace_services)) = + session_hook_facts + { native_hooks::dispatch_session_end( NativeHookSessionFacts { workspace_id: workspace_id.as_deref(), @@ -9059,6 +9092,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet is_remote_workspace, model: &model, bypass_permissions: false, + workspace_services: workspace_services.as_ref(), }, "other", ) @@ -11258,6 +11292,8 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet } let subagent_workspace = Self::build_workspace_binding(&session.config).await; + let subagent_services = Self::build_workspace_services(&subagent_workspace).await?; + let subagent_hook_services = subagent_services.clone(); let subagent_workspace_path = subagent_workspace .as_ref() .map(|workspace| workspace.root_path_string()); @@ -11307,6 +11343,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet is_remote_workspace: subagent_hook_is_remote, model: &subagent_hook_model, bypass_permissions: false, + workspace_services: subagent_hook_services.as_ref(), }; for section in native_hooks::dispatch_subagent_start(subagent_hook_facts, &session_id, &agent_type) @@ -11330,7 +11367,6 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet session.config.model_pool_selection_revision.to_string(), ); } - let subagent_services = Self::build_workspace_services(&subagent_workspace).await?; let execution_context = ExecutionContext { session_id: session_id.clone(), dialog_turn_id: dialog_turn_id.clone(), @@ -13472,6 +13508,17 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet let workspace_path = session.config.workspace_path.clone().map(PathBuf::from); let is_remote_workspace = Self::session_hooks_are_remote(&session).await; let model = session.config.model_id.clone().unwrap_or_default(); + let workspace_services = match Self::build_workspace_services( + &Self::build_workspace_binding(&session.config).await, + ) + .await + { + Ok(services) => services, + Err(error) => { + warn!("SessionEnd project Hooks are unavailable: {}", error); + None + } + }; if let Some(workspace_path) = workspace_path.as_deref() { native_hooks::dispatch_session_end( NativeHookSessionFacts { @@ -13482,6 +13529,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet is_remote_workspace, model: &model, bypass_permissions: false, + workspace_services: workspace_services.as_ref(), }, "other", ) diff --git a/src/crates/assembly/core/src/agentic/execution/compression_lifecycle.rs b/src/crates/assembly/core/src/agentic/execution/compression_lifecycle.rs index c00cfba492..0f946f65f8 100644 --- a/src/crates/assembly/core/src/agentic/execution/compression_lifecycle.rs +++ b/src/crates/assembly/core/src/agentic/execution/compression_lifecycle.rs @@ -117,7 +117,13 @@ impl ExecutionEngine { let expected_last_turn = session.dialog_turn_ids.last().cloned(); let planned_result = prepare_compression_cancellable(&cancellation_token, async { native_hooks::dispatch_pre_compact( - Self::native_hook_facts(session_id, dialog_turn_id, workspace, &ai_client_model), + Self::native_hook_facts( + session_id, + dialog_turn_id, + workspace, + workspace_services, + &ai_client_model, + ), trigger, ) .await; @@ -440,6 +446,7 @@ impl ExecutionEngine { session_id, dialog_turn_id, workspace, + workspace_services, &ai_client_model, ), trigger, diff --git a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs index 2bd7dbfb7f..76db71057b 100644 --- a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs +++ b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs @@ -2870,6 +2870,7 @@ impl ExecutionEngine { session_id: &'a str, dialog_turn_id: &'a str, workspace: Option<&'a WorkspaceBinding>, + workspace_services: Option<&'a crate::agentic::workspace::WorkspaceServices>, model: &'a str, ) -> NativeHookSessionFacts<'a> { NativeHookSessionFacts { @@ -2880,6 +2881,7 @@ impl ExecutionEngine { is_remote_workspace: workspace.is_some_and(|workspace| workspace.is_remote()), model, bypass_permissions: false, + workspace_services, } } @@ -2913,6 +2915,7 @@ impl ExecutionEngine { &session_id, &dialog_turn_id, context.workspace.as_ref(), + context.workspace_services.as_ref(), &scaffold.ai_client.config.model, ), trigger, @@ -3159,6 +3162,7 @@ impl ExecutionEngine { &session_id, &dialog_turn_id, context.workspace.as_ref(), + context.workspace_services.as_ref(), &scaffold.ai_client.config.model, ), trigger, @@ -5548,6 +5552,7 @@ impl ExecutionEngine { &context.session_id, &context.dialog_turn_id, context.workspace.as_ref(), + context.workspace_services.as_ref(), &ai_client.config.model, ), stop_hook_continuations > 0, diff --git a/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs b/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs index a9bf0f38bd..65afb7826a 100644 --- a/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs +++ b/src/crates/assembly/core/src/agentic/tools/pipeline/tool_pipeline.rs @@ -735,6 +735,7 @@ fn native_hook_session_facts<'a>( .is_some_and(|workspace| workspace.is_remote()), model: &context.primary_model_facts.model_id, bypass_permissions: options.auto_approve_ask, + workspace_services: context.workspace_services.as_ref(), } } diff --git a/src/crates/assembly/core/src/native_hooks.rs b/src/crates/assembly/core/src/native_hooks.rs index 9359afa9f2..4e5387e390 100644 --- a/src/crates/assembly/core/src/native_hooks.rs +++ b/src/crates/assembly/core/src/native_hooks.rs @@ -13,24 +13,26 @@ //! - Dispatch: typed helpers per lifecycle event, called from the //! conversation coordinator, execution engine, and tool pipeline. //! -//! Hooks always execute on the local host. Remote workspaces skip hook -//! dispatch because the payload `cwd` and the hook process would disagree -//! about the filesystem they describe. +//! Local hooks use the controller process environment. Remote workspaces keep +//! user hooks disabled, while project hooks are loaded through the workspace +//! filesystem and executed through the target workspace shell. +use crate::agentic::workspace::WorkspaceServices; use crate::infrastructure::try_get_path_manager_arc; use crate::service::config::get_global_config_service; pub use crate::service::config::types::AgentHooksConfig; use async_trait::async_trait; use dashmap::DashMap; -use log::{debug, info, warn}; +use log::{info, warn}; #[cfg(feature = "opencode-plugin-host")] use openbitfun_agent_runtime::native_hooks::PluginHookDispatchResult; use openbitfun_agent_runtime::native_hooks::{ AgentHookEngine, AgentHookEvent, AgentHookEventPayload, AgentHookMatcher, AgentHookOutcome, AgentHookPayload, AgentHookPayloadCommon, AgentHookPermissionMode, AgentHookPermissionOutcome, AgentHookScope, AgentHookSettings, AgentHookSettingsLayer, BuiltinHookExecutor, HookCall, - HookCallPayload, HookHandler, HookHandlerResult, RuntimeHookKind, RuntimeHookPlan, - RuntimeHookRegistration, RuntimeHookRegistry, RuntimeHookSource, MAX_HOOKS_FILE_BYTES, + HookCallPayload, HookHandler, HookHandlerResult, HookProcessProvider, HookProcessResult, + RuntimeHookKind, RuntimeHookPlan, RuntimeHookRegistration, RuntimeHookRegistry, + RuntimeHookSource, MAX_HOOKS_FILE_BYTES, }; use openbitfun_agent_runtime::post_call_hooks::{ resolve_deep_review_shared_context_tool_use, DeepReviewSharedContextToolUseFacts, @@ -40,6 +42,7 @@ use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use std::sync::{Arc, OnceLock}; +use std::time::Duration; const MAX_CACHED_WORKSPACE_HOOK_SOURCES: usize = 32; const MAX_PENDING_CONTEXT_SESSIONS: usize = 1024; @@ -90,6 +93,53 @@ fn hook_engine(registry: RuntimeHookRegistry) -> AgentHookEngine { AgentHookEngine::with_registry(registry).with_environment_defaults(hook_environment_defaults()) } +#[derive(Clone)] +struct WorkspaceHookProcessProvider { + shell: Arc, +} + +impl std::fmt::Debug for WorkspaceHookProcessProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("WorkspaceHookProcessProvider") + .field("shell", &"") + .finish() + } +} + +#[async_trait] +impl HookProcessProvider for WorkspaceHookProcessProvider { + async fn execute( + &self, + command: &str, + payload_json: &str, + _cwd: &Path, + timeout: Duration, + environment: &BTreeMap, + ) -> HookProcessResult { + let result = self + .shell + .exec_with_stdin( + command, + payload_json.as_bytes(), + environment, + openbitfun_runtime_ports::WorkspaceCommandOptions { + timeout_ms: Some(timeout.as_millis().min(u64::MAX as u128) as u64), + ..Default::default() + }, + ) + .await; + match result { + Ok(result) if result.timed_out => HookProcessResult::TimedOut, + Ok(result) => HookProcessResult::Completed { + exit_code: Some(result.exit_code), + stdout: result.stdout, + stderr: result.stderr, + }, + Err(error) => HookProcessResult::SpawnFailed(error.to_string()), + } + } +} + #[cfg(feature = "opencode-plugin-host")] pub(crate) fn plugin_hook_registry(_workspace_scope: &str) -> RuntimeHookRegistry { runtime_hook_registry() @@ -356,6 +406,9 @@ pub struct NativeHookSessionFacts<'a> { /// Maps to payload `permission_mode`: `bypassPermissions` when the turn /// auto-approves permission asks, `default` otherwise. pub bypass_permissions: bool, + /// Workspace IO provider used for remote project Hook configuration and + /// target-side command execution. + pub workspace_services: Option<&'a WorkspaceServices>, } #[derive(Debug, Default)] @@ -913,8 +966,33 @@ async fn prepare<'a>( return None; } if facts.is_remote_workspace { - report_remote_workspace_skip(&facts, event).await; - return None; + if !config.project_hooks_enabled { + return None; + } + let services = facts.workspace_services?; + let engine = remote_engine_for(facts.workspace_id, facts.workspace_root, services) + .await? + .with_project_hooks_enabled(true) + .with_remote_project_only(true) + // Do not export the controller's GUI/login PATH to the target; + // the remote shell owns its own environment and PATH resolution. + .with_environment_defaults(BTreeMap::new()) + .with_process_provider(Arc::new(WorkspaceHookProcessProvider { + shell: Arc::clone(&services.shell), + })); + let workspace_scope = facts.workspace_id.map(str::to_owned); + if !engine.has_rules_for_session(event, workspace_scope.as_deref(), facts.session_id) { + return None; + } + return Some(PreparedDispatch { + engine, + facts, + cwd: facts + .workspace_root + .map(Path::to_path_buf) + .unwrap_or_default(), + workspace_scope, + }); } let engine = engine_for( facts.workspace_id, @@ -940,71 +1018,67 @@ async fn prepare<'a>( }) } -/// Dot-path of the hook gates inside the settings document. Config paths -/// resolve against the serialized `GlobalConfig`, where `AppConfig` lives -/// under `app`. -pub(crate) const HOOKS_CONFIG_PATH: &str = "app.hooks"; - -/// A remote workspace never dispatches hooks: a local hook process and a -/// remote workspace path do not describe the same filesystem. The skip must -/// still be visible, so when the host-level hook configuration has rules for -/// this event the first skip per session is logged as a warning. -/// -/// Only the host-owned user layer is consulted. The project layer of a remote -/// workspace lives on the remote host; deriving a controller-local path from -/// the remote root to look for it would be exactly the local read this skip -/// exists to prevent. -async fn report_remote_workspace_skip(facts: &NativeHookSessionFacts<'_>, event: AgentHookEvent) { - let configured = match engine_for(None, None, false).await { - Some(engine) => engine.has_rules_for_workspace(event, None), - None => false, - }; - if !configured { - debug!( - "Skipping agent hook dispatch for remote workspace: event={}, session_id={}", - event, facts.session_id - ); - return; - } - if remote_skip_already_reported(facts.session_id) { - debug!( - "Skipping configured agent hooks for remote workspace: event={}, session_id={}", - event, facts.session_id - ); - return; - } - warn!( - "Configured agent hooks are not executed for a remote workspace: event={}, session_id={}, workspace_root={}; hooks run only where the workspace filesystem lives, and this host did not run them locally", - event, - facts.session_id, - facts - .workspace_root - .map(|root| root.to_string_lossy().to_string()) - .unwrap_or_default() +/// Read the project Hook document from the target workspace. User and imported +/// layers remain controller-owned and are filtered out by the remote engine. +async fn remote_engine_for( + workspace_id: Option<&str>, + workspace_root: Option<&Path>, + services: &WorkspaceServices, +) -> Option { + let workspace_id = workspace_id?; + let root = workspace_root?; + let path = services.fs.join_path( + &root.to_string_lossy(), + &[".openbitfun", "config", "hooks.json"], ); -} - -/// One warning per session keeps the skip visible without repeating it for -/// every tool call of a long remote turn. The set is bounded so a long-lived -/// host does not accumulate ids forever. -fn remote_skip_already_reported(session_id: &str) -> bool { - const MAX_TRACKED_SESSIONS: usize = 1024; - static REPORTED: OnceLock>> = - OnceLock::new(); - let reported = REPORTED.get_or_init(Default::default); - let Ok(mut reported) = reported.lock() else { - return false; + let text = match services + .fs + .read_file_text_bounded(&path, MAX_HOOKS_FILE_BYTES) + .await + { + Ok(Some(text)) => text, + Ok(None) => { + warn!( + "Ignoring remote Hook configuration over the {} byte limit: {}", + MAX_HOOKS_FILE_BYTES, path + ); + return None; + } + Err(error) => { + warn!( + "Remote project Hook configuration is unavailable; project Hooks were not run: path={}, error={}", + path, error + ); + return Some(hook_engine(RuntimeHookRegistry::default())); + } + }; + let layer = AgentHookSettingsLayer { + scope: AgentHookScope::Project, + source: path, + bytes: text.into_bytes(), }; - if reported.contains(session_id) { - return true; + let (project_settings, issues) = AgentHookSettings::from_layers(&[layer]); + for issue in issues { + warn!("Remote project Hook configuration issue: {issue}"); } - if reported.len() >= MAX_TRACKED_SESSIONS { - reported.clear(); + let project_entries = registrations_for_source( + project_settings, + RuntimeHookSource::ProjectCommand, + Some(workspace_id), + ); + let registry = RuntimeHookRegistry::default(); + if let Err(error) = registry.register_batch(project_entries) { + warn!("Failed to publish remote project Hook registrations: {error}"); + return None; } - reported.insert(session_id.to_string()); - false + Some(hook_engine(registry)) } +/// Dot-path of the hook gates inside the settings document. Config paths +/// resolve against the serialized `GlobalConfig`, where `AppConfig` lives +/// under `app`. +pub(crate) const HOOKS_CONFIG_PATH: &str = "app.hooks"; + async fn hooks_config() -> AgentHooksConfig { match get_global_config_service().await { Ok(service) => service @@ -1327,8 +1401,8 @@ pub struct NativeHookOverview { pub total_handlers: usize, /// Configuration problems, in the wording used for the backend log. pub issues: Vec, - /// `true` when the workspace is remote: the rules above describe what is - /// configured on this host, but none of them run for that workspace. + /// `true` when the workspace is remote: user/imported rules in this host + /// view are skipped; enabled project rules execute on the target host. pub remote_workspace_unsupported: bool, } @@ -1358,10 +1432,9 @@ pub async fn overview(workspace_id: Option<&str>) -> Result, workspace_root: Option<&Path>, diff --git a/src/crates/assembly/core/src/native_hooks/skill_hooks.rs b/src/crates/assembly/core/src/native_hooks/skill_hooks.rs index 09b2849a88..d3bab67629 100644 --- a/src/crates/assembly/core/src/native_hooks/skill_hooks.rs +++ b/src/crates/assembly/core/src/native_hooks/skill_hooks.rs @@ -188,6 +188,7 @@ mod tests { is_remote_workspace: false, model: "test", bypass_permissions: false, + workspace_services: None, }, "other", ) diff --git a/src/crates/assembly/core/src/native_hooks_tests.rs b/src/crates/assembly/core/src/native_hooks_tests.rs index b187c19089..1baef0a64b 100644 --- a/src/crates/assembly/core/src/native_hooks_tests.rs +++ b/src/crates/assembly/core/src/native_hooks_tests.rs @@ -170,11 +170,9 @@ fn oversized_settings_files_are_ignored() { } #[tokio::test] -async fn remote_workspaces_skip_hook_dispatch() { - // Remote workspaces never dispatch: a local hook process cannot act on - // the remote filesystem. The skip resolves to a no-op decision regardless - // of local configuration; when hooks are configured it is reported, not - // silent. +async fn remote_workspaces_without_a_target_provider_skip_hook_dispatch() { + // User Hooks remain disabled remotely. Without a target workspace provider + // the project layer also fails closed rather than falling back locally. let decision = dispatch_pre_tool_use( NativeHookSessionFacts { workspace_id: Some("remote-workspace"), @@ -184,6 +182,7 @@ async fn remote_workspaces_skip_hook_dispatch() { is_remote_workspace: true, model: "model-x", bypass_permissions: false, + workspace_services: None, }, "Bash", "call-1", diff --git a/src/crates/contracts/runtime-ports/src/workspace_ports.rs b/src/crates/contracts/runtime-ports/src/workspace_ports.rs index b4452c55a5..4f3a3fbb38 100644 --- a/src/crates/contracts/runtime-ports/src/workspace_ports.rs +++ b/src/crates/contracts/runtime-ports/src/workspace_ports.rs @@ -1,4 +1,5 @@ use super::*; +use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::Arc; use std::time::SystemTime; @@ -345,6 +346,21 @@ pub trait WorkspaceShell: Send + Sync { options: WorkspaceCommandOptions, ) -> anyhow::Result; + /// Execute a command with a finite stdin payload and target-side + /// environment overrides. This is used by protocols such as Agent Hooks + /// whose contract is a JSON document on stdin. Providers that do not own a + /// full-duplex process transport must fail explicitly rather than silently + /// dropping the payload. + async fn exec_with_stdin( + &self, + _command: &str, + _stdin: &[u8], + _environment: &BTreeMap, + _options: WorkspaceCommandOptions, + ) -> anyhow::Result { + anyhow::bail!("workspace shell does not support stdin process execution") + } + /// Execute a command and return (stdout, stderr, exit_code). async fn exec( &self, diff --git a/src/crates/execution/agent-runtime/src/native_hooks/engine.rs b/src/crates/execution/agent-runtime/src/native_hooks/engine.rs index 7aa413e98a..ec4f45f871 100644 --- a/src/crates/execution/agent-runtime/src/native_hooks/engine.rs +++ b/src/crates/execution/agent-runtime/src/native_hooks/engine.rs @@ -14,6 +14,7 @@ use super::handler::{ CommandHookOptions, HookHandler, HookHandlerResult, HookToolMapping, PluginHookCall, }; use super::kind::RuntimeHookKind; +use super::kind::RuntimeHookSource; use super::output::{non_empty, AgentHookOutcome, RawHookOutput}; use super::payload::AgentHookPayload; use super::registry::{RuntimeHookErrorPolicy, RuntimeHookRegistry}; @@ -28,6 +29,35 @@ use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::process::Command; +/// Result of one command hook process, independent of where that process ran. +#[derive(Debug, Clone)] +pub enum HookProcessResult { + Completed { + exit_code: Option, + stdout: String, + stderr: String, + }, + TimedOut, + SpawnFailed(String), +} + +/// Executes a command hook in the workspace's process domain. +/// +/// The default engine path remains the local child-process implementation. +/// Remote workspaces inject a provider backed by their workspace shell so a +/// hook command, cwd, environment and stdin all stay on the target host. +#[async_trait::async_trait] +pub trait HookProcessProvider: Send + Sync { + async fn execute( + &self, + command: &str, + payload_json: &str, + cwd: &Path, + timeout: Duration, + environment: &BTreeMap, + ) -> HookProcessResult; +} + /// Cap for a single model-visible hook text (reason or context). Larger /// output is truncated with a marker, mirroring the Codex output budget. pub const MAX_HOOK_MODEL_OUTPUT_BYTES: usize = 10_000; @@ -36,15 +66,33 @@ pub const MAX_HOOK_MODEL_OUTPUT_BYTES: usize = 10_000; const MAX_CAPTURED_OUTPUT_BYTES: usize = 1024 * 1024; /// Executes configured hooks for agent lifecycle events. -#[derive(Debug, Clone, Default)] +#[derive(Clone, Default)] pub struct AgentHookEngine { registry: RuntimeHookRegistry, settings: Option>, project_hooks_disabled: bool, + remote_project_only: bool, /// Environment every command handler inherits. The host supplies what its /// own launch environment lost (a GUI launch starts without the login /// shell PATH); a handler's own options always win. environment_defaults: Arc>, + process_provider: Option>, +} + +impl std::fmt::Debug for AgentHookEngine { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AgentHookEngine") + .field("registry", &self.registry) + .field("settings", &self.settings) + .field("project_hooks_disabled", &self.project_hooks_disabled) + .field("remote_project_only", &self.remote_project_only) + .field("environment_defaults", &self.environment_defaults) + .field( + "process_provider", + &self.process_provider.as_ref().map(|_| ""), + ) + .finish() + } } impl AgentHookEngine { @@ -57,7 +105,9 @@ impl AgentHookEngine { registry, settings: Some(Arc::new(settings)), project_hooks_disabled: false, + remote_project_only: false, environment_defaults: Arc::default(), + process_provider: None, } } @@ -66,7 +116,9 @@ impl AgentHookEngine { registry, settings: None, project_hooks_disabled: false, + remote_project_only: false, environment_defaults: Arc::default(), + process_provider: None, } } @@ -98,6 +150,20 @@ impl AgentHookEngine { self } + /// Use a workspace-specific process provider for command handlers. + pub fn with_process_provider(mut self, provider: Arc) -> Self { + self.process_provider = Some(provider); + self + } + + /// Restrict command dispatch to the manually configured project layer. + /// Remote workspaces use this to keep controller user/imported handlers out + /// of the target execution domain. + pub fn with_remote_project_only(mut self, enabled: bool) -> Self { + self.remote_project_only = enabled; + self + } + pub fn is_empty(&self) -> bool { self.registry.plans().is_empty() } @@ -173,6 +239,14 @@ impl AgentHookEngine { if self.project_hooks_disabled && registration.requires_project_trust { continue; } + if self.remote_project_only + && !matches!( + registration.plan.source(), + RuntimeHookSource::ProjectCommand + ) + { + continue; + } let options = ®istration.command_options; let mapping = options .tool_mappings @@ -218,6 +292,7 @@ impl AgentHookEngine { cwd, options, mapping, + self.process_provider.as_deref(), &mut outcome, ) => result, }; @@ -430,9 +505,17 @@ impl AgentHookEngine { cwd: &Path, options: &CommandHookOptions, mapping: Option<&HookToolMapping>, + process_provider: Option<&dyn HookProcessProvider>, outcome: &mut AgentHookOutcome, ) -> (bool, bool) { - let command = handler.effective_command(); + // A remote workspace has a target shell independent of the + // controller's OS. Its project command is the portable `command` + // field; `commandWindows` is only selected for local Windows hooks. + let command = if process_provider.is_some() { + &handler.command + } else { + handler.effective_command() + }; let timeout = handler.effective_timeout(event); debug!( "Running agent hook: event={}, command={}, timeout_ms={}", @@ -440,14 +523,15 @@ impl AgentHookEngine { command, timeout.as_millis() ); - let run = run_hook_command( - command, - payload_json, - cwd, - timeout, - &self.handler_environment(options), - ) - .await; + let environment = self.handler_environment(options); + let run = match process_provider { + Some(provider) => { + provider + .execute(command, payload_json, cwd, timeout, &environment) + .await + } + None => run_hook_command(command, payload_json, cwd, timeout, &environment).await, + }; let mut succeeded = false; let finalized = match run { HookCommandRun::SpawnFailed(error) => { @@ -614,15 +698,7 @@ fn merge_handler_result(result: HookHandlerResult, outcome: &mut HookHandlerResu } } -enum HookCommandRun { - Completed { - exit_code: Option, - stdout: String, - stderr: String, - }, - TimedOut, - SpawnFailed(String), -} +type HookCommandRun = HookProcessResult; /// Grace a timed-out handler receives after `SIGTERM` before its whole process /// group is force-killed. @@ -659,11 +735,20 @@ impl Drop for HookProcessGroup { } fn hook_command(command: &str) -> Command { - if cfg!(windows) { + #[cfg(windows)] + { + // `Command::arg` applies Windows quoting to the complete command + // string. That is incorrect for `cmd /C`: embedded quotes (for + // example, the quotes around a PowerShell `-File` path) then reach + // the child as literal characters. Append the command line raw and + // use cmd's documented outer quote so ordinary shell quoting keeps + // working. let mut process = Command::new("cmd"); - process.arg("/C").arg(command); + process.arg("/C").raw_arg(format!("\"{command}\"")); process - } else { + } + #[cfg(not(windows))] + { let mut process = Command::new("sh"); process.arg("-c").arg(command); process @@ -1006,3 +1091,19 @@ mod plugin_dispatch_tests { assert_eq!(result.output, json!({"args": {}})); } } + +#[cfg(all(test, windows))] +mod windows_command_tests { + use super::hook_command; + + #[tokio::test] + async fn hook_command_preserves_embedded_quotes_for_cmd() { + let mut process = hook_command(r#"echo "hello world""#); + let output = process.output().await.expect("cmd starts"); + assert_eq!(output.status.code(), Some(0)); + + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("\"hello world\""), "stdout={stdout:?}"); + assert!(!stdout.contains("\\\"hello world\\\""), "stdout={stdout:?}"); + } +} diff --git a/src/crates/execution/agent-runtime/src/native_hooks/mod.rs b/src/crates/execution/agent-runtime/src/native_hooks/mod.rs index f823d16ac4..68783f3fdb 100644 --- a/src/crates/execution/agent-runtime/src/native_hooks/mod.rs +++ b/src/crates/execution/agent-runtime/src/native_hooks/mod.rs @@ -35,7 +35,10 @@ mod settings; #[cfg(feature = "native-hook-runtime")] pub use call::{HookCall, HookCallPayload}; #[cfg(feature = "native-hook-runtime")] -pub use engine::{AgentHookEngine, PluginHookDispatchResult, MAX_HOOK_MODEL_OUTPUT_BYTES}; +pub use engine::{ + AgentHookEngine, HookProcessProvider, HookProcessResult, PluginHookDispatchResult, + MAX_HOOK_MODEL_OUTPUT_BYTES, +}; #[cfg(feature = "native-hook-runtime")] pub use handler::{ BuiltinHookExecutor, CommandHookOptions, HookHandler, HookHandlerResult, HookInputAdapter, diff --git a/src/crates/execution/agent-runtime/tests/native_hook_execution_contracts.rs b/src/crates/execution/agent-runtime/tests/native_hook_execution_contracts.rs index 9837bbf33e..b41ab35a12 100644 --- a/src/crates/execution/agent-runtime/tests/native_hook_execution_contracts.rs +++ b/src/crates/execution/agent-runtime/tests/native_hook_execution_contracts.rs @@ -9,14 +9,18 @@ #![cfg(unix)] #![cfg(feature = "native-hook-runtime")] +use async_trait::async_trait; use openbitfun_agent_runtime::native_hooks::{ AgentHookEngine, AgentHookEventPayload, AgentHookOutcome, AgentHookPayload, AgentHookPayloadCommon, AgentHookPermissionMode, AgentHookPermissionOutcome, AgentHookScope, - AgentHookSettings, AgentHookSettingsLayer, CommandHookOptions, RuntimeHookRegistry, - MAX_HOOK_MODEL_OUTPUT_BYTES, + AgentHookSettings, AgentHookSettingsLayer, CommandHookOptions, HookProcessProvider, + HookProcessResult, RuntimeHookRegistry, MAX_HOOK_MODEL_OUTPUT_BYTES, }; use serde_json::json; +use std::collections::BTreeMap; use std::path::Path; +use std::sync::Arc; +use std::time::Duration; fn engine(hooks_json: &str) -> AgentHookEngine { let (settings, issues) = AgentHookSettings::from_layers(&[AgentHookSettingsLayer { @@ -66,6 +70,45 @@ async fn dispatch(engine: &AgentHookEngine, payload: &AgentHookPayload) -> Agent engine.dispatch(payload, Path::new(".")).await } +#[derive(Debug)] +struct TargetProcessProvider; + +#[async_trait] +impl HookProcessProvider for TargetProcessProvider { + async fn execute( + &self, + _command: &str, + payload_json: &str, + _cwd: &Path, + _timeout: Duration, + _environment: &BTreeMap, + ) -> HookProcessResult { + let payload: serde_json::Value = serde_json::from_str(payload_json).unwrap(); + assert_eq!(payload["hook_event_name"], "PreToolUse"); + HookProcessResult::Completed { + exit_code: Some(0), + stdout: r#"{"hookSpecificOutput":{"hookEventName":"PreToolUse","updatedInput":{"command":"target-side"}}}"#.to_string(), + stderr: String::new(), + } + } +} + +#[tokio::test] +async fn injected_process_provider_runs_hooks_outside_the_controller_process() { + let engine = engine( + r#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"ignored-by-provider"}]}]}}"#, + ) + .with_process_provider(Arc::new(TargetProcessProvider)); + let outcome = dispatch(&engine, &pre_tool_use_payload("Bash")).await; + + assert_eq!( + outcome.updated_input, + Some(json!({"command": "target-side"})) + ); + assert_eq!(outcome.executed_handlers, 1); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); +} + #[tokio::test] async fn payload_is_delivered_on_stdin() { // `cat` echoes the payload JSON, which parses as a decision document with diff --git a/src/crates/services/services-integrations/src/remote_ssh/workspace_services.rs b/src/crates/services/services-integrations/src/remote_ssh/workspace_services.rs index 66f9b07e4b..d28bee0fab 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/workspace_services.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/workspace_services.rs @@ -9,10 +9,13 @@ use openbitfun_runtime_ports::{ WorkspaceCommandOptions, WorkspaceCommandResult, WorkspaceDirEntry, WorkspaceFileSystem, WorkspacePathKind, WorkspaceServices, WorkspaceShell, }; +use std::collections::BTreeMap; use std::sync::Arc; #[cfg(feature = "remote-ssh-concrete")] use std::time::SystemTime; use std::time::{Duration, UNIX_EPOCH}; +#[cfg(feature = "remote-ssh-concrete")] +use tokio::io::{AsyncReadExt, AsyncWriteExt}; use super::{ RemoteFileEntry, RemoteFileService, SSHCommandOptions, SSHCommandResult, SSHConnectionManager, @@ -415,6 +418,93 @@ impl WorkspaceShell for RemoteWorkspaceShell { Ok(workspace_result_from_ssh(result)) } + + async fn exec_with_stdin( + &self, + command: &str, + stdin_payload: &[u8], + environment: &BTreeMap, + options: WorkspaceCommandOptions, + ) -> anyhow::Result { + #[cfg(not(feature = "remote-ssh-concrete"))] + { + let _ = (command, stdin_payload, environment, options); + anyhow::bail!("remote workspace stdin execution is unavailable without SSH support") + } + #[cfg(feature = "remote-ssh-concrete")] + { + let command = remote_workspace_command( + &self.workspace_root, + &remote_hook_command(command, environment), + ); + let stdio = if let Some(timeout_ms) = options.timeout_ms { + match tokio::time::timeout( + Duration::from_millis(timeout_ms), + self.ssh_manager + .open_workspace_stdio(&self.connection_id, &command), + ) + .await + { + Ok(result) => result?, + Err(_) => { + return Ok(WorkspaceCommandResult { + stdout: String::new(), + stderr: String::new(), + exit_code: 124, + interrupted: false, + timed_out: true, + }); + } + } + } else { + self.ssh_manager + .open_workspace_stdio(&self.connection_id, &command) + .await? + }; + let (mut stdin, mut stdout, mut stderr, control, completion) = stdio.into_parts(); + let payload = stdin_payload.to_vec(); + let interaction = async move { + stdin.write_all(&payload).await?; + stdin.shutdown().await?; + let (stdout, stderr, completion) = tokio::join!( + async { + let mut bytes = Vec::new(); + stdout.read_to_end(&mut bytes).await.map(|_| bytes) + }, + async { + let mut bytes = Vec::new(); + stderr.read_to_end(&mut bytes).await.map(|_| bytes) + }, + completion.wait(), + ); + Ok::<_, anyhow::Error>((stdout?, stderr?, completion.exit_code)) + }; + let result = if let Some(timeout_ms) = options.timeout_ms { + match tokio::time::timeout(Duration::from_millis(timeout_ms), interaction).await { + Ok(result) => result?, + Err(_) => { + let _ = control.kill().await; + return Ok(WorkspaceCommandResult { + stdout: String::new(), + stderr: String::new(), + exit_code: 124, + interrupted: false, + timed_out: true, + }); + } + } + } else { + interaction.await? + }; + Ok(WorkspaceCommandResult { + stdout: bounded_hook_output(result.0), + stderr: bounded_hook_output(result.1), + exit_code: result.2.unwrap_or(-1), + interrupted: false, + timed_out: false, + }) + } + } } /// Build [`WorkspaceServices`] backed by SSH for a remote workspace. @@ -438,6 +528,40 @@ fn remote_workspace_command(workspace_root: &str, command: &str) -> String { shell::cd_and(workspace_root, command) } +#[cfg(feature = "remote-ssh-concrete")] +fn remote_hook_command(command: &str, environment: &BTreeMap) -> String { + if environment.is_empty() { + return command.to_string(); + } + let mut prefix = String::new(); + for (key, value) in environment { + if key.is_empty() + || !key.chars().enumerate().all(|(index, ch)| { + ch == '_' || ch.is_ascii_alphanumeric() && (index > 0 || ch.is_ascii_alphabetic()) + }) + { + continue; + } + prefix.push_str("export "); + prefix.push_str(key); + prefix.push('='); + prefix.push_str(&shell::quote_arg(value)); + prefix.push_str("; "); + } + format!("{prefix}{command}") +} + +#[cfg(feature = "remote-ssh-concrete")] +fn bounded_hook_output(bytes: Vec) -> String { + const MAX_CAPTURED_OUTPUT_BYTES: usize = 1024 * 1024; + let bytes = if bytes.len() > MAX_CAPTURED_OUTPUT_BYTES { + &bytes[..MAX_CAPTURED_OUTPUT_BYTES] + } else { + &bytes + }; + String::from_utf8_lossy(bytes).into_owned() +} + fn workspace_result_from_ssh(result: SSHCommandResult) -> WorkspaceCommandResult { WorkspaceCommandResult { stdout: result.stdout,