| 1 | package opencode |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "sync" |
| 10 | ) |
| 11 | |
| 12 | // Client speaks the Agent Client Protocol to `opencode acp`: JSON-RPC 2.0 |
| 13 | // messages, one per line (LF), on the process's stdin and stdout. It |
| 14 | // frames and bounds; routing is the session's: every message read is in |
| 15 | // Messages, in order, and the one reader hands each back with Release. |
| 16 | // Writes go through one writer goroutine and a bounded queue, and |
| 17 | // Shutdown ends both directions however full they are (security round |
| 18 | // findings 5 and 7). |
| 19 | type Client struct { |
| 20 | w io.Writer |
| 21 | writes chan write |
| 22 | done chan struct{} |
| 23 | once sync.Once |
| 24 | |
| 25 | mu sync.Mutex |
| 26 | closed bool |
| 27 | |
| 28 | // Messages are every message OpenCode sends, in order; closed when |
| 29 | // its stdout ends, a message is over the size limit, or Shutdown. |
| 30 | Messages <-chan []byte |
| 31 | |
| 32 | // queued is how many bytes of Messages are taken and not released; |
| 33 | // the client stops reading OpenCode's stdout while they are over |
| 34 | // budget. |
| 35 | qmu sync.Mutex |
| 36 | qcond *sync.Cond |
| 37 | queued int |
| 38 | budget int |
| 39 | } |
| 40 | |
| 41 | // write is one queued line and where its outcome goes. |
| 42 | type write struct { |
| 43 | line []byte |
| 44 | done chan error |
| 45 | } |
| 46 | |
| 47 | // ErrClosed: OpenCode's stdout ended, or the client was shut down. |
| 48 | var ErrClosed = errors.New("opencode: the process ended") |
| 49 | |
| 50 | // maxMessage bounds one message (a tool's output can be large); |
| 51 | // maxQueued bounds the bytes waiting in the client; maxPendingWrites |
| 52 | // bounds the writes waiting for OpenCode to read its stdin. |
| 53 | const ( |
| 54 | maxMessage = 8 << 20 |
| 55 | maxQueued = 16 << 20 |
| 56 | maxPendingWrites = 32 |
| 57 | ) |
| 58 | |
| 59 | // NewClient reads r until it ends. |
| 60 | func NewClient(r io.Reader, w io.Writer) *Client { |
| 61 | return newClientLimits(r, w, maxMessage, maxQueued) |
| 62 | } |
| 63 | |
| 64 | func newClientLimits(r io.Reader, w io.Writer, message, queued int) *Client { |
| 65 | messages := make(chan []byte, 256) |
| 66 | c := &Client{w: w, writes: make(chan write, maxPendingWrites), done: make(chan struct{}), Messages: messages, budget: queued} |
| 67 | c.qcond = sync.NewCond(&c.qmu) |
| 68 | go func() { |
| 69 | defer close(messages) |
| 70 | defer c.fail() |
| 71 | s := bufio.NewScanner(r) |
| 72 | s.Buffer(make([]byte, 0, min(64<<10, message)), message) |
| 73 | for s.Scan() { |
| 74 | line := append([]byte(nil), s.Bytes()...) |
| 75 | if len(line) == 0 { |
| 76 | continue |
| 77 | } |
| 78 | if !c.take(len(line)) { |
| 79 | return |
| 80 | } |
| 81 | select { |
| 82 | case messages <- line: |
| 83 | case <-c.done: |
| 84 | return |
| 85 | } |
| 86 | } |
| 87 | }() |
| 88 | go c.writer() |
| 89 | return c |
| 90 | } |
| 91 | |
| 92 | // writer writes the queued lines in order until Shutdown. A write |
| 93 | // OpenCode never reads holds only this goroutine, until the pipe closes. |
| 94 | func (c *Client) writer() { |
| 95 | for { |
| 96 | select { |
| 97 | case <-c.done: |
| 98 | return |
| 99 | case wr := <-c.writes: |
| 100 | _, err := c.w.Write(wr.line) |
| 101 | if wr.done != nil { |
| 102 | wr.done <- err |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | // take waits until n more bytes fit the budget (one message always does |
| 109 | // when nothing else waits); false once the client is shut down. |
| 110 | func (c *Client) take(n int) bool { |
| 111 | c.qmu.Lock() |
| 112 | defer c.qmu.Unlock() |
| 113 | for c.queued > 0 && c.queued+n > c.budget { |
| 114 | if c.shut() { |
| 115 | return false |
| 116 | } |
| 117 | c.qcond.Wait() |
| 118 | } |
| 119 | if c.shut() { |
| 120 | return false |
| 121 | } |
| 122 | c.queued += n |
| 123 | return true |
| 124 | } |
| 125 | |
| 126 | func (c *Client) shut() bool { |
| 127 | select { |
| 128 | case <-c.done: |
| 129 | return true |
| 130 | default: |
| 131 | return false |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | // Release hands back a message's bytes once it has been read. |
| 136 | func (c *Client) Release(n int) { |
| 137 | c.qmu.Lock() |
| 138 | c.queued -= n |
| 139 | c.qmu.Unlock() |
| 140 | c.qcond.Broadcast() |
| 141 | } |
| 142 | |
| 143 | func (c *Client) queuedBytes() int { |
| 144 | c.qmu.Lock() |
| 145 | defer c.qmu.Unlock() |
| 146 | return c.queued |
| 147 | } |
| 148 | |
| 149 | func (c *Client) fail() { |
| 150 | c.mu.Lock() |
| 151 | c.closed = true |
| 152 | c.mu.Unlock() |
| 153 | } |
| 154 | |
| 155 | // Closed reports whether OpenCode's stdout ended or the client was shut |
| 156 | // down. |
| 157 | func (c *Client) Closed() bool { |
| 158 | c.mu.Lock() |
| 159 | defer c.mu.Unlock() |
| 160 | return c.closed || c.shut() |
| 161 | } |
| 162 | |
| 163 | // Shutdown ends the client: its reader stops (however full its queue), |
| 164 | // a write waiting on OpenCode gives up, nothing more is sent, and the |
| 165 | // writer closes OpenCode's stdin when it can. |
| 166 | func (c *Client) Shutdown() { |
| 167 | c.once.Do(func() { |
| 168 | close(c.done) |
| 169 | c.qmu.Lock() |
| 170 | c.qcond.Broadcast() |
| 171 | c.qmu.Unlock() |
| 172 | if wc, ok := c.w.(io.Closer); ok { |
| 173 | // Unblocks a write OpenCode never reads. |
| 174 | wc.Close() |
| 175 | } |
| 176 | }) |
| 177 | } |
| 178 | |
| 179 | func (c *Client) line(v any) ([]byte, error) { |
| 180 | raw, err := json.Marshal(v) |
| 181 | if err != nil { |
| 182 | return nil, err |
| 183 | } |
| 184 | if c.Closed() { |
| 185 | return nil, ErrClosed |
| 186 | } |
| 187 | return append(raw, '\n'), nil |
| 188 | } |
| 189 | |
| 190 | // Send writes one message as a line. It gives up when ctx ends or the |
| 191 | // client shuts down: an OpenCode that stops reading its stdin holds only |
| 192 | // the writer goroutine, never the caller. |
| 193 | func (c *Client) Send(ctx context.Context, v any) error { |
| 194 | line, err := c.line(v) |
| 195 | if err != nil { |
| 196 | return err |
| 197 | } |
| 198 | wr := write{line: line, done: make(chan error, 1)} |
| 199 | select { |
| 200 | case c.writes <- wr: |
| 201 | case <-ctx.Done(): |
| 202 | return ctx.Err() |
| 203 | case <-c.done: |
| 204 | return ErrClosed |
| 205 | } |
| 206 | select { |
| 207 | case err := <-wr.done: |
| 208 | return err |
| 209 | case <-ctx.Done(): |
| 210 | return ctx.Err() |
| 211 | case <-c.done: |
| 212 | return ErrClosed |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | // TrySend queues one message without waiting: false when the queue is |
| 217 | // full or the client is closed (the message is not sent). |
| 218 | func (c *Client) TrySend(v any) bool { |
| 219 | line, err := c.line(v) |
| 220 | if err != nil { |
| 221 | return false |
| 222 | } |
| 223 | select { |
| 224 | case c.writes <- write{line: line}: |
| 225 | return true |
| 226 | default: |
| 227 | return false |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // Message is one JSON-RPC message as read: a request or notification |
| 232 | // (Method), or a response (ID with Result or Error). |
| 233 | type Message struct { |
| 234 | JSONRPC string `json:"jsonrpc"` |
| 235 | ID json.RawMessage `json:"id,omitempty"` |
| 236 | Method string `json:"method,omitempty"` |
| 237 | Params json.RawMessage `json:"params,omitempty"` |
| 238 | Result json.RawMessage `json:"result,omitempty"` |
| 239 | Error *RPCError `json:"error,omitempty"` |
| 240 | } |
| 241 | |
| 242 | // RPCError is a JSON-RPC error. Data carries OpenCode's error name. |
| 243 | type RPCError struct { |
| 244 | Code int `json:"code"` |
| 245 | Message string `json:"message"` |
| 246 | Data struct { |
| 247 | ErrorName string `json:"errorName"` |
| 248 | } `json:"data"` |
| 249 | } |
| 250 | |
| 251 | // Response reports whether m answers a request (an id, no method). |
| 252 | func (m Message) Response() bool { return len(m.ID) > 0 && m.Method == "" } |
| 253 | |
| 254 | // Request reports whether m is OpenCode's request to the client (an id |
| 255 | // and a method): it must be answered. |
| 256 | func (m Message) Request() bool { return len(m.ID) > 0 && m.Method != "" } |
| 257 | |