| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "time" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 10 | "amadan.net/oficina/equipo/internal/runner/provider/codex" |
| 11 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 12 | ) |
| 13 | |
| 14 | // DirectQuestionRelay uses the instance's durable question API through ask. |
| 15 | // Current must revalidate that API's current question revision and answerer as |
| 16 | // well as lease/fence authority. A saved answer alone never confers authority. |
| 17 | type DirectQuestionRelay struct { |
| 18 | Binding ToolBinding |
| 19 | Proxy *ToolProxy |
| 20 | Launcher provider.Launcher |
| 21 | Current func(context.Context, runnerproto.Question) (time.Time, error) |
| 22 | Answerer func(context.Context, runnerproto.Question) (string, error) |
| 23 | } |
| 24 | |
| 25 | func (r *DirectQuestionRelay) Handle(ctx context.Context, ev provider.Event, ask func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error)) error { |
| 26 | b := r.Binding |
| 27 | if r.Launcher == nil || b.Journal == nil || b.Current == nil || ev.Kind != "request" || ev.RequestID == "" || ev.SessionID != b.Session.ID || ev.TurnID != b.TurnID { |
| 28 | return runnerproto.ErrInvalid |
| 29 | } |
| 30 | if err := b.Current(ctx); err != nil { |
| 31 | return err |
| 32 | } |
| 33 | if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { |
| 34 | return err |
| 35 | } |
| 36 | if b.Session.Provider == "codex" { |
| 37 | if _, _, e := codex.MCPApproval(ev); e == nil { |
| 38 | if r.Proxy == nil { |
| 39 | return runnerproto.ErrInvalid |
| 40 | } |
| 41 | authorize := func(ctx context.Context, original provider.Event) error { |
| 42 | if original.SessionID != ev.SessionID || original.TurnID != ev.TurnID || original.RequestID != ev.RequestID || (!bytes.Equal(original.Payload, ev.Payload) || !bytes.Equal(original.ToolCall, ev.ToolCall)) { |
| 43 | return runnerproto.ErrInvalid |
| 44 | } |
| 45 | name, args, e := codex.MCPApproval(original) |
| 46 | if e != nil { |
| 47 | return e |
| 48 | } |
| 49 | var fields map[string]json.RawMessage |
| 50 | if runnerproto.DecodeLimit(bytes.NewReader(args), &fields, maxToolFrame) != nil { |
| 51 | return runnerproto.ErrInvalid |
| 52 | } |
| 53 | var id string |
| 54 | if json.Unmarshal(fields["request_id"], &id) != nil { |
| 55 | return runnerproto.ErrInvalid |
| 56 | } |
| 57 | delete(fields, "request_id") |
| 58 | args, _ = json.Marshal(fields) |
| 59 | return r.Proxy.ValidateApproval(ctx, ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: name, RequestID: id, Arguments: args}) |
| 60 | } |
| 61 | if e = authorize(ctx, ev); e != nil { |
| 62 | if err := b.Current(ctx); err != nil { |
| 63 | return err |
| 64 | } |
| 65 | if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { |
| 66 | return err |
| 67 | } |
| 68 | return r.Launcher.Respond(ctx, b.Session, provider.Answer{RequestID: ev.RequestID, TurnID: b.TurnID, Behavior: "deny"}) |
| 69 | } |
| 70 | return r.Launcher.Respond(ctx, b.Session, provider.Answer{RequestID: ev.RequestID, TurnID: b.TurnID, Behavior: "allow", Authorize: authorize}) |
| 71 | } |
| 72 | } |
| 73 | if ask == nil || r.Current == nil { |
| 74 | return runnerproto.ErrInvalid |
| 75 | } |
| 76 | q, e := DirectQuestionFromEvent(ev, b) |
| 77 | if e != nil { |
| 78 | return e |
| 79 | } |
| 80 | q.ExpiresAt, e = r.Current(ctx, q) |
| 81 | if e != nil || q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt) { |
| 82 | return runnerproto.ErrInvalid |
| 83 | } |
| 84 | waitCtx := ctx |
| 85 | answer, e := ask(waitCtx, q) |
| 86 | if e != nil { |
| 87 | return e |
| 88 | } |
| 89 | q.Answer = &answer |
| 90 | if _, err := q.NativeApproval(); err == nil && answer.Behavior == "allow" { |
| 91 | if r.Answerer == nil { |
| 92 | return runnerproto.ErrInvalid |
| 93 | } |
| 94 | q.AnsweredBy, e = r.Answerer(waitCtx, q) |
| 95 | if e != nil || q.AnsweredBy == "" { |
| 96 | return runnerproto.ErrInvalid |
| 97 | } |
| 98 | } |
| 99 | client := &directQuestionClient{launcher: r.Launcher, session: b.Session, turn: b.TurnID} |
| 100 | if _, err := q.NativeApproval(); err == nil && answer.Behavior == "allow" { |
| 101 | client.authorize = func(ctx context.Context, original provider.Event) error { |
| 102 | if original.SessionID != ev.SessionID || original.TurnID != ev.TurnID || original.ProviderTurnID != ev.ProviderTurnID || original.RequestID != ev.RequestID || !bytes.Equal(original.Payload, ev.Payload) || !bytes.Equal(original.ToolCall, ev.ToolCall) { |
| 103 | return runnerproto.ErrInvalid |
| 104 | } |
| 105 | // A redacted request cannot confer authority over unseen bytes. |
| 106 | var saved struct { |
| 107 | Request json.RawMessage |
| 108 | ToolCall json.RawMessage `json:"tool_call"` |
| 109 | } |
| 110 | if json.Unmarshal(q.RawRequest, &saved) != nil || !runnerproto.SameRequestJSON(original.Payload, saved.Request) { |
| 111 | return runnerproto.ErrInvalid |
| 112 | } |
| 113 | if len(original.ToolCall) > 0 { |
| 114 | if !runnerproto.SameRequestJSON(original.ToolCall, saved.ToolCall) { |
| 115 | return runnerproto.ErrInvalid |
| 116 | } |
| 117 | } |
| 118 | if err := b.Current(ctx); err != nil { |
| 119 | return err |
| 120 | } |
| 121 | if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { |
| 122 | return err |
| 123 | } |
| 124 | deadline, err := r.Current(ctx, q) |
| 125 | if err != nil || deadline.IsZero() || !time.Now().Before(deadline) { |
| 126 | return runnerproto.ErrInvalid |
| 127 | } |
| 128 | return nil |
| 129 | } |
| 130 | } |
| 131 | relay := QuestionRelay{Journal: b.Journal, Client: client, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(ctx context.Context, q runnerproto.Question) (time.Time, error) { |
| 132 | if e := b.Current(ctx); e != nil { |
| 133 | return time.Time{}, e |
| 134 | } |
| 135 | return r.Current(ctx, q) |
| 136 | }} |
| 137 | return relay.Deliver(waitCtx, q, answer) |
| 138 | } |
| 139 | |
| 140 | type directQuestionClient struct { |
| 141 | launcher provider.Launcher |
| 142 | session provider.Session |
| 143 | turn string |
| 144 | authorize func(context.Context, provider.Event) error |
| 145 | } |
| 146 | |
| 147 | func (c *directQuestionClient) Respond(ctx context.Context, _ provider.Agent, a provider.PermissionResponse) error { |
| 148 | return c.launcher.Respond(ctx, c.session, provider.Answer{RequestID: a.RequestID, TurnID: c.turn, Behavior: a.Behavior, Input: a.UpdatedInput, Authorize: c.authorize}) |
| 149 | } |
| 150 | func (c *directQuestionClient) Send(context.Context, provider.Agent, string, string) error { |
| 151 | return runnerproto.ErrInvalid |
| 152 | } |
| 153 | |
| 154 | func DirectQuestionFromEvent(ev provider.Event, b ToolBinding) (runnerproto.Question, error) { |
| 155 | q := runnerproto.Question{ID: runnerproto.EventHash([]any{b.InstanceID, b.TaskID, b.Attempt, b.Fence, ev.TurnID, ev.RequestID}), TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: ev.RequestID, Kind: "tool", Revision: 1, ExpiresAt: b.LeaseDeadline} |
| 156 | if ev.Kind != "request" || ev.SessionID != b.Session.ID || ev.TurnID != b.TurnID || !uniqueFrame(ev.Payload) { |
| 157 | return q, runnerproto.ErrInvalid |
| 158 | } |
| 159 | name := "" |
| 160 | var input json.RawMessage |
| 161 | if b.Session.Provider == "claude" { |
| 162 | var p struct { |
| 163 | Tool string `json:"tool_name"` |
| 164 | ToolUseID string `json:"tool_use_id,omitempty"` |
| 165 | Input json.RawMessage `json:"input"` |
| 166 | } |
| 167 | if runnerproto.DecodeLimit(bytes.NewReader(ev.Payload), &p, maxToolFrame) != nil { |
| 168 | return q, runnerproto.ErrInvalid |
| 169 | } |
| 170 | name = p.Tool |
| 171 | input = p.Input |
| 172 | if name == "AskUserQuestion" || name == "ask_person" { |
| 173 | q.Kind = "question" |
| 174 | } |
| 175 | } else if b.Session.Provider == "codex" { |
| 176 | var p struct { |
| 177 | Method string |
| 178 | Params json.RawMessage |
| 179 | } |
| 180 | if json.Unmarshal(ev.Payload, &p) != nil { |
| 181 | return q, runnerproto.ErrInvalid |
| 182 | } |
| 183 | name = p.Method |
| 184 | input = p.Params |
| 185 | if keys, e := codex.QuestionKeys(ev); e == nil { |
| 186 | q.Kind = "question" |
| 187 | name = "request_user_input" |
| 188 | questions := []any{} |
| 189 | for _, k := range keys { |
| 190 | questions = append(questions, map[string]string{"question": k, "header": k}) |
| 191 | } |
| 192 | input, _ = json.Marshal(map[string]any{"questions": questions}) |
| 193 | } |
| 194 | } else { |
| 195 | return q, runnerproto.ErrInvalid |
| 196 | } |
| 197 | q.RawRequest, _ = json.Marshal(map[string]any{"id": q.PermissionID, "kind": q.Kind, "provider": b.Session.Provider, "name": name, "input": input, "direct": true, "turn_id": b.TurnID, "request": json.RawMessage(ev.Payload), "tool_call": ev.ToolCall, "provider_turn_id": ev.ProviderTurnID}) |
| 198 | q.RawRequest = RedactJSON(q.RawRequest, nil) |
| 199 | return q, q.Validate() |
| 200 | } |
| 201 | |
| 202 | // Ask returns a scoped MCP question's answer to that same tool call. |
| 203 | func (r *DirectQuestionRelay) Ask(ctx context.Context, id string, args json.RawMessage, ask func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error)) (json.RawMessage, error) { |
| 204 | b := r.Binding |
| 205 | if b.Journal == nil || b.Current == nil || r.Current == nil || ask == nil || id == "" || validateToolArguments("ask_person", args) != nil { |
| 206 | return nil, runnerproto.ErrInvalid |
| 207 | } |
| 208 | var input PersonQuestion |
| 209 | _ = json.Unmarshal(args, &input) |
| 210 | permission := runnerproto.EventHash([]any{"ask", id, b.TurnID}) |
| 211 | q := runnerproto.Question{ID: runnerproto.EventHash([]any{b.InstanceID, b.TaskID, b.Attempt, b.Fence, permission}), TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: permission, Kind: "person", Revision: 1, ExpiresAt: b.LeaseDeadline} |
| 212 | q.RawRequest, _ = json.Marshal(map[string]any{"id": permission, "kind": "person", "question": input.Question}) |
| 213 | if err := b.Current(ctx); err != nil { |
| 214 | return nil, err |
| 215 | } |
| 216 | if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { |
| 217 | return nil, err |
| 218 | } |
| 219 | expiry, err := r.Current(ctx, q) |
| 220 | if err != nil || expiry.IsZero() || !time.Now().Before(expiry) { |
| 221 | return nil, runnerproto.ErrInvalid |
| 222 | } |
| 223 | q.ExpiresAt = expiry |
| 224 | answer, err := ask(ctx, q) |
| 225 | if err != nil { |
| 226 | return nil, err |
| 227 | } |
| 228 | client := &scopedAnswerClient{} |
| 229 | relay := QuestionRelay{Journal: b.Journal, Agent: b.Agent, Client: client, DirectSession: b.Session, TurnID: b.TurnID, Current: func(ctx context.Context, q runnerproto.Question) (time.Time, error) { |
| 230 | if err := b.Current(ctx); err != nil { |
| 231 | return time.Time{}, err |
| 232 | } |
| 233 | return r.Current(ctx, q) |
| 234 | }} |
| 235 | if err = relay.Deliver(ctx, q, answer); err != nil { |
| 236 | return nil, err |
| 237 | } |
| 238 | if client.result == nil { |
| 239 | return nil, errDirectUncertain |
| 240 | } |
| 241 | return client.result, nil |
| 242 | } |
| 243 | |
| 244 | type scopedAnswerClient struct{ result json.RawMessage } |
| 245 | |
| 246 | func (c *scopedAnswerClient) Respond(_ context.Context, _ provider.Agent, a provider.PermissionResponse) error { |
| 247 | if a.Behavior == "deny" { |
| 248 | c.result = json.RawMessage(`{"behavior":"deny"}`) |
| 249 | return nil |
| 250 | } |
| 251 | if a.Behavior != "allow" { |
| 252 | return runnerproto.ErrInvalid |
| 253 | } |
| 254 | c.result = bytes.Clone(a.UpdatedInput) |
| 255 | return nil |
| 256 | } |
| 257 | func (c *scopedAnswerClient) Send(context.Context, provider.Agent, string, string) error { |
| 258 | return runnerproto.ErrInvalid |
| 259 | } |
| 260 | |