package runner import ( "bytes" "context" "encoding/json" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/codex" "amadan.net/oficina/equipo/internal/runnerproto" ) // DirectQuestionRelay uses the instance's durable question API through ask. // Current must revalidate that API's current question revision and answerer as // well as lease/fence authority. A saved answer alone never confers authority. type DirectQuestionRelay struct { Binding ToolBinding Proxy *ToolProxy Launcher provider.Launcher Current func(context.Context, runnerproto.Question) (time.Time, error) Answerer func(context.Context, runnerproto.Question) (string, error) } func (r *DirectQuestionRelay) Handle(ctx context.Context, ev provider.Event, ask func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error)) error { b := r.Binding if r.Launcher == nil || b.Journal == nil || b.Current == nil || ev.Kind != "request" || ev.RequestID == "" || ev.SessionID != b.Session.ID || ev.TurnID != b.TurnID { return runnerproto.ErrInvalid } if err := b.Current(ctx); err != nil { return err } if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { return err } if b.Session.Provider == "codex" { if _, _, e := codex.MCPApproval(ev); e == nil { if r.Proxy == nil { return runnerproto.ErrInvalid } authorize := func(ctx context.Context, original provider.Event) error { 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)) { return runnerproto.ErrInvalid } name, args, e := codex.MCPApproval(original) if e != nil { return e } var fields map[string]json.RawMessage if runnerproto.DecodeLimit(bytes.NewReader(args), &fields, maxToolFrame) != nil { return runnerproto.ErrInvalid } var id string if json.Unmarshal(fields["request_id"], &id) != nil { return runnerproto.ErrInvalid } delete(fields, "request_id") args, _ = json.Marshal(fields) 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}) } if e = authorize(ctx, ev); e != nil { if err := b.Current(ctx); err != nil { return err } if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { return err } return r.Launcher.Respond(ctx, b.Session, provider.Answer{RequestID: ev.RequestID, TurnID: b.TurnID, Behavior: "deny"}) } return r.Launcher.Respond(ctx, b.Session, provider.Answer{RequestID: ev.RequestID, TurnID: b.TurnID, Behavior: "allow", Authorize: authorize}) } } if ask == nil || r.Current == nil { return runnerproto.ErrInvalid } q, e := DirectQuestionFromEvent(ev, b) if e != nil { return e } q.ExpiresAt, e = r.Current(ctx, q) if e != nil || q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt) { return runnerproto.ErrInvalid } waitCtx := ctx answer, e := ask(waitCtx, q) if e != nil { return e } q.Answer = &answer if _, err := q.NativeApproval(); err == nil && answer.Behavior == "allow" { if r.Answerer == nil { return runnerproto.ErrInvalid } q.AnsweredBy, e = r.Answerer(waitCtx, q) if e != nil || q.AnsweredBy == "" { return runnerproto.ErrInvalid } } client := &directQuestionClient{launcher: r.Launcher, session: b.Session, turn: b.TurnID} if _, err := q.NativeApproval(); err == nil && answer.Behavior == "allow" { client.authorize = func(ctx context.Context, original provider.Event) error { 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) { return runnerproto.ErrInvalid } // A redacted request cannot confer authority over unseen bytes. var saved struct { Request json.RawMessage ToolCall json.RawMessage `json:"tool_call"` } if json.Unmarshal(q.RawRequest, &saved) != nil || !runnerproto.SameRequestJSON(original.Payload, saved.Request) { return runnerproto.ErrInvalid } if len(original.ToolCall) > 0 { if !runnerproto.SameRequestJSON(original.ToolCall, saved.ToolCall) { return runnerproto.ErrInvalid } } if err := b.Current(ctx); err != nil { return err } if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { return err } deadline, err := r.Current(ctx, q) if err != nil || deadline.IsZero() || !time.Now().Before(deadline) { return runnerproto.ErrInvalid } return nil } } 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) { if e := b.Current(ctx); e != nil { return time.Time{}, e } return r.Current(ctx, q) }} return relay.Deliver(waitCtx, q, answer) } type directQuestionClient struct { launcher provider.Launcher session provider.Session turn string authorize func(context.Context, provider.Event) error } func (c *directQuestionClient) Respond(ctx context.Context, _ provider.Agent, a provider.PermissionResponse) error { return c.launcher.Respond(ctx, c.session, provider.Answer{RequestID: a.RequestID, TurnID: c.turn, Behavior: a.Behavior, Input: a.UpdatedInput, Authorize: c.authorize}) } func (c *directQuestionClient) Send(context.Context, provider.Agent, string, string) error { return runnerproto.ErrInvalid } func DirectQuestionFromEvent(ev provider.Event, b ToolBinding) (runnerproto.Question, error) { 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} if ev.Kind != "request" || ev.SessionID != b.Session.ID || ev.TurnID != b.TurnID || !uniqueFrame(ev.Payload) { return q, runnerproto.ErrInvalid } name := "" var input json.RawMessage if b.Session.Provider == "claude" { var p struct { Tool string `json:"tool_name"` ToolUseID string `json:"tool_use_id,omitempty"` Input json.RawMessage `json:"input"` } if runnerproto.DecodeLimit(bytes.NewReader(ev.Payload), &p, maxToolFrame) != nil { return q, runnerproto.ErrInvalid } name = p.Tool input = p.Input if name == "AskUserQuestion" || name == "ask_person" { q.Kind = "question" } } else if b.Session.Provider == "codex" { var p struct { Method string Params json.RawMessage } if json.Unmarshal(ev.Payload, &p) != nil { return q, runnerproto.ErrInvalid } name = p.Method input = p.Params if keys, e := codex.QuestionKeys(ev); e == nil { q.Kind = "question" name = "request_user_input" questions := []any{} for _, k := range keys { questions = append(questions, map[string]string{"question": k, "header": k}) } input, _ = json.Marshal(map[string]any{"questions": questions}) } } else { return q, runnerproto.ErrInvalid } 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}) q.RawRequest = RedactJSON(q.RawRequest, nil) return q, q.Validate() } // Ask returns a scoped MCP question's answer to that same tool call. func (r *DirectQuestionRelay) Ask(ctx context.Context, id string, args json.RawMessage, ask func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error)) (json.RawMessage, error) { b := r.Binding if b.Journal == nil || b.Current == nil || r.Current == nil || ask == nil || id == "" || validateToolArguments("ask_person", args) != nil { return nil, runnerproto.ErrInvalid } var input PersonQuestion _ = json.Unmarshal(args, &input) permission := runnerproto.EventHash([]any{"ask", id, b.TurnID}) 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} q.RawRequest, _ = json.Marshal(map[string]any{"id": permission, "kind": "person", "question": input.Question}) if err := b.Current(ctx); err != nil { return nil, err } if err := b.Journal.currentDirectTurn(ctx, b.Session, b.TurnID); err != nil { return nil, err } expiry, err := r.Current(ctx, q) if err != nil || expiry.IsZero() || !time.Now().Before(expiry) { return nil, runnerproto.ErrInvalid } q.ExpiresAt = expiry answer, err := ask(ctx, q) if err != nil { return nil, err } client := &scopedAnswerClient{} 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) { if err := b.Current(ctx); err != nil { return time.Time{}, err } return r.Current(ctx, q) }} if err = relay.Deliver(ctx, q, answer); err != nil { return nil, err } if client.result == nil { return nil, errDirectUncertain } return client.result, nil } type scopedAnswerClient struct{ result json.RawMessage } func (c *scopedAnswerClient) Respond(_ context.Context, _ provider.Agent, a provider.PermissionResponse) error { if a.Behavior == "deny" { c.result = json.RawMessage(`{"behavior":"deny"}`) return nil } if a.Behavior != "allow" { return runnerproto.ErrInvalid } c.result = bytes.Clone(a.UpdatedInput) return nil } func (c *scopedAnswerClient) Send(context.Context, provider.Agent, string, string) error { return runnerproto.ErrInvalid }