package connect import ( "bufio" "context" "encoding/json" "errors" "io" "strconv" "sync" ) // MaxAppServerFrame bounds one app-server line. const MaxAppServerFrame = 1 << 20 // ErrAppServer is any protocol failure talking to codex app-server; the // app-server's own error text is never surfaced. var ErrAppServer = errors.New("codex app-server protocol failure") // Message is one app-server line that is not an answer to our call: a // notification (ID empty) or a request the server makes of us (ID set), // which must be answered with Answer or Refuse. type Message struct { ID json.RawMessage Method string Params json.RawMessage } type reply struct { result, err json.RawMessage } // AppServer is a JSON-RPC 2.0 client over codex app-server's stdio, // one JSON document per line. type AppServer struct { w io.Writer wmu sync.Mutex mu sync.Mutex next int64 pending map[string]chan reply // Messages are notifications and server requests in order. It closes // when the server's output ends. Messages chan Message done chan struct{} err error } // NewAppServer reads r until it ends; w is the server's stdin. func NewAppServer(r io.Reader, w io.Writer) *AppServer { a := &AppServer{w: w, pending: map[string]chan reply{}, Messages: make(chan Message, 256), done: make(chan struct{})} go a.read(r) return a } func (a *AppServer) read(r io.Reader) { defer close(a.done) defer close(a.Messages) scan := bufio.NewScanner(r) scan.Buffer(make([]byte, 0, 64<<10), MaxAppServerFrame) for scan.Scan() { var m struct { ID json.RawMessage `json:"id"` Method string `json:"method"` Params json.RawMessage `json:"params"` Result json.RawMessage `json:"result"` Error json.RawMessage `json:"error"` } if json.Unmarshal(scan.Bytes(), &m) != nil { a.fail(ErrAppServer) return } if m.Method == "" { a.mu.Lock() ch := a.pending[string(m.ID)] delete(a.pending, string(m.ID)) a.mu.Unlock() if ch != nil { ch <- reply{result: m.Result, err: m.Error} } continue } select { case a.Messages <- Message{ID: m.ID, Method: m.Method, Params: m.Params}: default: // A reader that falls this far behind has lost the turn. a.fail(ErrAppServer) return } } a.fail(io.EOF) } func (a *AppServer) fail(err error) { a.mu.Lock() defer a.mu.Unlock() if a.err == nil { a.err = err } for id, ch := range a.pending { close(ch) delete(a.pending, id) } } // Done closes when the server's output has ended. func (a *AppServer) Done() <-chan struct{} { return a.done } func (a *AppServer) write(v any) error { raw, err := json.Marshal(v) if err != nil { return err } a.wmu.Lock() defer a.wmu.Unlock() _, err = a.w.Write(append(raw, '\n')) return err } // Call sends a request and waits for its answer. A JSON-RPC error answer // is returned as ErrAppServer with the error document for the caller to // read codes from (never to show). func (a *AppServer) Call(ctx context.Context, method string, params any) (json.RawMessage, json.RawMessage, error) { a.mu.Lock() if a.err != nil { a.mu.Unlock() return nil, nil, ErrAppServer } a.next++ id := strconv.Quote("e" + strconv.FormatInt(a.next, 10)) ch := make(chan reply, 1) a.pending[id] = ch a.mu.Unlock() if err := a.write(map[string]any{"id": json.RawMessage(id), "method": method, "params": params}); err != nil { return nil, nil, ErrAppServer } select { case r, ok := <-ch: if !ok { return nil, nil, ErrAppServer } if len(r.err) > 0 && string(r.err) != "null" { return nil, r.err, ErrAppServer } return r.result, nil, nil case <-ctx.Done(): a.mu.Lock() delete(a.pending, id) a.mu.Unlock() return nil, nil, ctx.Err() } } // Notify sends a notification. func (a *AppServer) Notify(method string, params any) error { return a.write(map[string]any{"method": method, "params": params}) } // Answer answers a server request. func (a *AppServer) Answer(id json.RawMessage, result any) error { return a.write(map[string]any{"id": id, "result": result}) } // Refuse answers a server request with an error: Equipo does not do it. func (a *AppServer) Refuse(id json.RawMessage) error { return a.write(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": "refused by policy"}}) }