package opencode import ( "bufio" "context" "encoding/json" "errors" "io" "sync" ) // Client speaks the Agent Client Protocol to `opencode acp`: JSON-RPC 2.0 // messages, one per line (LF), on the process's stdin and stdout. It // frames and bounds; routing is the session's: every message read is in // Messages, in order, and the one reader hands each back with Release. // Writes go through one writer goroutine and a bounded queue, and // Shutdown ends both directions however full they are (security round // findings 5 and 7). type Client struct { w io.Writer writes chan write done chan struct{} once sync.Once mu sync.Mutex closed bool // Messages are every message OpenCode sends, in order; closed when // its stdout ends, a message is over the size limit, or Shutdown. Messages <-chan []byte // queued is how many bytes of Messages are taken and not released; // the client stops reading OpenCode's stdout while they are over // budget. qmu sync.Mutex qcond *sync.Cond queued int budget int } // write is one queued line and where its outcome goes. type write struct { line []byte done chan error } // ErrClosed: OpenCode's stdout ended, or the client was shut down. var ErrClosed = errors.New("opencode: the process ended") // maxMessage bounds one message (a tool's output can be large); // maxQueued bounds the bytes waiting in the client; maxPendingWrites // bounds the writes waiting for OpenCode to read its stdin. const ( maxMessage = 8 << 20 maxQueued = 16 << 20 maxPendingWrites = 32 ) // NewClient reads r until it ends. func NewClient(r io.Reader, w io.Writer) *Client { return newClientLimits(r, w, maxMessage, maxQueued) } func newClientLimits(r io.Reader, w io.Writer, message, queued int) *Client { messages := make(chan []byte, 256) c := &Client{w: w, writes: make(chan write, maxPendingWrites), done: make(chan struct{}), Messages: messages, budget: queued} c.qcond = sync.NewCond(&c.qmu) go func() { defer close(messages) defer c.fail() s := bufio.NewScanner(r) s.Buffer(make([]byte, 0, min(64<<10, message)), message) for s.Scan() { line := append([]byte(nil), s.Bytes()...) if len(line) == 0 { continue } if !c.take(len(line)) { return } select { case messages <- line: case <-c.done: return } } }() go c.writer() return c } // writer writes the queued lines in order until Shutdown. A write // OpenCode never reads holds only this goroutine, until the pipe closes. func (c *Client) writer() { for { select { case <-c.done: return case wr := <-c.writes: _, err := c.w.Write(wr.line) if wr.done != nil { wr.done <- err } } } } // take waits until n more bytes fit the budget (one message always does // when nothing else waits); false once the client is shut down. func (c *Client) take(n int) bool { c.qmu.Lock() defer c.qmu.Unlock() for c.queued > 0 && c.queued+n > c.budget { if c.shut() { return false } c.qcond.Wait() } if c.shut() { return false } c.queued += n return true } func (c *Client) shut() bool { select { case <-c.done: return true default: return false } } // Release hands back a message's bytes once it has been read. func (c *Client) Release(n int) { c.qmu.Lock() c.queued -= n c.qmu.Unlock() c.qcond.Broadcast() } func (c *Client) queuedBytes() int { c.qmu.Lock() defer c.qmu.Unlock() return c.queued } func (c *Client) fail() { c.mu.Lock() c.closed = true c.mu.Unlock() } // Closed reports whether OpenCode's stdout ended or the client was shut // down. func (c *Client) Closed() bool { c.mu.Lock() defer c.mu.Unlock() return c.closed || c.shut() } // Shutdown ends the client: its reader stops (however full its queue), // a write waiting on OpenCode gives up, nothing more is sent, and the // writer closes OpenCode's stdin when it can. func (c *Client) Shutdown() { c.once.Do(func() { close(c.done) c.qmu.Lock() c.qcond.Broadcast() c.qmu.Unlock() if wc, ok := c.w.(io.Closer); ok { // Unblocks a write OpenCode never reads. wc.Close() } }) } func (c *Client) line(v any) ([]byte, error) { raw, err := json.Marshal(v) if err != nil { return nil, err } if c.Closed() { return nil, ErrClosed } return append(raw, '\n'), nil } // Send writes one message as a line. It gives up when ctx ends or the // client shuts down: an OpenCode that stops reading its stdin holds only // the writer goroutine, never the caller. func (c *Client) Send(ctx context.Context, v any) error { line, err := c.line(v) if err != nil { return err } wr := write{line: line, done: make(chan error, 1)} select { case c.writes <- wr: case <-ctx.Done(): return ctx.Err() case <-c.done: return ErrClosed } select { case err := <-wr.done: return err case <-ctx.Done(): return ctx.Err() case <-c.done: return ErrClosed } } // TrySend queues one message without waiting: false when the queue is // full or the client is closed (the message is not sent). func (c *Client) TrySend(v any) bool { line, err := c.line(v) if err != nil { return false } select { case c.writes <- write{line: line}: return true default: return false } } // Message is one JSON-RPC message as read: a request or notification // (Method), or a response (ID with Result or Error). type Message struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id,omitempty"` Method string `json:"method,omitempty"` Params json.RawMessage `json:"params,omitempty"` Result json.RawMessage `json:"result,omitempty"` Error *RPCError `json:"error,omitempty"` } // RPCError is a JSON-RPC error. Data carries OpenCode's error name. type RPCError struct { Code int `json:"code"` Message string `json:"message"` Data struct { ErrorName string `json:"errorName"` } `json:"data"` } // Response reports whether m answers a request (an id, no method). func (m Message) Response() bool { return len(m.ID) > 0 && m.Method == "" } // Request reports whether m is OpenCode's request to the client (an id // and a method): it must be answered. func (m Message) Request() bool { return len(m.ID) > 0 && m.Method != "" }