8000 feat(acp): ACP client — external agents as first-class agent ids (Track 62) by stpinkie · Pull Request #8 · stpinkie/rhizome · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions .todo.md
33 changes: 30 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,14 @@ system (first tenant: the Helios Ethereum light node), Agent Client Protocol
- [x] Verified: unit tests (`pkg/acp` fake runner/conn + real `EventBus`), and a real stdio smoke — `initialize`/`session/new`/`session/prompt` against a fake SSE OpenAI endpoint produced three `agent_message_chunk` notifications + `stopReason:"end_turn"` with a clean stdout protocol stream.

### Track 62 — ACP client (external agents as first-class agent ids)
- [ ] `pkg/acp` client: spawn per `agents.list[].acp = {command, args, env, cwd}`; `initialize` (clientCapabilities: `fs` read/write routed through `restrict_to_workspace` sandbox; `terminal` declared unsupported); `session/new` per delegation; `session/prompt` → collect `session/update` → final text; cancel on ctx done.
- [ ] `AgentConfig.ACP *ACPAgentConfig` binding; registry marks the id external; new `ACPSpawner` in the `SubTurnSpawner` chain routes ACP-bound ids *before* local dispatch — `hasLocal` stays true so `mesh.RemoteSpawner` never routes them off-box. `delegate`, `spawn`, `subagent`, `network route`, `swarm offer --require-agent` all work unchanged. **Also needed** (found in planning): remote peers delegate via `runFunc`→`agentLoop.ProcessRemoteDispatch`, which bypasses the spawner chain — add an `ExternalAgentRunner` seam on the loop so ACP-bound ids resolve to the ACP client there too.
- [ ] `acp_run` tool — explicit one-off invocation of a configured ACP agent (escape hatch).
- [ ] External `session/request_permission` → `acp.client.permission_policy`: `deny` (default) | `allow-read-only` | `allow`.
- [ ] Manifests advertise ACP-bound agents like locals (peer-bound to the host); remote peers can delegate into them under existing ACL.
- [x] `pkg/acp/client.go` — `ClientManager` spawns per `agents.list[].acp = {command, args, env, cwd}` via plain `exec.Command` (documented trust posture: un-sandboxed child; safety = sandboxed fs bridge + permission policy). Lazy spawn, process reuse, respawn on dead conn, `Close()` on gateway shutdown (`services.ACPManager`). `initialize` advertises `fs:{readTextFile,writeTextFile}` + `terminal:false`; `session/new` per delegation (mcpServers must be `[]`, not nil — SDK validates); `session/prompt` → accumulate chunks → final text; ctx cancel → SDK sends `session/cancel`; `session/close` best-effort.
- [x] `pkg/acp/client_handler.go` — `acpsdk.Client` impl: `SessionUpdate` collects `agent_message_chunk`+`agent_thought_chunk` text; `fs/read_text_file`+`fs/write_text_file` served via `toolfs.ValidatePathWithAllowPaths` (new exported `CompilePatterns`) under `restrict_to_workspace` + allow_*_paths, 64 KiB read cap; `terminal/*` → method-not-found.
- [x] `AgentConfig.ACP *ACPAgentConfig` → `AgentInstance.ACP`; `acp.Spawner` (`tools.SubTurnSpawner`) inserted remote→**acp**→local in gateway.go — `hasLocal` stays true for ACP ids so `mesh.RemoteSpawner` never routes them off-box; also set as the loop's spawner when mesh is off. Prompt = `SubTurnConfig.SystemPrompt` + user `InitialMessages` (where delegate/subagent put the task).
- [x] `ExternalAgentRunner` seam (`AgentLoop.SetExternalAgentRunner`) intercepts `ProcessRemoteDispatch` for `inst.ACP != nil` — remote peers delegating into ACP ids hit the client instead of silently running local inference. Registry resolved lazily (`func() *AgentRegistry`) since reload swaps it.
- [x] `acp_run` tool (`pkg/tools/acp_run.go`) — `tools.ACPInvoker` interface keeps the SDK out of pkg/tools; registered only when `SetACPInvoker` was called (≥1 acp-bound agent).
- [x] `acp.client.permission_policy`: `deny` (default — reject option selected, else cancelled outcome) | `allow-read-only` (read/search/think/fetch kinds; `writeTextFile` also unadvertised+refused) | `allow`. Auth: `authMethods` advertised at initialize → clear error (env-carry credentials instead).
- [x] Manifests advertise ACP-bound agents automatically (registry membership is all that takes).
- [x] Tests: `client_test.go` — io.Pipe mock agent over the real SDK transport (streamed text, stop-reason mapping, per-policy permission outcomes, fs sandbox allow/deny, process reuse) **plus a real-process E2E** (`TestHelperProcess` re-exec of the test binary over stdio through the actual `spawn()` path).

