package codex import ( "bytes" "context" "encoding/json" "fmt" "slices" "sort" "strings" "amadan.net/oficina/equipo/internal/runner/provider" ) // QuestionKeys recognises both the pinned async representation and the schema // request. Other shapes can be displayed, but cannot be approved as questions. func QuestionKeys(ev provider.Event) ([]string, error) { v, e := parse(ev.Payload) if e != nil { return nil, e } var p struct { Questions []struct { ID string `json:"id"` } Item struct { Type, Delivery string Questions []struct { Title string `json:"title"` } } } if json.Unmarshal(v.Params, &p) != nil { return nil, errProtocol } keys := []string{} switch v.Method { case "item/tool/requestUserInput": for _, q := range p.Questions { keys = append(keys, q.ID) } case "item/completed": if p.Item.Type != "agentMessage" || p.Item.Delivery != "async" { return nil, errProtocol } for _, q := range p.Item.Questions { keys = append(keys, q.Title) } default: return nil, errProtocol } if len(keys) == 0 || len(keys) > 32 { return nil, errProtocol } seen := map[string]bool{} for _, k := range keys { if k == "" || seen[k] || strings.HasPrefix(k, "mcp_tool_call_approval_") { return nil, errProtocol } seen[k] = true } return keys, nil } // MCPApproval keeps the provider's tool identity and arguments intact. func MCPApproval(ev provider.Event) (string, json.RawMessage, error) { v, e := parse(ev.Payload) if e != nil || v.Method != "mcpServer/elicitation/request" { return "", nil, provider.ErrPolicy } var p struct { ThreadID, TurnID, ServerName, Mode string Meta struct { Kind string `json:"codex_approval_kind"` Arguments json.RawMessage `json:"tool_params"` } `json:"_meta"` RequestedSchema json.RawMessage } 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":{}}`)) { return "", nil, provider.ErrPolicy } call, e := parse(ev.ToolCall) if e != nil || call.Method != "item/started" { return "", nil, provider.ErrPolicy } var c struct { ThreadID, TurnID string Item struct { ID, Type, Server, Tool string Arguments json.RawMessage } } 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) { return "", nil, provider.ErrPolicy } return c.Item.Tool, c.Item.Arguments, nil } func (s *sessionState) correlateMCP(ev *provider.Event) { for _, call := range s.mcpCalls { candidate := *ev candidate.ToolCall = call if _, _, err := MCPApproval(candidate); err == nil { if len(ev.ToolCall) > 0 { ev.ToolCall = nil return } // Ambiguous calls cannot approve one another. ev.ToolCall = call } } } func (l *Launcher) respond(ctx context.Context, session provider.Session, a provider.Answer) error { s, e := l.state(session) if e != nil { return e } s.op.Lock() defer s.op.Unlock() s.mu.Lock() ev, ok := s.requests[a.RequestID] 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 { s.mu.Unlock() return errNotReady } providerTurn := s.providerTurn s.mu.Unlock() if e = s.lease.ValidatePolicy(ctx); e != nil { return e } v, e := parse(ev.Payload) if e != nil { return e } if a.Behavior == "deny" && len(a.Input) == 0 && (v.Method == "item/tool/requestUserInput" || !supportedRequest(v.Method)) { s.mu.Lock() delete(s.requests, a.RequestID) s.mu.Unlock() return s.rpc.answer(ctx, session, a.TurnID, requestRefusal(a.RequestID)) } var result any steer := false keys, keyErr := QuestionKeys(ev) if keyErr == nil { answers := map[string]string{} if a.Behavior == "deny" && len(a.Input) == 0 { for _, key := range keys { answers[key] = provider.ErrPolicy.Error() } } else { if a.Behavior != "allow" || !uniqueJSON(a.Input) { return provider.ErrPolicy } var err error answers, err = provider.QuestionAnswers(a.Input, keys) if err != nil { return err } } if v.Method == "item/tool/requestUserInput" { mapped := map[string]any{} for k, v := range answers { mapped[k] = map[string]any{"answers": []string{v}} } result = map[string]any{"answers": mapped} } else { steer = true sort.Strings(keys) lines := []string{} for _, key := range keys { lines = append(lines, fmt.Sprintf("%s: %s", key, answers[key])) } result = map[string]any{"threadId": session.ID, "expectedTurnId": providerTurn, "input": []any{map[string]any{"type": "text", "text": strings.Join(lines, "\n")}}} } } else { if len(a.Input) != 0 { return provider.ErrPolicy } switch v.Method { case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "mcpServer/elicitation/request", "execCommandApproval", "applyPatchApproval": default: return provider.ErrPolicy } decision := "decline" if a.Behavior == "allow" { _, nativeErr := NativeApproval(ev) tool, _, mcpErr := MCPApproval(ev) var m manifest if json.Unmarshal(s.launch.Policy.Manifest, &m) != nil { return provider.ErrPolicy } if m.Action != "" { if mcpErr == nil && !slices.Contains(m.Tools, "mcp__equipo__"+tool) { return provider.ErrPolicy } if nativeErr == nil && s.launch.Policy.ReadOnlyWorkspace() && (v.Method == "item/fileChange/requestApproval" || v.Method == "applyPatchApproval") { return provider.ErrPolicy } } if a.Authorize == nil || (nativeErr != nil && mcpErr != nil) { return provider.ErrPolicy } if e = a.Authorize(ctx, ev); e == nil { decision = "accept" } else { if nativeErr == nil { return e } a.Behavior = "deny" } } else if a.Behavior != "deny" { return provider.ErrPolicy } result = map[string]any{"decision": decision} if v.Method == "execCommandApproval" || v.Method == "applyPatchApproval" { if decision == "accept" { result = map[string]any{"decision": "approved"} } else { result = map[string]any{"decision": map[string]any{"denied": map[string]any{"rejection": ""}}} } } if v.Method == "mcpServer/elicitation/request" { var content any if decision == "accept" { content = map[string]any{} } result = map[string]any{"action": decision, "content": content, "_meta": nil} } } if a.Behavior == "allow" && v.Method == "mcpServer/elicitation/request" { s.mu.Lock() current := ev current.ToolCall = nil s.correlateMCP(¤t) s.mu.Unlock() if len(current.ToolCall) == 0 || !bytes.Equal(current.ToolCall, ev.ToolCall) { return provider.ErrPolicy } } if a.Behavior == "allow" && v.Method == "item/fileChange/requestApproval" { s.mu.Lock() current := ev current.ToolCall = nil s.correlateNative(¤t) s.mu.Unlock() if len(current.ToolCall) == 0 || !bytes.Equal(current.ToolCall, ev.ToolCall) { return provider.ErrPolicy } } // Reserve the one response before I/O. A lost write cannot be replayed. s.mu.Lock() if !s.active || s.closed || s.err != nil || s.providerTurn != providerTurn || s.turn.ID != a.TurnID { s.mu.Unlock() return errNotReady } current, present := s.requests[a.RequestID] if !present || !bytes.Equal(current.Payload, ev.Payload) || !bytes.Equal(current.ToolCall, ev.ToolCall) { s.mu.Unlock() return provider.ErrPolicy } delete(s.requests, a.RequestID) s.mu.Unlock() if steer { raw, e := s.rpc.callAnswer(ctx, session, a.TurnID, marshal(result)) if e != nil { return s.stop(e) } var response struct { TurnID string `json:"turnId"` } if json.Unmarshal(raw, &response) != nil || response.TurnID != providerTurn { return s.stop(provider.ErrIdentity) } return nil } return s.rpc.answer(ctx, session, a.TurnID, map[string]any{"id": json.RawMessage(a.RequestID), "result": result}) } func supportedRequest(method string) bool { switch method { case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "mcpServer/elicitation/request", "execCommandApproval", "applyPatchApproval", "item/tool/requestUserInput", "item/completed": return true } return false } func requestRefusal(id string) any { return map[string]any{"id": json.RawMessage(id), "error": map[string]any{"code": -32000, "message": provider.ErrPolicy.Error()}} }