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 "context"
5 "encoding/json"
6 "fmt"
7 "strings"
8 "testing"
9 "time"
10
11 "amadan.net/oficina/equipo/internal/runner/provider"
12)
13
14func answerFixture(t *testing.T) (*Launcher, *sessionState, *rpcInput, chan provider.Frame) {
15 t.Helper()
16 f := fixtureFor(t)
17 s, _ := openFixture(t, f)
18 ctx, cancel := context.WithCancel(context.Background())
19 t.Cleanup(cancel)
20 st := &sessionState{
21 session: s, launch: f.launch, lease: f.lease, ctx: ctx, cancel: cancel,
22 events: make(chan provider.Event, 64), active: true,
23 turn: provider.Turn{ID: "local-turn"}, providerTurn: "provider-turn",
24 }
25 w := &rpcInput{sent: make(chan []byte, 16)}
26 frames := make(chan provider.Frame, 16)
27 rpc := newFrameRPC(ctx, &provider.Capture{Input: w, Frames: frames, Done: make(chan error, 1)}, st.handle)
28 st.rpc = rpc
29 l := &Launcher{sessions: map[string]*sessionState{s.AttemptKey: st}}
30 t.Cleanup(func() { rpc.close(); <-rpc.done })
31 return l, st, w, frames
32}
33func TestCodexApprovalResponse(t *testing.T) {
34 for _, method := range []string{"item/commandExecution/requestApproval", "item/fileChange/requestApproval", "mcpServer/elicitation/request"} {
35 t.Run(method, func(t *testing.T) {
36 l, s, w, _ := answerFixture(t)
37 ctx := context.Background()
38 raw := []byte(fmt.Sprintf(`{"id":7,"method":%q,"params":{"threadId":%q,"turnId":"provider-turn","itemId":"item","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, method, s.session.ID))
39 raw = pinnedMCPRequest(t, s, raw)
40 if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil {
41 t.Fatal(e)
42 }
43 // IDs are JSON values, not their display form.
44 if l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: `"7"`, Behavior: "deny"}) == nil {
45 t.Fatal("string ID answered numeric request")
46 }
47 for _, input := range []string{`{"decision":"acceptForSession"}`, `{"execpolicyAmendment":["curl"]}`, `{"permissions":{"network":true}}`} {
48 if l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "allow", Input: json.RawMessage(input)}) == nil {
49 t.Fatal("policy amendment accepted", input)
50 }
51 }
52 if l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "allow"}) == nil {
53 t.Fatal("approval without broker validation")
54 }
55 if e := l.Respond(ctx, s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "deny"}); e != nil {
56 t.Fatal(e)
57 }
58 var reply struct {
59 ID json.RawMessage
60 Result map[string]any
61 }
62 if json.Unmarshal(<-w.sent, &reply) != nil || string(reply.ID) != "7" || reply.Result["decision"] != "decline" && reply.Result["action"] != "decline" {
63 t.Fatal(reply)
64 }
65 })
66 }
67}
68func TestCodexAsyncQuestionAnswer(t *testing.T) {
69 for _, mode := range []string{"async", "schema"} {
70 t.Run(mode, func(t *testing.T) {
71 l, s, w, frames := answerFixture(t)
72 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
73 defer cancel()
74 raw := fmt.Sprintf(`{"method":"item/completed","params":{"threadId":%q,"turnId":"provider-turn","item":{"id":"message","type":"agentMessage","delivery":"async","questions":[{"title":"Greeting","options":["hi","bye"]}]}}}`, s.session.ID)
75 id := "async:message"
76 if mode == "schema" {
77 id = `"user-input"`
78 raw = fmt.Sprintf(`{"id":"user-input","method":"item/tool/requestUserInput","params":{"threadId":%q,"turnId":"provider-turn","itemId":"tool","questions":[{"id":"Greeting","header":"Greeting","question":"Which greeting?","options":[{"label":"hi"}]}]}}`, s.session.ID)
79 }
80 if e := s.handle(provider.Frame{Sequence: 99, Bytes: []byte(raw)}); e != nil {
81 t.Fatal(e)
82 }
83 a := provider.Answer{RequestID: id, TurnID: "local-turn", Behavior: "allow", Input: json.RawMessage(`{"answers":{"Greeting":"hi"}}`)}
84 bad := a
85 bad.TurnID = "replaced"
86 if l.Respond(ctx, s.session, bad) == nil {
87 t.Fatal("replaced turn answered")
88 }
89 result := make(chan error, 1)
90 go func() { result <- l.Respond(ctx, s.session, a) }()
91 var call struct {
92 ID json.RawMessage
93 Method string
94 Params struct{ ThreadID, ExpectedTurnID string }
95 Result struct {
96 Answers map[string]struct{ Answers []string }
97 }
98 }
99 var wire []byte
100 select {
101 case wire = <-w.sent:
102 case e := <-result:
103 t.Fatal("answer not transmitted", e)
104 case <-ctx.Done():
105 t.Fatal("answer timeout")
106 }
107 if json.Unmarshal(wire, &call) != nil {
108 t.Fatal("bad wire")
109 }
110 if mode == "async" {
111 if call.Method != "turn/steer" || call.Params.ExpectedTurnID != "provider-turn" || call.Params.ThreadID != s.session.ID {
112 t.Fatalf("wrong steer: %+v", call)
113 }
114 frames <- provider.Frame{Sequence: 100, Bytes: []byte(fmt.Sprintf(`{"id":%s,"result":{"turnId":"provider-turn"}}`, call.ID))}
115 } else if string(call.ID) != id || len(call.Result.Answers["Greeting"].Answers) != 1 {
116 t.Fatal("wrong schema answer", call)
117 }
118 if e := <-result; e != nil {
119 t.Fatal(e)
120 }
121 if l.Respond(ctx, s.session, a) == nil {
122 t.Fatal("answer replay")
123 }
124 s.mu.Lock()
125 s.active = false
126 s.mu.Unlock()
127 if l.Respond(ctx, s.session, a) == nil {
128 t.Fatal("completed turn follow-up without admission")
129 }
130 })
131 }
132}
133
134func TestCodexApprovalResponseValidatedMCP(t *testing.T) {
135 l, s, w, _ := answerFixture(t)
136 raw := []byte(fmt.Sprintf(`{"id":"mcp","method":"mcpServer/elicitation/request","params":{"threadId":%q,"turnId":"provider-turn","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, s.session.ID))
137 raw = pinnedMCPRequest(t, s, raw)
138 if e := s.handle(provider.Frame{Sequence: 100, Bytes: raw}); e != nil {
139 t.Fatal(e)
140 }
141 checked := 0
142 a := provider.Answer{TurnID: "local-turn", RequestID: `"mcp"`, Behavior: "allow", Authorize: func(_ context.Context, ev provider.Event) error {
143 checked++
144 if string(ev.Payload) != string(raw) {
145 t.Fatal("original request changed")
146 }
147 return nil
148 }}
149 if e := l.Respond(context.Background(), s.session, a); e != nil {
150 t.Fatal(e)
151 }
152 var reply struct {
153 ID string
154 Result struct{ Decision, Action string }
155 }
156 if json.Unmarshal(<-w.sent, &reply) != nil || reply.ID != "mcp" || reply.Result.Action != "accept" || checked != 1 {
157 t.Fatal(reply, checked)
158 }
159}
160func TestCodexApprovalResponseFixedMCPPolicy(t *testing.T) {
161 f := fixtureFor(t)
162 var cfg map[string]json.RawMessage
163 if json.Unmarshal(f.inputs.Settings, &cfg) != nil {
164 t.Fatal("settings")
165 }
166 var servers map[string]struct {
167 Command string
168 Args []string
169 }
170 if json.Unmarshal(cfg["mcp_servers"], &servers) != nil || len(servers) != 1 || servers["equipo"].Command != "/opt/equipo-tool-proxy" || fmt.Sprint(servers["equipo"].Args) != "[--socket /tool/equipo.sock]" {
171 t.Fatal("fixed MCP missing", string(cfg["mcp_servers"]))
172 }
173}
174
175func pinnedMCPRequest(t *testing.T, s *sessionState, raw []byte) []byte {
176 t.Helper()
177 var v map[string]any
178 if json.Unmarshal(raw, &v) != nil {
179 t.Fatal("request")
180 }
181 if v["method"] != "mcpServer/elicitation/request" {
182 return raw
183 }
184 p := v["params"].(map[string]any)
185 item := map[string]any{"method": "item/started", "params": map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "item": map[string]any{"id": "mcp-item", "type": "mcpToolCall", "server": "equipo", "tool": p["tool"], "arguments": p["arguments"], "status": "inProgress"}}}
186 if e := s.handle(provider.Frame{Sequence: 98, Bytes: marshal(item)}); e != nil {
187 t.Fatal(e)
188 }
189 v["params"] = map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "serverName": "equipo", "mode": "form", "message": "approval fixture", "requestedSchema": map[string]any{"type": "object", "properties": map[string]any{}}, "_meta": map[string]any{"codex_approval_kind": "mcp_tool_call", "tool_params": p["arguments"], "persist": []string{"session", "always"}}}
190 return marshal(v)
191}
192
193func TestCodexApprovalResponseResolvedRequest(t *testing.T) {
194 l, s, _, _ := answerFixture(t)
195 raw := []byte(fmt.Sprintf(`{"id":9,"method":"item/commandExecution/requestApproval","params":{"threadId":%q,"turnId":"provider-turn","itemId":"command"}}`, s.session.ID))
196 if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil {
197 t.Fatal(e)
198 }
199 resolved := []byte(fmt.Sprintf(`{"method":"serverRequest/resolved","params":{"threadId":%q,"requestId":9}}`, s.session.ID))
200 if e := s.handle(provider.Frame{Sequence: 100, Bytes: resolved}); e != nil {
201 t.Fatal(e)
202 }
203 if l.Respond(context.Background(), s.session, provider.Answer{RequestID: "9", TurnID: "local-turn", Behavior: "deny"}) == nil {
204 t.Fatal("resolved request answered")
205 }
206}
207func TestCodexApprovalResponseMCPCorrelation(t *testing.T) {
208 for _, change := range []string{"arguments", "server", "schema", "missing-item", "completed-item", "ambiguous"} {
209 t.Run(change, func(t *testing.T) {
210 l, s, _, _ := answerFixture(t)
211 raw := []byte(fmt.Sprintf(`{"id":7,"method":"mcpServer/elicitation/request","params":{"threadId":%q,"turnId":"provider-turn","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, s.session.ID))
212 raw = pinnedMCPRequest(t, s, raw)
213 switch change {
214 case "arguments":
215 raw = []byte(strings.Replace(string(raw), "Which?", "Changed?", 1))
216 case "server":
217 raw = []byte(strings.Replace(string(raw), `"serverName":"equipo"`, `"serverName":"other"`, 1))
218 case "schema":
219 raw = []byte(strings.Replace(string(raw), `"properties":{}`, `"properties":{"permissions":{"type":"string"}}`, 1))
220 case "missing-item":
221 s.mcpCalls = nil
222 case "ambiguous":
223 s.mcpCalls["other"] = s.mcpCalls["mcp-item"]
224 }
225 if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil {
226 t.Fatal(e)
227 }
228 if change == "completed-item" {
229 s.mu.Lock()
230 delete(s.mcpCalls, "mcp-item")
231 s.mu.Unlock()
232 }
233 if l.Respond(context.Background(), s.session, provider.Answer{RequestID: "7", TurnID: "local-turn", Behavior: "allow", Authorize: func(context.Context, provider.Event) error { return nil }}) == nil {
234 t.Fatal("uncorrelated MCP approved", change)
235 }
236 })
237 }
238}
239
240func TestCodexApprovalResponseNoQuestionFallback(t *testing.T) {
241 l, s, _, _ := answerFixture(t)
242 raw := []byte(fmt.Sprintf(`{"id":"fallback","method":"item/tool/requestUserInput","params":{"threadId":%q,"turnId":"provider-turn","itemId":"tool","questions":[{"id":"mcp_tool_call_approval_1","header":"Approve app tool call?","question":"Allow?","options":[{"label":"Always allow"}]}]}}`, s.session.ID))
243 if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil {
244 t.Fatal(e)
245 }
246 if l.Respond(context.Background(), s.session, provider.Answer{RequestID: `"fallback"`, TurnID: "local-turn", Behavior: "allow", Input: json.RawMessage(`{"answers":{"mcp_tool_call_approval_1":"Always allow"}}`)}) == nil {
247 t.Fatal("permission amendment through question fallback")
248 }
249}
250
251func TestCodexApprovalResponseInvalidAuthorizationWire(t *testing.T) {
252 for _, reason := range []string{"fence", "attempt", "tool", "arguments", "changed-call", "completed-turn"} {
253 t.Run(reason, func(t *testing.T) {
254 l, s, w, _ := answerFixture(t)
255 raw := []byte(fmt.Sprintf(`{"id":7,"method":"mcpServer/elicitation/request","params":{"threadId":%q,"turnId":"provider-turn","server":"equipo","tool":"submit_candidate","arguments":{"request_id":"r","commit":"bad"}}}`, s.session.ID))
256 raw = pinnedMCPRequest(t, s, raw)
257 if e := s.handle(provider.Frame{Sequence: 99, Bytes: raw}); e != nil {
258 t.Fatal(e)
259 }
260 e := l.Respond(context.Background(), s.session, provider.Answer{TurnID: "local-turn", RequestID: "7", Behavior: "allow", Authorize: func(context.Context, provider.Event) error {
261 s.mu.Lock()
262 defer s.mu.Unlock()
263 if reason == "changed-call" {
264 clear(s.mcpCalls)
265 }
266 if reason == "completed-turn" {
267 s.active = false
268 }
269 return provider.ErrPolicy
270 }})
271 if reason == "completed-turn" {
272 if e == nil {
273 t.Fatal("completed turn answered")
274 }
275 select {
276 case raw := <-w.sent:
277 t.Fatalf("completed turn wire: %s", raw)
278 default:
279 }
280 return
281 }
282 if e != nil {
283 t.Fatalf("invalid %s authorization left request pending: %v", reason, e)
284 }
285 select {
286 case raw := <-w.sent:
287 var reply struct {
288 ID json.RawMessage
289 Result struct {
290 Action string
291 Content, Meta json.RawMessage
292 }
293 }
294 if json.Unmarshal(raw, &reply) != nil || string(reply.ID) != "7" || reply.Result.Action != "decline" || string(reply.Result.Content) != "null" {
295 t.Fatalf("expected decline on wire: %s", raw)
296 }
297 case <-time.After(time.Second):
298 t.Fatal("no decline on wire")
299 }
300 })
301 }
302}
303
304func TestCodexRefusesUnsupportedRequests(t *testing.T) {
305 for _, method := range []string{"item/permissions/requestApproval", "async/requestUserInput", "unlisted/request", "item/tool/requestUserInput"} {
306 t.Run(method, func(t *testing.T) {
307 l, s, w, _ := answerFixture(t)
308 raw := fmt.Sprintf(`{"id":7,"method":%q,"params":{"threadId":%q,"turnId":"provider-turn","questions":[{"id":"q"}]}}`, method, s.session.ID)
309 if err := s.handle(provider.Frame{Sequence: 99, Bytes: []byte(raw)}); err != nil {
310 t.Fatal(err)
311 }
312 if supportedRequest(method) {
313 if err := l.Respond(context.Background(), s.session, provider.Answer{RequestID: "7", TurnID: "local-turn", Behavior: "deny"}); err != nil {
314 t.Fatal("cannot refuse server request", err)
315 }
316 }
317 select {
318 case raw := <-w.sent:
319 var reply struct {
320 ID json.RawMessage
321 Error json.RawMessage
322 }
323 if json.Unmarshal(raw, &reply) != nil || len(reply.Error) == 0 {
324 t.Fatal("missing protocol refusal", string(raw))
325 }
326 case <-time.After(time.Second):
327 t.Fatal("request left hanging")
328 }
329 })
330 }
331}
332
333func TestCodexAsyncQuestionDenial(t *testing.T) {
334 l, s, w, frames := answerFixture(t)
335 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
336 defer cancel()
337 raw := fmt.Sprintf(`{"method":"item/completed","params":{"threadId":%q,"turnId":"provider-turn","item":{"id":"message","type":"agentMessage","delivery":"async","questions":[{"title":"Greeting"}]}}}`, s.session.ID)
338 if err := s.handle(provider.Frame{Sequence: 99, Bytes: []byte(raw)}); err != nil {
339 t.Fatal(err)
340 }
341 done := make(chan error, 1)
342 go func() {
343 done <- l.Respond(ctx, s.session, provider.Answer{RequestID: "async:message", TurnID: "local-turn", Behavior: "deny"})
344 }()
345 select {
346 case err := <-done:
347 t.Fatal("async denial was not sent", err)
348 case raw := <-w.sent:
349 var call struct {
350 ID json.RawMessage
351 Method string
352 Params struct {
353 ExpectedTurnID string `json:"expectedTurnId"`
354 Input []struct{ Text string }
355 }
356 }
357 if json.Unmarshal(raw, &call) != nil || call.Method != "turn/steer" || call.Params.ExpectedTurnID != "provider-turn" || len(call.Params.Input) != 1 || !strings.Contains(call.Params.Input[0].Text, provider.ErrPolicy.Error()) {
358 t.Fatal("wrong async refusal", string(raw))
359 }
360 frames <- provider.Frame{Sequence: 100, Bytes: marshal(map[string]any{"id": call.ID, "result": map[string]string{"turnId": "provider-turn"}})}
361 case <-ctx.Done():
362 t.Fatal("async refusal left waiting")
363 }
364 if err := <-done; err != nil {
365 t.Fatal(err)
366 }
367}
368