Overview
The Stream interface and utilities enable bidirectional communication between ACP clients and agents. Streams handle the serialization and deserialization of JSON-RPC messages over various transport layers.Stream Interface
- Receives JSON-RPC messages through the
readablestream - Sends JSON-RPC messages through the
writablestream
Properties
writable
readable
ndJsonStream
output(WritableStream<Uint8Array>) - The writable stream to send encoded messages toinput(ReadableStream<Uint8Array>) - The readable stream to receive encoded messages from
How It Works
ThendJsonStream function:
-
Encoding (Writable Stream):
- Takes
AnyMessageobjects - Serializes them to JSON
- Appends a newline character
- Encodes as UTF-8 bytes
- Writes to the output stream
- Takes
-
Decoding (Readable Stream):
- Reads UTF-8 bytes from the input stream
- Buffers incomplete lines
- Splits on newline characters
- Parses each line as JSON
- Emits
AnyMessageobjects
Error Handling
The function handles errors gracefully:- Parse errors: Logged to console but don’t stop the stream
- Empty lines: Silently skipped
- Incomplete messages: Buffered until complete
Usage Examples
Creating a Stream from stdin/stdout (Node.js)
Creating a Stream from stdin/stdout (Deno)
Creating a Stream from WebSockets
Creating a Custom Stream Implementation
For custom transport layers, you can create Stream objects directly without usingndJsonStream:
Testing with In-Memory Streams
Stream Lifecycle
Connection Establishment
- Create a Stream with your transport layer
- Pass the Stream to
AgentSideConnectionorClientSideConnection - The connection automatically starts reading from the stream
Message Flow
Connection Closure
The connection closes when:- The readable stream ends (remote peer disconnected)
- An unrecoverable error occurs
- You explicitly close the underlying transport
Best Practices
1. Use ndJsonStream for stdio
For most use cases with stdin/stdout,ndJsonStream is the recommended approach:
2. Handle Transport Errors
Ensure your transport layer handles errors gracefully:3. Clean Up Resources
Close streams and connections when done:4. Buffer Management
Be mindful of buffering when implementing custom streams:See Also
- AgentSideConnection - Agent connection class
- ClientSideConnection - Client connection class
- JSON-RPC Types - Message type definitions
- Web Streams API - MDN documentation