package codex import ( "bytes" "context" "encoding/json" "fmt" "io" "sync" "amadan.net/oficina/equipo/internal/runner/provider" ) type reply struct { raw json.RawMessage err error } // RPC owns client call correlation. Server request IDs never enter pending. // Construction and the transport stay private to the adapter. type RPC struct { ctx context.Context cancel context.CancelFunc cap *provider.Capture handler func(provider.Frame) error mu sync.Mutex writeMu sync.Mutex pending map[string]chan reply next uint64 err error done chan struct{} } func newRPC(ctx context.Context, cap *provider.Capture, handler func([]byte) error) *RPC { return newFrameRPC(ctx, cap, func(f provider.Frame) error { return handler(f.Bytes) }) } func newFrameRPC(ctx context.Context, cap *provider.Capture, handler func(provider.Frame) error) *RPC { ctx, cancel := context.WithCancel(ctx) r := &RPC{ctx: ctx, cancel: cancel, cap: cap, handler: handler, pending: map[string]chan reply{}, done: make(chan struct{})} go r.read() return r } func (r *RPC) close() { r.fail(io.EOF) } func (r *RPC) fail(e error) { r.mu.Lock() if r.err == nil { r.err = e } for id, ch := range r.pending { ch <- reply{err: r.err} delete(r.pending, id) } r.mu.Unlock() r.cancel() r.cap.Input.Close() } func (r *RPC) write(ctx context.Context, v any) error { raw, e := json.Marshal(v) if e != nil || len(raw) > MaxFrameBytes { return errProtocol } raw = append(raw, '\n') r.writeMu.Lock() defer r.writeMu.Unlock() if e = ctx.Err(); e != nil { return e } if e = r.ctx.Err(); e != nil { return e } stop := context.AfterFunc(ctx, func() { r.fail(ctx.Err()) }) defer stop() n, e := r.cap.Input.Write(raw) if e != nil || n != len(raw) { r.fail(io.ErrShortWrite) return io.ErrShortWrite } return ctx.Err() } func validCall(method string, params json.RawMessage) bool { if !uniqueJSON(params) { return false } var m map[string]json.RawMessage if json.Unmarshal(params, &m) != nil || m == nil { return false } switch method { case "initialize", "account/read", "config/read", "thread/start", "thread/resume", "turn/interrupt": return true case "turn/start": for key := range m { switch key { case "threadId", "input", "effort", "summary": default: return false } } return len(m["threadId"]) > 0 && len(m["input"]) > 0 default: return false } } func (r *RPC) Call(ctx context.Context, method string, params json.RawMessage) (json.RawMessage, error) { if !validCall(method, params) { return nil, provider.ErrPolicy } r.mu.Lock() if r.err != nil { e := r.err r.mu.Unlock() return nil, e } r.next++ id := fmt.Sprintf("equipo:%d", r.next) key, _ := json.Marshal(id) ch := make(chan reply, 1) r.pending[string(key)] = ch r.mu.Unlock() if e := r.write(ctx, struct { ID string `json:"id"` Method string `json:"method"` Params json.RawMessage `json:"params"` }{id, method, params}); e != nil { r.fail(e) return nil, e } select { case v := <-ch: return v.raw, v.err case <-ctx.Done(): r.fail(ctx.Err()) return nil, ctx.Err() case <-r.ctx.Done(): select { case v := <-ch: return v.raw, v.err default: return nil, r.ctx.Err() } } } func (r *RPC) initialized(ctx context.Context) error { return r.write(ctx, map[string]any{"method": "initialized", "params": map[string]any{}}) } func (r *RPC) read() { defer close(r.done) var seq int64 for { select { case <-r.ctx.Done(): r.fail(r.ctx.Err()) return case frame, ok := <-r.cap.Frames: if !ok { select { case e := <-r.cap.Done: if e == nil { e = io.EOF } r.fail(e) case <-r.ctx.Done(): r.fail(r.ctx.Err()) } return } if frame.Sequence <= seq { r.fail(errProtocol) return } seq = frame.Sequence v, e := parse(frame.Bytes) if e != nil { r.fail(e) return } if v.Method != "" { if e = r.handler(provider.Frame{Sequence: frame.Sequence, Bytes: bytes.Clone(frame.Bytes)}); e != nil { r.fail(e) return } continue } r.mu.Lock() ch, ok := r.pending[string(v.ID)] if ok { delete(r.pending, string(v.ID)) } r.mu.Unlock() if !ok { r.fail(errProtocol) return } if len(v.Error) > 0 { ch <- reply{err: errProtocol} } else { ch <- reply{raw: bytes.Clone(v.Result)} } } } } // answer writes server replies separately from client-call correlation. func (r *RPC) answer(ctx context.Context, s provider.Session, turn string, v any) error { raw, e := json.Marshal(v) if e != nil || len(raw) > MaxFrameBytes { return errProtocol } raw = append(raw, '\n') r.writeMu.Lock() defer r.writeMu.Unlock() if ctx.Err() != nil || r.ctx.Err() != nil { return errNotReady } stop := context.AfterFunc(ctx, func() { r.fail(ctx.Err()) }) defer stop() var n int if w, ok := r.cap.Input.(provider.AnswerWriter); ok { n, e = w.WriteAnswer(ctx, s, turn, raw) } else { n, e = r.cap.Input.Write(raw) } if e != nil || n != len(raw) { r.fail(io.ErrShortWrite) return io.ErrShortWrite } return nil } func (r *RPC) callAnswer(ctx context.Context, s provider.Session, turn string, params json.RawMessage) (json.RawMessage, error) { if !validSteer(params) { return nil, provider.ErrPolicy } r.mu.Lock() if r.err != nil { e := r.err r.mu.Unlock() return nil, e } r.next++ id := fmt.Sprintf("equipo:%d", r.next) key, _ := json.Marshal(id) ch := make(chan reply, 1) r.pending[string(key)] = ch r.mu.Unlock() if e := r.answer(ctx, s, turn, map[string]any{"id": id, "method": "turn/steer", "params": params}); e != nil { return nil, e } select { case v := <-ch: return v.raw, v.err case <-ctx.Done(): r.fail(ctx.Err()) return nil, ctx.Err() case <-r.ctx.Done(): return nil, r.ctx.Err() } } func validSteer(raw json.RawMessage) bool { if !uniqueJSON(raw) { return false } var p map[string]json.RawMessage if json.Unmarshal(raw, &p) != nil || len(p) != 3 { return false } for _, key := range []string{"threadId", "expectedTurnId"} { var s string if json.Unmarshal(p[key], &s) != nil || s == "" { return false } } var input []struct{ Type, Text string } return json.Unmarshal(p["input"], &input) == nil && len(input) == 1 && input[0].Type == "text" && input[0].Text != "" }