### Track 63 — Mesh observability (data + panels)
- [ ] `PeerStatus` extensions: `conns[]` {remote_multiaddr, direction, transport (detect `/p2p-circuit`, quic/tcp), stream count, opened_at}, `latency_ms` (peerstore `LatencyEWMA`), `score` {successes, failures, avg_latency_ms, last_error, score} from `PeerScoreStore`, `last_seen`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,10 +215,37 @@ Rhizome as an editor agent). `pkg/acp` contains all
carried on the exec payloads.
- **Permissions**: `acp.server.permission_policy` = `prompt` (default:
`session/request_permission` per tool call, `*_always` cached per
session, failures deny) | `allow` | `deny`. Client policy
`acp.client.permission_policy` is reserved for the Track 62 ACP client.
session, failures deny) | `allow` | `deny`.
- See `docs/guides/acp.md` for Zed `agent_servers` / JetBrains setup.

### ACP client (external agents)

`agents.list[].acp = {command, args, env, cwd}` binds an external ACP
agent (`gemini --acp`, `claude-code acp`, …) to a routable agent id:

- `AgentInstance.ACP` marks the binding; `pkg/acp.ClientManager` lazily
spawns the child process (plain `exec.Command` — NOT `pkg/isolation`;
trust posture documented in the guide), handshakes `initialize`
(`fs:{read,write}` + `terminal:false`), and runs one `session/new` +
`session/prompt` per delegation, accumulating `session/update` chunks.
- Spawner chain in `pkg/gateway`: `RemoteSpawner` → `acp.Spawner` → local
`AgentLoopSpawner`. `hasLocal(id)` is true for ACP ids (registry
membership) so they never route off-box. Without mesh, `acp.Spawner` is
installed directly.
- Remote peers delegating into an ACP id go through
`AgentLoop.SetExternalAgentRunner` (`ClientManager.RunRemote`) —
`ProcessRemoteDispatch` bypasses the spawner chain, so the seam lives
on the loop.
- `acp_run` tool invokes an ACP id explicitly (`tools.ACPInvoker`
interface keeps the SDK out of pkg/tools).
- `acp.client.permission_policy` = `deny` (default) | `allow-read-only` |
`allow` answers the external agent's `session/request_permission`;
`fs/*` requests are served through the workspace sandbox
(`restrict_to_workspace` + `tools.allow_*_paths`); `terminal/*` is
refused. `authMethods` advertised at initialize → clear error.
- Registry is resolved lazily (`func() *AgentRegistry`) in both the
manager and spawner — reload swaps the registry pointer.

## Web Backend Network API

The web console (the launcher) exposes authenticated JSON endpoints that wrap `rhizome network status` so the dashboard can display live mesh/DHT status:
Expand Down Expand Up @@ -246,7 +273,7 @@ Both endpoints require a valid node identity and use the launcher's `RHIZOME_HOM

