| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 11 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 12 | ) |
| 13 | |
| 14 | type QuestionClient interface { |
| 15 | Respond(context.Context, provider.Agent, provider.PermissionResponse) error |
| 16 | Send(context.Context, provider.Agent, string, string) error |
| 17 | } |
| 18 | |
| 19 | func DeliverAnswer(ctx context.Context, client QuestionClient, agent provider.Agent, q runnerproto.Question, answer runnerproto.QuestionAnswer) error { |
| 20 | if client == nil || q.Validate() != nil || q.ValidateAnswer(answer) != nil || agent.ServerID != q.ServerID || agent.AgentID != q.AgentID || agent.ProviderSessionID != q.SessionID || (q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt)) { |
| 21 | return runnerproto.ErrInvalid |
| 22 | } |
| 23 | return client.Respond(ctx, agent, provider.PermissionResponse{RequestID: q.PermissionID, Behavior: answer.Behavior, UpdatedInput: answer.UpdatedInput}) |
| 24 | } |
| 25 | func SendFollowup(ctx context.Context, client QuestionClient, agent provider.Agent, message, id string, admit func(context.Context, string) error) error { |
| 26 | if client == nil || admit == nil || message == "" || id == "" { |
| 27 | return runnerproto.ErrInvalid |
| 28 | } |
| 29 | if err := admit(ctx, id); err != nil { |
| 30 | return err |
| 31 | } |
| 32 | return client.Send(ctx, agent, message, id) |
| 33 | } |
| 34 | |
| 35 | // QuestionFromEvent preserves the provider request, after bounded sanitization. |
| 36 | // Unknown request kinds stay pending; they cannot pass QuestionAnswer.Validate. |
| 37 | func QuestionFromEvent(e provider.RecordedEvent, id, task string, secrets []string) (runnerproto.Question, error) { |
| 38 | var envelope struct { |
| 39 | Request json.RawMessage `json:"request"` |
| 40 | Event struct { |
| 41 | Request json.RawMessage `json:"request"` |
| 42 | } `json:"event"` |
| 43 | } |
| 44 | if len(e.Payload) > provider.MaxEventBytes || json.Unmarshal(e.Payload, &envelope) != nil { |
| 45 | return runnerproto.Question{}, runnerproto.ErrInvalid |
| 46 | } |
| 47 | raw := envelope.Request |
| 48 | if len(raw) == 0 { |
| 49 | raw = envelope.Event.Request |
| 50 | } |
| 51 | var request struct { |
| 52 | ID string `json:"id"` |
| 53 | Kind string `json:"kind"` |
| 54 | } |
| 55 | if json.Unmarshal(raw, &request) != nil || request.ID != e.PermissionID { |
| 56 | return runnerproto.Question{}, runnerproto.ErrInvalid |
| 57 | } |
| 58 | q := runnerproto.Question{ID: id, TaskID: task, ServerID: e.ServerID, AgentID: e.AgentID, SessionID: e.ProviderSessionID, PermissionID: request.ID, Kind: request.Kind, Revision: 1, RawRequest: raw} |
| 59 | if err := q.Validate(); err != nil { |
| 60 | return runnerproto.Question{}, err |
| 61 | } |
| 62 | q.RawRequest = RedactJSON(raw, secrets) |
| 63 | return q, q.Validate() |
| 64 | } |
| 65 | |
| 66 | // QuestionRelay records delivery intent before Respond. A lost reply remains |
| 67 | // uncertain; it cannot trigger an automatic second response or a new turn. |
| 68 | type QuestionRelay struct { |
| 69 | DirectSession provider.Session |
| 70 | TurnID string |
| 71 | Journal *Journal |
| 72 | Client QuestionClient |
| 73 | Agent provider.Agent |
| 74 | // Current returns the trusted current lease bound, capped by the attempt deadline. |
| 75 | Current func(context.Context, runnerproto.Question) (time.Time, error) |
| 76 | } |
| 77 | |
| 78 | func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, answer runnerproto.QuestionAnswer) error { |
| 79 | if r.Journal == nil || r.Client == nil || r.Current == nil || q.Attempt <= 0 || q.Fence <= 0 || q.ExpiresAt.IsZero() || q.Validate() != nil || q.ValidateAnswer(answer) != nil { |
| 80 | return runnerproto.ErrInvalid |
| 81 | } |
| 82 | if r.DirectSession.AttemptKey != "" { |
| 83 | if q.SessionID != r.DirectSession.ID || q.AgentID != r.DirectSession.AttemptKey { |
| 84 | return runnerproto.ErrInvalid |
| 85 | } |
| 86 | if err := r.Journal.currentDirectTurn(ctx, r.DirectSession, r.TurnID); err != nil { |
| 87 | return err |
| 88 | } |
| 89 | } |
| 90 | var err error |
| 91 | q.ExpiresAt, err = r.Current(ctx, q) |
| 92 | if err != nil { |
| 93 | return err |
| 94 | } |
| 95 | if q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt) { |
| 96 | return runnerproto.ErrInvalid |
| 97 | } |
| 98 | key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID}) |
| 99 | hash := runnerproto.EventHash([]any{q.ID, q.Revision, q.RawRequest, answer}) |
| 100 | if _, err := q.NativeApproval(); err == nil && answer.Behavior == "allow" { |
| 101 | hash = runnerproto.EventHash([]any{q.ID, q.Revision, q.RawRequest, answer, q.AnsweredBy}) |
| 102 | } |
| 103 | if err := r.Journal.AdmissionAllowed(ctx); err != nil { |
| 104 | return err |
| 105 | } |
| 106 | tx, err := r.Journal.db.BeginTx(ctx, nil) |
| 107 | if err != nil { |
| 108 | return r.Journal.storageFailure(ctx, err) |
| 109 | } |
| 110 | defer tx.Rollback() |
| 111 | var old, state string |
| 112 | err = tx.QueryRowContext(ctx, "SELECT content_hash,state FROM journal_answers WHERE answer_key=?", key).Scan(&old, &state) |
| 113 | if err == nil { |
| 114 | if r.DirectSession.AttemptKey != "" { |
| 115 | var attempt, turn string |
| 116 | if err := tx.QueryRowContext(ctx, "SELECT attempt,turn FROM direct_answer_scopes WHERE answer_key=?", key).Scan(&attempt, &turn); err != nil || attempt != r.DirectSession.AttemptKey || turn != r.TurnID { |
| 117 | return runnerproto.ErrInvalid |
| 118 | } |
| 119 | } |
| 120 | if old != hash { |
| 121 | return runnerproto.ErrInvalid |
| 122 | } |
| 123 | if state == "delivered" { |
| 124 | return nil |
| 125 | } |
| 126 | return provider.ErrUncertain |
| 127 | } |
| 128 | if !errors.Is(err, sql.ErrNoRows) { |
| 129 | tx.Rollback() |
| 130 | return r.Journal.storageFailure(ctx, err) |
| 131 | } |
| 132 | if err = r.journalAdmissionTx(ctx, tx); err != nil { |
| 133 | return err |
| 134 | } |
| 135 | if _, err = tx.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,?,'pending')", key, hash); err != nil { |
| 136 | tx.Rollback() |
| 137 | return r.Journal.storageFailure(ctx, err) |
| 138 | } |
| 139 | if r.DirectSession.AttemptKey != "" { |
| 140 | if _, err = tx.ExecContext(ctx, "INSERT INTO direct_answer_scopes(answer_key,attempt,turn) VALUES(?,?,?)", key, r.DirectSession.AttemptKey, r.TurnID); err != nil { |
| 141 | return err |
| 142 | } |
| 143 | } |
| 144 | if _, nativeErr := q.NativeApproval(); nativeErr == nil && answer.Behavior == "allow" { |
| 145 | if q.AnsweredBy == "" { |
| 146 | return runnerproto.ErrInvalid |
| 147 | } |
| 148 | saved := q |
| 149 | saved.Answer = &answer |
| 150 | raw, err := json.Marshal(saved) |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | if _, err = tx.ExecContext(ctx, "INSERT INTO journal_supervisor(kind,state_key,body) VALUES('profile-approval',?,?)", key, raw); err != nil { |
| 155 | tx.Rollback() |
| 156 | return r.Journal.storageFailure(ctx, err) |
| 157 | } |
| 158 | } |
| 159 | if err = tx.Commit(); err != nil { |
| 160 | return r.Journal.storageFailure(ctx, err) |
| 161 | } |
| 162 | q.ExpiresAt, err = r.Current(ctx, q) |
| 163 | if err != nil { |
| 164 | return err |
| 165 | } |
| 166 | if r.DirectSession.AttemptKey != "" { |
| 167 | if err := r.Journal.currentDirectTurn(ctx, r.DirectSession, r.TurnID); err != nil { |
| 168 | return err |
| 169 | } |
| 170 | var state string |
| 171 | if err := r.Journal.db.QueryRowContext(ctx, "SELECT state FROM journal_answers WHERE answer_key=?", key).Scan(&state); err != nil || state != "pending" { |
| 172 | return runnerproto.ErrInvalid |
| 173 | } |
| 174 | } |
| 175 | if err = DeliverAnswer(ctx, r.Client, r.Agent, q, answer); err != nil { |
| 176 | return err |
| 177 | } |
| 178 | if _, err = r.Journal.db.ExecContext(ctx, "UPDATE journal_answers SET state='delivered' WHERE answer_key=? AND state='pending'", key); err != nil { |
| 179 | return r.Journal.storageFailure(ctx, err) |
| 180 | } |
| 181 | return nil |
| 182 | } |
| 183 | func (r *QuestionRelay) journalAdmissionTx(ctx context.Context, tx *sql.Tx) error { |
| 184 | var blocked int |
| 185 | if err := tx.QueryRowContext(ctx, "SELECT blocked FROM journal_state WHERE id=1").Scan(&blocked); err != nil || blocked != 0 { |
| 186 | return ErrJournal |
| 187 | } |
| 188 | return nil |
| 189 | } |
| 190 | |
| 191 | // Wait releases and contains expired, cancelled or invalidated waits through |
| 192 | // the supervisor. The poll callback is the authenticated instance answer API. |
| 193 | func (r *QuestionRelay) Wait(ctx context.Context, q runnerproto.Question, poll func(context.Context) (*runnerproto.QuestionAnswer, error), contain func(context.Context) error) error { |
| 194 | if poll == nil || contain == nil || r.Current == nil || q.ExpiresAt.IsZero() { |
| 195 | return runnerproto.ErrInvalid |
| 196 | } |
| 197 | stop := func(cause error) error { |
| 198 | cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| 199 | defer cancel() |
| 200 | invalidErr := r.Invalidate(cleanup, q) |
| 201 | if err := contain(cleanup); err != nil { |
| 202 | return err |
| 203 | } |
| 204 | if invalidErr != nil { |
| 205 | return invalidErr |
| 206 | } |
| 207 | return cause |
| 208 | } |
| 209 | timer := time.NewTimer(time.Until(q.ExpiresAt)) |
| 210 | defer timer.Stop() |
| 211 | tick := time.NewTicker(time.Duration(runnerproto.LongPollSeconds) * time.Second) |
| 212 | defer tick.Stop() |
| 213 | for { |
| 214 | deadline, err := r.Current(ctx, q) |
| 215 | if err != nil { |
| 216 | return stop(err) |
| 217 | } |
| 218 | q.ExpiresAt = deadline |
| 219 | if q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt) { |
| 220 | return stop(runnerproto.ErrInvalid) |
| 221 | } |
| 222 | timer.Reset(time.Until(q.ExpiresAt)) |
| 223 | pollCtx, cancel := context.WithDeadline(ctx, q.ExpiresAt) |
| 224 | var answer *runnerproto.QuestionAnswer |
| 225 | err = retryAuthority(pollCtx, func() error { var e error; answer, e = poll(pollCtx); return e }) |
| 226 | cancel() |
| 227 | if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil && !time.Now().Before(q.ExpiresAt) { |
| 228 | continue |
| 229 | } |
| 230 | if err != nil { |
| 231 | return stop(err) |
| 232 | } |
| 233 | if answer != nil { |
| 234 | if err := r.Deliver(ctx, q, *answer); err != nil { |
| 235 | return stop(err) |
| 236 | } |
| 237 | return nil |
| 238 | } |
| 239 | select { |
| 240 | case <-ctx.Done(): |
| 241 | return stop(ctx.Err()) |
| 242 | case <-timer.C: |
| 243 | // Recheck trusted renewal before treating the prior bound as expired. |
| 244 | case <-tick.C: |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | func (r *QuestionRelay) Invalidate(ctx context.Context, q runnerproto.Question) error { |
| 250 | if r.Journal == nil { |
| 251 | return runnerproto.ErrInvalid |
| 252 | } |
| 253 | key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID}) |
| 254 | if _, err := r.Journal.db.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,'','invalid') ON CONFLICT(answer_key) DO UPDATE SET state='invalid'", key); err != nil { |
| 255 | return r.Journal.storageFailure(ctx, err) |
| 256 | } |
| 257 | return nil |
| 258 | } |
| 259 | |