| 1 | package codex |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "slices" |
| 9 | "sort" |
| 10 | "strings" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 13 | ) |
| 14 | |
| 15 | // QuestionKeys recognises both the pinned async representation and the schema |
| 16 | // request. Other shapes can be displayed, but cannot be approved as questions. |
| 17 | func QuestionKeys(ev provider.Event) ([]string, error) { |
| 18 | v, e := parse(ev.Payload) |
| 19 | if e != nil { |
| 20 | return nil, e |
| 21 | } |
| 22 | var p struct { |
| 23 | Questions []struct { |
| 24 | ID string `json:"id"` |
| 25 | } |
| 26 | Item struct { |
| 27 | Type, Delivery string |
| 28 | Questions []struct { |
| 29 | Title string `json:"title"` |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | if json.Unmarshal(v.Params, &p) != nil { |
| 34 | return nil, errProtocol |
| 35 | } |
| 36 | keys := []string{} |
| 37 | switch v.Method { |
| 38 | case "item/tool/requestUserInput": |
| 39 | for _, q := range p.Questions { |
| 40 | keys = append(keys, q.ID) |
| 41 | } |
| 42 | case "item/completed": |
| 43 | if p.Item.Type != "agentMessage" || p.Item.Delivery != "async" { |
| 44 | return nil, errProtocol |
| 45 | } |
| 46 | for _, q := range p.Item.Questions { |
| 47 | keys = append(keys, q.Title) |
| 48 | } |
| 49 | default: |
| 50 | return nil, errProtocol |
| 51 | } |
| 52 | if len(keys) == 0 || len(keys) > 32 { |
| 53 | return nil, errProtocol |
| 54 | } |
| 55 | seen := map[string]bool{} |
| 56 | for _, k := range keys { |
| 57 | if k == "" || seen[k] || strings.HasPrefix(k, "mcp_tool_call_approval_") { |
| 58 | return nil, errProtocol |
| 59 | } |
| 60 | seen[k] = true |
| 61 | } |
| 62 | return keys, nil |
| 63 | } |
| 64 | |
| 65 | // MCPApproval keeps the provider's tool identity and arguments intact. |
| 66 | func MCPApproval(ev provider.Event) (string, json.RawMessage, error) { |
| 67 | v, e := parse(ev.Payload) |
| 68 | if e != nil || v.Method != "mcpServer/elicitation/request" { |
| 69 | return "", nil, provider.ErrPolicy |
| 70 | } |
| 71 | var p struct { |
| 72 | ThreadID, TurnID, ServerName, Mode string |
| 73 | Meta struct { |
| 74 | Kind string `json:"codex_approval_kind"` |
| 75 | Arguments json.RawMessage `json:"tool_params"` |
| 76 | } `json:"_meta"` |
| 77 | RequestedSchema json.RawMessage |
| 78 | } |
| 79 | if json.Unmarshal(v.Params, &p) != nil || p.ServerName != "equipo" || p.Mode != "form" || p.Meta.Kind != "mcp_tool_call" || !uniqueJSON(p.Meta.Arguments) || !sameJSON(p.RequestedSchema, []byte(`{"type":"object","properties":{}}`)) { |
| 80 | return "", nil, provider.ErrPolicy |
| 81 | } |
| 82 | call, e := parse(ev.ToolCall) |
| 83 | if e != nil || call.Method != "item/started" { |
| 84 | return "", nil, provider.ErrPolicy |
| 85 | } |
| 86 | var c struct { |
| 87 | ThreadID, TurnID string |
| 88 | Item struct { |
| 89 | ID, Type, Server, Tool string |
| 90 | Arguments json.RawMessage |
| 91 | } |
| 92 | } |
| 93 | if json.Unmarshal(call.Params, &c) != nil || c.ThreadID != p.ThreadID || c.TurnID != p.TurnID || c.Item.ID == "" || c.Item.Type != "mcpToolCall" || c.Item.Server != p.ServerName || c.Item.Tool == "" || !sameJSON(c.Item.Arguments, p.Meta.Arguments) { |
| 94 | return "", nil, provider.ErrPolicy |
| 95 | } |
| 96 | return c.Item.Tool, c.Item.Arguments, nil |
| 97 | } |
| 98 | func (s *sessionState) correlateMCP(ev *provider.Event) { |
| 99 | for _, call := range s.mcpCalls { |
| 100 | candidate := *ev |
| 101 | candidate.ToolCall = call |
| 102 | if _, _, err := MCPApproval(candidate); err == nil { |
| 103 | if len(ev.ToolCall) > 0 { |
| 104 | ev.ToolCall = nil |
| 105 | return |
| 106 | } // Ambiguous calls cannot approve one another. |
| 107 | ev.ToolCall = call |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | func (l *Launcher) respond(ctx context.Context, session provider.Session, a provider.Answer) error { |
| 113 | s, e := l.state(session) |
| 114 | if e != nil { |
| 115 | return e |
| 116 | } |
| 117 | s.op.Lock() |
| 118 | defer s.op.Unlock() |
| 119 | s.mu.Lock() |
| 120 | ev, ok := s.requests[a.RequestID] |
| 121 | if !ok || !s.active || s.closed || s.err != nil || s.ctx.Err() != nil || ctx.Err() != nil || a.TurnID != s.turn.ID || ev.TurnID != a.TurnID { |
| 122 | s.mu.Unlock() |
| 123 | return errNotReady |
| 124 | } |
| 125 | providerTurn := s.providerTurn |
| 126 | s.mu.Unlock() |
| 127 | if e = s.lease.ValidatePolicy(ctx); e != nil { |
| 128 | return e |
| 129 | } |
| 130 | v, e := parse(ev.Payload) |
| 131 | if e != nil { |
| 132 | return e |
| 133 | } |
| 134 | if a.Behavior == "deny" && len(a.Input) == 0 && (v.Method == "item/tool/requestUserInput" || !supportedRequest(v.Method)) { |
| 135 | s.mu.Lock() |
| 136 | delete(s.requests, a.RequestID) |
| 137 | s.mu.Unlock() |
| 138 | return s.rpc.answer(ctx, session, a.TurnID, requestRefusal(a.RequestID)) |
| 139 | } |
| 140 | var result any |
| 141 | steer := false |
| 142 | keys, keyErr := QuestionKeys(ev) |
| 143 | if keyErr == nil { |
| 144 | answers := map[string]string{} |
| 145 | if a.Behavior == "deny" && len(a.Input) == 0 { |
| 146 | for _, key := range keys { |
| 147 | answers[key] = provider.ErrPolicy.Error() |
| 148 | } |
| 149 | } else { |
| 150 | if a.Behavior != "allow" || !uniqueJSON(a.Input) { |
| 151 | return provider.ErrPolicy |
| 152 | } |
| 153 | var err error |
| 154 | answers, err = provider.QuestionAnswers(a.Input, keys) |
| 155 | if err != nil { |
| 156 | return err |
| 157 | } |
| 158 | } |
| 159 | if v.Method == "item/tool/requestUserInput" { |
| 160 | mapped := map[string]any{} |
| 161 | for k, v := range answers { |
| 162 | mapped[k] = map[string]any{"answers": []string{v}} |
| 163 | } |
| 164 | result = map[string]any{"answers": mapped} |
| 165 | } else { |
| 166 | steer = true |
| 167 | sort.Strings(keys) |
| 168 | lines := []string{} |
| 169 | for _, key := range keys { |
| 170 | lines = append(lines, fmt.Sprintf("%s: %s", key, answers[key])) |
| 171 | } |
| 172 | result = map[string]any{"threadId": session.ID, "expectedTurnId": providerTurn, "input": []any{map[string]any{"type": "text", "text": strings.Join(lines, "\n")}}} |
| 173 | } |
| 174 | } else { |
| 175 | if len(a.Input) != 0 { |
| 176 | return provider.ErrPolicy |
| 177 | } |
| 178 | switch v.Method { |
| 179 | case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "mcpServer/elicitation/request", "execCommandApproval", "applyPatchApproval": |
| 180 | default: |
| 181 | return provider.ErrPolicy |
| 182 | } |
| 183 | decision := "decline" |
| 184 | if a.Behavior == "allow" { |
| 185 | _, nativeErr := NativeApproval(ev) |
| 186 | tool, _, mcpErr := MCPApproval(ev) |
| 187 | var m manifest |
| 188 | if json.Unmarshal(s.launch.Policy.Manifest, &m) != nil { |
| 189 | return provider.ErrPolicy |
| 190 | } |
| 191 | if m.Action != "" { |
| 192 | if mcpErr == nil && !slices.Contains(m.Tools, "mcp__equipo__"+tool) { |
| 193 | return provider.ErrPolicy |
| 194 | } |
| 195 | if nativeErr == nil && s.launch.Policy.ReadOnlyWorkspace() && (v.Method == "item/fileChange/requestApproval" || v.Method == "applyPatchApproval") { |
| 196 | return provider.ErrPolicy |
| 197 | } |
| 198 | } |
| 199 | if a.Authorize == nil || (nativeErr != nil && mcpErr != nil) { |
| 200 | return provider.ErrPolicy |
| 201 | } |
| 202 | if e = a.Authorize(ctx, ev); e == nil { |
| 203 | decision = "accept" |
| 204 | } else { |
| 205 | if nativeErr == nil { |
| 206 | return e |
| 207 | } |
| 208 | a.Behavior = "deny" |
| 209 | } |
| 210 | } else if a.Behavior != "deny" { |
| 211 | return provider.ErrPolicy |
| 212 | } |
| 213 | result = map[string]any{"decision": decision} |
| 214 | if v.Method == "execCommandApproval" || v.Method == "applyPatchApproval" { |
| 215 | if decision == "accept" { |
| 216 | result = map[string]any{"decision": "approved"} |
| 217 | } else { |
| 218 | result = map[string]any{"decision": map[string]any{"denied": map[string]any{"rejection": ""}}} |
| 219 | } |
| 220 | } |
| 221 | if v.Method == "mcpServer/elicitation/request" { |
| 222 | var content any |
| 223 | if decision == "accept" { |
| 224 | content = map[string]any{} |
| 225 | } |
| 226 | result = map[string]any{"action": decision, "content": content, "_meta": nil} |
| 227 | } |
| 228 | } |
| 229 | if a.Behavior == "allow" && v.Method == "mcpServer/elicitation/request" { |
| 230 | s.mu.Lock() |
| 231 | current := ev |
| 232 | current.ToolCall = nil |
| 233 | s.correlateMCP(¤t) |
| 234 | s.mu.Unlock() |
| 235 | if len(current.ToolCall) == 0 || !bytes.Equal(current.ToolCall, ev.ToolCall) { |
| 236 | return provider.ErrPolicy |
| 237 | } |
| 238 | } |
| 239 | if a.Behavior == "allow" && v.Method == "item/fileChange/requestApproval" { |
| 240 | s.mu.Lock() |
| 241 | current := ev |
| 242 | current.ToolCall = nil |
| 243 | s.correlateNative(¤t) |
| 244 | s.mu.Unlock() |
| 245 | if len(current.ToolCall) == 0 || !bytes.Equal(current.ToolCall, ev.ToolCall) { |
| 246 | return provider.ErrPolicy |
| 247 | } |
| 248 | } |
| 249 | // Reserve the one response before I/O. A lost write cannot be replayed. |
| 250 | s.mu.Lock() |
| 251 | if !s.active || s.closed || s.err != nil || s.providerTurn != providerTurn || s.turn.ID != a.TurnID { |
| 252 | s.mu.Unlock() |
| 253 | return errNotReady |
| 254 | } |
| 255 | current, present := s.requests[a.RequestID] |
| 256 | if !present || !bytes.Equal(current.Payload, ev.Payload) || !bytes.Equal(current.ToolCall, ev.ToolCall) { |
| 257 | s.mu.Unlock() |
| 258 | return provider.ErrPolicy |
| 259 | } |
| 260 | delete(s.requests, a.RequestID) |
| 261 | s.mu.Unlock() |
| 262 | if steer { |
| 263 | raw, e := s.rpc.callAnswer(ctx, session, a.TurnID, marshal(result)) |
| 264 | if e != nil { |
| 265 | return s.stop(e) |
| 266 | } |
| 267 | var response struct { |
| 268 | TurnID string `json:"turnId"` |
| 269 | } |
| 270 | if json.Unmarshal(raw, &response) != nil || response.TurnID != providerTurn { |
| 271 | return s.stop(provider.ErrIdentity) |
| 272 | } |
| 273 | return nil |
| 274 | } |
| 275 | return s.rpc.answer(ctx, session, a.TurnID, map[string]any{"id": json.RawMessage(a.RequestID), "result": result}) |
| 276 | } |
| 277 | |
| 278 | func supportedRequest(method string) bool { |
| 279 | switch method { |
| 280 | case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "mcpServer/elicitation/request", "execCommandApproval", "applyPatchApproval", "item/tool/requestUserInput", "item/completed": |
| 281 | return true |
| 282 | } |
| 283 | return false |
| 284 | } |
| 285 | func requestRefusal(id string) any { |
| 286 | return map[string]any{"id": json.RawMessage(id), "error": map[string]any{"code": -32000, "message": provider.ErrPolicy.Error()}} |
| 287 | } |
| 288 | |