oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package codex
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "sync"
10
11 "amadan.net/oficina/equipo/internal/runner/provider"
12)
13
14type reply struct {
15 raw json.RawMessage
16 err error
17}
18
19// RPC owns client call correlation. Server request IDs never enter pending.
20// Construction and the transport stay private to the adapter.
21type RPC struct {
22 ctx context.Context
23 cancel context.CancelFunc
24 cap *provider.Capture
25 handler func(provider.Frame) error
26 mu sync.Mutex
27 writeMu sync.Mutex
28 pending map[string]chan reply
29 next uint64
30 err error
31 done chan struct{}
32}
33
34func newRPC(ctx context.Context, cap *provider.Capture, handler func([]byte) error) *RPC {
35 return newFrameRPC(ctx, cap, func(f provider.Frame) error { return handler(f.Bytes) })
36}
37func newFrameRPC(ctx context.Context, cap *provider.Capture, handler func(provider.Frame) error) *RPC {
38 ctx, cancel := context.WithCancel(ctx)
39 r := &RPC{ctx: ctx, cancel: cancel, cap: cap, handler: handler, pending: map[string]chan reply{}, done: make(chan struct{})}
40 go r.read()
41 return r
42}
43func (r *RPC) close() { r.fail(io.EOF) }
44func (r *RPC) fail(e error) {
45 r.mu.Lock()
46 if r.err == nil {
47 r.err = e
48 }
49 for id, ch := range r.pending {
50 ch <- reply{err: r.err}
51 delete(r.pending, id)
52 }
53 r.mu.Unlock()
54 r.cancel()
55 r.cap.Input.Close()
56}
57func (r *RPC) write(ctx context.Context, v any) error {
58 raw, e := json.Marshal(v)
59 if e != nil || len(raw) > MaxFrameBytes {
60 return errProtocol
61 }
62 raw = append(raw, '\n')
63 r.writeMu.Lock()
64 defer r.writeMu.Unlock()
65 if e = ctx.Err(); e != nil {
66 return e
67 }
68 if e = r.ctx.Err(); e != nil {
69 return e
70 }
71 stop := context.AfterFunc(ctx, func() { r.fail(ctx.Err()) })
72 defer stop()
73 n, e := r.cap.Input.Write(raw)
74 if e != nil || n != len(raw) {
75 r.fail(io.ErrShortWrite)
76 return io.ErrShortWrite
77 }
78 return ctx.Err()
79}
80func validCall(method string, params json.RawMessage) bool {
81 if !uniqueJSON(params) {
82 return false
83 }
84 var m map[string]json.RawMessage
85 if json.Unmarshal(params, &m) != nil || m == nil {
86 return false
87 }
88 switch method {
89 case "initialize", "account/read", "config/read", "thread/start", "thread/resume", "turn/interrupt":
90 return true
91 case "turn/start":
92 for key := range m {
93 switch key {
94 case "threadId", "input", "effort", "summary":
95 default:
96 return false
97 }
98 }
99 return len(m["threadId"]) > 0 && len(m["input"]) > 0
100 default:
101 return false
102 }
103}
104func (r *RPC) Call(ctx context.Context, method string, params json.RawMessage) (json.RawMessage, error) {
105 if !validCall(method, params) {
106 return nil, provider.ErrPolicy
107 }
108 r.mu.Lock()
109 if r.err != nil {
110 e := r.err
111 r.mu.Unlock()
112 return nil, e
113 }
114 r.next++
115 id := fmt.Sprintf("equipo:%d", r.next)
116 key, _ := json.Marshal(id)
117 ch := make(chan reply, 1)
118 r.pending[string(key)] = ch
119 r.mu.Unlock()
120 if e := r.write(ctx, struct {
121 ID string `json:"id"`
122 Method string `json:"method"`
123 Params json.RawMessage `json:"params"`
124 }{id, method, params}); e != nil {
125 r.fail(e)
126 return nil, e
127 }
128 select {
129 case v := <-ch:
130 return v.raw, v.err
131 case <-ctx.Done():
132 r.fail(ctx.Err())
133 return nil, ctx.Err()
134 case <-r.ctx.Done():
135 select {
136 case v := <-ch:
137 return v.raw, v.err
138 default:
139 return nil, r.ctx.Err()
140 }
141 }
142}
143func (r *RPC) initialized(ctx context.Context) error {
144 return r.write(ctx, map[string]any{"method": "initialized", "params": map[string]any{}})
145}
146func (r *RPC) read() {
147 defer close(r.done)
148 var seq int64
149 for {
150 select {
151 case <-r.ctx.Done():
152 r.fail(r.ctx.Err())
153 return
154 case frame, ok := <-r.cap.Frames:
155 if !ok {
156 select {
157 case e := <-r.cap.Done:
158 if e == nil {
159 e = io.EOF
160 }
161 r.fail(e)
162 case <-r.ctx.Done():
163 r.fail(r.ctx.Err())
164 }
165 return
166 }
167 if frame.Sequence <= seq {
168 r.fail(errProtocol)
169 return
170 }
171 seq = frame.Sequence
172 v, e := parse(frame.Bytes)
173 if e != nil {
174 r.fail(e)
175 return
176 }
177 if v.Method != "" {
178 if e = r.handler(provider.Frame{Sequence: frame.Sequence, Bytes: bytes.Clone(frame.Bytes)}); e != nil {
179 r.fail(e)
180 return
181 }
182 continue
183 }
184 r.mu.Lock()
185 ch, ok := r.pending[string(v.ID)]
186 if ok {
187 delete(r.pending, string(v.ID))
188 }
189 r.mu.Unlock()
190 if !ok {
191 r.fail(errProtocol)
192 return
193 }
194 if len(v.Error) > 0 {
195 ch <- reply{err: errProtocol}
196 } else {
197 ch <- reply{raw: bytes.Clone(v.Result)}
198 }
199 }
200 }
201}
202
203// answer writes server replies separately from client-call correlation.
204func (r *RPC) answer(ctx context.Context, s provider.Session, turn string, v any) error {
205 raw, e := json.Marshal(v)
206 if e != nil || len(raw) > MaxFrameBytes {
207 return errProtocol
208 }
209 raw = append(raw, '\n')
210 r.writeMu.Lock()
211 defer r.writeMu.Unlock()
212 if ctx.Err() != nil || r.ctx.Err() != nil {
213 return errNotReady
214 }
215 stop := context.AfterFunc(ctx, func() { r.fail(ctx.Err()) })
216 defer stop()
217 var n int
218 if w, ok := r.cap.Input.(provider.AnswerWriter); ok {
219 n, e = w.WriteAnswer(ctx, s, turn, raw)
220 } else {
221 n, e = r.cap.Input.Write(raw)
222 }
223 if e != nil || n != len(raw) {
224 r.fail(io.ErrShortWrite)
225 return io.ErrShortWrite
226 }
227 return nil
228}
229func (r *RPC) callAnswer(ctx context.Context, s provider.Session, turn string, params json.RawMessage) (json.RawMessage, error) {
230 if !validSteer(params) {
231 return nil, provider.ErrPolicy
232 }
233 r.mu.Lock()
234 if r.err != nil {
235 e := r.err
236 r.mu.Unlock()
237 return nil, e
238 }
239 r.next++
240 id := fmt.Sprintf("equipo:%d", r.next)
241 key, _ := json.Marshal(id)
242 ch := make(chan reply, 1)
243 r.pending[string(key)] = ch
244 r.mu.Unlock()
245 if e := r.answer(ctx, s, turn, map[string]any{"id": id, "method": "turn/steer", "params": params}); e != nil {
246 return nil, e
247 }
248 select {
249 case v := <-ch:
250 return v.raw, v.err
251 case <-ctx.Done():
252 r.fail(ctx.Err())
253 return nil, ctx.Err()
254 case <-r.ctx.Done():
255 return nil, r.ctx.Err()
256 }
257}
258func validSteer(raw json.RawMessage) bool {
259 if !uniqueJSON(raw) {
260 return false
261 }
262 var p map[string]json.RawMessage
263 if json.Unmarshal(raw, &p) != nil || len(p) != 3 {
264 return false
265 }
266 for _, key := range []string{"threadId", "expectedTurnId"} {
267 var s string
268 if json.Unmarshal(p[key], &s) != nil || s == "" {
269 return false
270 }
271 }
272 var input []struct{ Type, Text string }
273 return json.Unmarshal(p["input"], &input) == nil && len(input) == 1 && input[0].Type == "text" && input[0].Text != ""
274}
275