You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: codex-rs/acp/docs.md
+9-133Lines changed: 9 additions & 133 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,114 +2,20 @@
2
2
3
3
Path: @/codex-rs/acp
4
4
5
-
###Overview
5
+
## Overview
6
6
7
7
- Implements Agent Context Protocol (ACP) for Codex to communicate with external AI agent subprocesses
8
-
- Uses the official `agent-client-protocol` v0.7 library instead of custom JSON-RPC implementation
9
-
- Includes `AcpModelClient` for high-level streaming interaction with ACP agents
10
-
- Manages agent lifecycle, initialization handshake, and stderr capture for diagnostic logging
8
+
- Uses the official `agent-client-protocol` v0.7 library instead of any custom JSON-RPC implementation
11
9
- Exports `init_file_tracing()` for file-based structured logging at DEBUG level
12
-
-**Critical**: All ACP operations use !Send futures from `agent-client-protocol`, requiring `LocalSet` contexts
13
10
14
11
### How it fits into the larger codebase
15
12
16
-
- Used by `@/codex-rs/core/src/client.rs` to spawn and communicate with ACP-compliant agents via `WireApi::Acp` variant
17
-
-`AcpModelClient` is designed to mirror the `ModelClient` interface for future core integration
18
-
- Enables Codex to delegate AI operations to external providers (Claude, Gemini, etc.) that implement the ACP specification
19
-
- Complements the existing OpenAI-style API path in core by providing an alternative subprocess-based agent model
13
+
- Used by `@/codex-rs/core/src/client.rs` to communicate with ACP-compliant agents via `WireApi::Acp` variant
20
14
- Uses channel-based streaming pattern (mpsc) consistent with core's `ResponseStream`
21
15
- Provides structured error handling via library's typed error responses that core translates to user-facing messages
22
16
- TUI and other clients can access captured stderr for displaying agent diagnostic output
23
-
- Re-exports commonly used types from `agent-client-protocol` library for convenience (`Agent`, `Client`, `ClientSideConnection`, request/response types)
24
17
25
-
### Core Implementation
26
-
27
-
**High-Level API:**`AcpModelClient::stream()` in `@/codex-rs/acp/src/acp_client.rs`
28
-
29
-
- Encapsulates the full flow: spawn, initialize, session/new, session/prompt, stream notifications, complete
30
-
- Returns an `AcpStream` implementing the futures `Stream` trait for async iteration
31
-
- Events are delivered via `AcpEvent` enum: `TextDelta`, `ReasoningDelta`, `Completed`, `Error`
32
-
- Uses mpsc channel (capacity 16) for backpressure-aware event delivery
33
-
-**Spawns dedicated thread with LocalSet** because agent-client-protocol futures are !Send
34
-
35
-
**Low-Level Entry Point:**`AgentProcess::spawn()` in `@/codex-rs/acp/src/agent.rs`
36
-
37
-
- Creates a tokio subprocess with piped stdin/stdout/stderr
38
-
- Wraps stdio streams with tokio-util compat layer to bridge tokio's AsyncRead/Write with futures crate traits
39
-
- Creates `ClientSideConnection` from agent-client-protocol library, passing `spawn_local` callback for !Send futures
40
-
- Spawns detached tokio task to asynchronously read stderr lines into a thread-safe buffer
41
-
- Returns `AgentProcess` wrapping the connection, child process, and event channels
42
-
43
-
**Protocol Flow (via AcpModelClient and Library):**
-`TokioAsyncReadCompatExt::compat()` and `TokioAsyncWriteCompatExt::compat_write()` convert between them
100
-
- Applied to child process stdin/stdout before passing to ClientSideConnection
101
-
102
-
**Client Callback Architecture:**
103
-
104
-
Agent callbacks are handled through a channel-based forwarding pattern:
105
-
-`AcpClientHandler` implements the `Client` trait from agent-client-protocol
106
-
- Callbacks (`request_permission`, `session_notification`) forward to mpsc channel as `ClientEvent` enum
107
-
-`AgentProcess::next_client_event()` exposes the receiver for consuming callbacks
108
-
-`AcpModelClient` processes `ClientEvent::SessionUpdate` to emit `AcpEvent::{TextDelta, ReasoningDelta}`
109
-
- Permission requests currently auto-cancel (TODO: implement proper permission handling)
110
-
- File operations and terminal operations return `method_not_found` errors
111
-
112
-
**Model Registry and Lookup Architecture:**
18
+
### Model Registry
113
19
114
20
The ACP registry in `@/codex-rs/acp/src/registry.rs` is **model-centric** rather than provider-centric:
115
21
-`get_agent_config()` accepts model names (e.g., "mock-model", "gemini-flash-2.5") instead of provider names
@@ -122,33 +28,15 @@ The ACP registry in `@/codex-rs/acp/src/registry.rs` is **model-centric** rather
122
28
- Uses exact matching only (no prefix matching) - each model must be explicitly registered
123
29
- The `provider` field enables future optimization to determine when existing subprocess can be reused vs when new one must be spawned when switching models
124
30
125
-
**Session Lifecycle:**
126
-
127
-
Each `AcpModelClient::stream()` call spawns a fresh agent process:
128
-
- Agent is initialized with hardcoded capabilities: `fs.readTextFile`, `fs.writeTextFile`, `terminal`
129
-
- Session created via `session/new` with `cwd` and empty `mcpServers`
130
-
- Prompt sent via `session/prompt` with text content block format
131
-
- Library's `Agent::prompt()` returns when final response received; session updates arrive via Client callbacks
132
-
- Agent is killed after stream completes or errors
133
31
134
-
**Typed Request/Response Pattern:**
32
+
### Stderr Capture Implementation
135
33
136
-
The agent-client-protocol library provides typed request/response structs:
137
-
-`InitializeRequest`/`InitializeResponse` - Protocol handshake with capability negotiation
138
-
-`NewSessionRequest`/`NewSessionResponse` - Session creation with cwd and MCP servers
139
-
-`PromptRequest`/`PromptResponse` - Prompt submission with content blocks
140
-
-`SessionNotification` - Async notifications for session updates (agent message/thought chunks)
141
-
- Eliminates manual JSON-RPC message construction and parsing
142
-
- Provides compile-time type safety for protocol conformance
143
-
144
-
**Stderr Capture Implementation:**
145
-
146
-
- Buffer uses `Arc<Mutex<Vec<String>>>` for thread-safe access between reader task and caller
34
+
- Buffer lines per session for access between reader task and caller
147
35
- Bounded at 500 lines with FIFO eviction when full
148
36
- Individual lines truncated to 10KB
149
37
- Reader task runs until EOF or error, logging warnings via tracing
150
38
151
-
**File-Based Tracing:**
39
+
### File-Based Tracing
152
40
153
41
The `init_file_tracing()` function in `@/codex-rs/acp/src/tracing_setup.rs` provides structured file logging:
154
42
- Sets global tracing subscriber that writes to a user-specified file path
@@ -160,20 +48,8 @@ The `init_file_tracing()` function in `@/codex-rs/acp/src/tracing_setup.rs` prov
160
48
- ANSI colors disabled for clean file output
161
49
- Automatically initialized by the CLI (`@/codex-rs/cli/src/main.rs`) at startup, writing to `.codex-acp.log` in the current working directory
162
50
163
-
**Test coverage:**
164
-
165
-
- Thin slice integration tests in `@/codex-rs/acp/tests/thin_slice.rs` verify end-to-end streaming with mock agent, wrapped in LocalSet
166
-
- Unit tests in `agent.rs` use shell commands to test stderr capture, buffer overflow, and line truncation - all wrapped in LocalSet
167
-
- Integration tests in `@/codex-rs/acp/tests/integration.rs` test protocol handshake with typed requests/responses from library
168
-
- Tracing integration test in `@/codex-rs/acp/tests/tracing_test.rs` validates file creation, log level filtering, and re-initialization error handling
169
-
- TUI black-box tests in `@/codex-rs/tui-integration-tests` exercise full application flow including ACP protocol
0 commit comments