- `pkg/browser` — pluggable browser-automation backends (catalog, `AgentBrowserDriver` CLI wrapper, endpoint resolvers, session manager, Cloudflare REST); `pkg/tools/browser` exposes the eight `browser_*` agent tools.
- `pkg/modules` — companion-module sidecar system (catalog, sha256-verified install, daemon supervision with restart backoff, bounded logs, `module.*` events); `cmd/rhizome/internal/module` exposes the `rhizome module` CLI, `pkg/gateway/moduleapi.go` the `/modules*` daemon endpoints, `web/backend/api/modules.go` the `/api/modules*` launcher routes.
- `pkg/acp` — ACP (Agent Client Protocol) server bridge: `rhizome acp` exposes the agent loop to editor clients over stdio JSON-RPC via `coder/acp-go-sdk` (all SDK usage isolated here). Sessions map to `agent:<id>:acp:<sid>` keys on channel `acp` through `AgentLoop.ProcessInbound`; streaming via a `bus.StreamDelegate`; tool approvals bridge to `session/request_permission`.
- `pkg/acp` — ACP (Agent Client Protocol) both ways, all `coder/acp-go-sdk` usage isolated here: **server** (`rhizome acp` exposes the agent loop to editor clients over stdio JSON-RPC; sessions map to `agent:<id>:acp:<sid>` keys on channel `acp` through `AgentLoop.ProcessInbound`; streaming via a `bus.StreamDelegate`; tool approvals bridge to `session/request_permission`) and **client** (`ClientManager` spawns `agents.list[].acp` external agents; `Spawner` intercepts ACP-bound `SubTurn` targets; `RunRemote` backs `ExternalAgentRunner` for mesh dispatch; sandboxed `fs/*` serving + `acp.client.permission_policy` for permission requests).
- `pkg/redact` — leaf package for secret masking (generic patterns + configured `SecureString` values); used by `pkg/logger` and `Config.FilterSensitiveData`.
- `pkg/guard` — leaf package for prompt-injection phrase detection; used by shell-command screening, the tool-argument scan, and CLI tool-call extraction.
- `pkg/rhizome/identity` — BIP39/SLIP-0010 Ed25519 node identity, persistence, and Ed25519 signing; now supports OS keyring and passphrase encryption.
Expand Down
28 changes: 18 additions & 10 deletions docs/design/v0.10.0-sprint.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,16 +166,23 @@ Editors (Zed, JetBrains) drive Rhizome over stdio JSON-RPC.
`agents.list[].acp = {command, args, env, cwd}` binds an external ACP agent
(`gemini --acp`, `claude-code acp`, …) as a routable agent id.

- `pkg/acp/client.go` — spawn via plain `exec.Command` (not `pkg/isolation`;
the external agent needs its own fs/env — document the trust posture);
`initialize` advertises `fs:{readTextFile,writeTextFile}` served by us
through the workspace sandbox (`restrict_to_workspace` + whitelists) and
`terminal:false`; `session/new` per delegation; `session/prompt` →
accumulate `session/update` → final text; cancel on ctx done.
- `pkg/acp/client.go` — `ClientManager` owns per-agent processes spawned via
plain `exec.Command` (not `pkg/isolation`; the external agent needs its own
fs/env — trust posture documented in the guide); `initialize` advertises
`fs:{readTextFile,writeTextFile}` served by us through the workspace
sandbox (`restrict_to_workspace` + allow_*_paths) and `terminal:false`;
`session/new` per delegation; `session/prompt` → accumulate
`session/update` → final text; `session/cancel` on ctx done; process reuse
across delegations, respawn on connection loss.
- `pkg/acp/client_handler.go` — `acpsdk.Client` impl: streamed-text
accumulation, sandboxed fs serving, permission-policy evaluation, terminal
refusal. Registry/config resolved lazily (registry swaps on reload).
- External `session/request_permission` → `acp.client.permission_policy` =
`deny`(default)|`allow-read-only`|`allow`.
- `pkg/acp/spawner.go` — `ACPSpawner implements tools.SubTurnSpawner`; chain
in `pkg/gateway/gateway.go`: `remoteSpawner` → `acpSpawner` → `local`.
`deny`(default)|`allow-read-only`|`allow` (read->
fetch tool kinds; `fs/write_text_file` is not advertised under it).
- `pkg/acp/spawner.go` — `Spawner implements tools.SubTurnSpawner`; chain
in `pkg/gateway/gateway.go`: `remoteSpawner` → `acpSpawner` → `local`
(or `acpSpawner` → `local` when mesh is off).
`remoteSpawner.hasLocal(id)` stays true for ACP-bound ids (they're in the
registry) so they never route off-box.
- **Correction to the draft:** remote peers delegate via `runFunc` →
Expand All @@ -184,7 +191,8 @@ Editors (Zed, JetBrains) drive Rhizome over stdio JSON-RPC.
ACP-bound ids resolve to the ACP client on that path too — otherwise remote
delegation to an ACP id silently falls to local dispatch and fails.
- `pkg/tools/acp_run.go` — explicit one-off invocation of a configured ACP
agent id (escape hatch).
agent id (escape hatch); registered only when a `tools.ACPInvoker` is
installed on the loop.
- Manifests advertise ACP-bound agents like locals (peer-bound to the host);
remote peers delegate into them under existing ACL.
- Tests use a mock ACP stdio agent built on the same SDK (Track 61's server
Expand Down
89 changes: 86 additions & 3 deletions docs/guides/acp.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
# ACP — Agent Client Protocol

Rhizome can act as an [ACP](https://agentclientprotocol.com) agent, so editors
such as **Zed** and **JetBrains IDEs** can drive your Rhizome agents directly
— with streamed responses, tool-call progress, and permission prompts.
Rhizome speaks [ACP](https://agentclientprotocol.com) in both directions:

- **Server** — `rhizome acp` lets editors such as **Zed** and **JetBrains
IDEs** drive your Rhizome agents directly, with streamed responses,
tool-call progress, and permission prompts.
- **Client** — `agents.list[].acp` binds an external ACP agent
(`gemini --acp`, `claude-code acp`, …) to a Rhizome agent id, so it can
be delegated to like any local agent.

`rhizome acp` speaks newline-delimited JSON-RPC over **stdio**. The editor
spawns it as a subprocess; prompts run through the normal Rhizome agent
Expand Down Expand Up @@ -83,3 +88,81 @@ stdout carries the protocol, so console logging is always disabled inside
```bash
RHIZOME_LOG_FILE=~/.rhizome/acp.log rhizome acp
```

---

## External ACP agents (Rhizome as client)

Bind an external ACP-capable agent to a Rhizome agent id:

```json
{
"agents": {
"list": [
{
"id": "gemini",
"acp": {
"command": "gemini",
"args": ["--acp"],
"env": { "GEMINI_API_KEY": "..." },
"cwd": "D:\\work\\project"
}
}
]
}
}
```

The bound id is routable like any other agent:

- `delegate`/`subagent`/`spawn` tools can target it (subject to the usual
`subagents.allow_agents` rules).
- Trusted mesh peers can delegate into it — the node advertises it in its
capability manifest and the dispatch is served by the local ACP client
(the agent never routes off-box by accident: the mesh checker treats
ACP-bound ids as local).
- The `acp_run` tool invokes it explicitly.

### Lifecycle

The external process is spawned lazily on first use and reused across
delegations; each delegation creates a fresh `session/new` (prompt text
only — media attachments are dropped with a warning). On gateway shutdown
the processes are terminated.

### What the external agent can do

Rhizome answers client-bound ACP requests like this:

| Capability | Behaviour |
| ---------------------- | ------------------------------------------------------------------------------------------ |
| `fs/read_text_file` | Served through the workspace sandbox (`agents.defaults.restrict_to_workspace` + `tools.allow_read_paths`), 64 KiB cap. |
| `fs/write_text_file` | Served through the same sandbox (`tools.allow_write_paths`); **disabled** under `allow-read-only`. |
| `session/request_permission` | Answered by `acp.client.permission_policy` (below). |
| `terminal/*` | Not supported (`terminal:false`); rhizome never proxies shells into external agents. |

```json
{
"acp": {
"client": { "permission_policy": "deny" }
}
}
```

| Policy | Behaviour |
| ----------------- | --------------------------------------------------------------------- |
| `deny` | *(default)* reject every permission request. |
| `allow-read-only` | allow `read`/`search`/`think`/`fetch` tool kinds; reject the rest. |
| `allow` | allow every permission request. |

Authentication: if the external agent advertises `authMethods` during
`initialize`, the connection fails — Rhizome does not perform ACP auth.
Give the agent its credentials via `env` instead.

### Trust posture

The external agent runs as a **plain child process** with its own
filesystem and environment — it is not sandboxed by `pkg/isolation`.
Rhizome's controls are the sandboxed fs bridge and the permission policy.
Treat an `acp` binding with the same trust you'd give running that agent's
CLI yourself.
Loading
Loading
0