package runner import ( "context" "database/sql" "encoding/json" "errors" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type QuestionClient interface { Respond(context.Context, provider.Agent, provider.PermissionResponse) error Send(context.Context, provider.Agent, string, string) error } func DeliverAnswer(ctx context.Context, client QuestionClient, agent provider.Agent, q runnerproto.Question, answer runnerproto.QuestionAnswer) error { 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)) { return runnerproto.ErrInvalid } return client.Respond(ctx, agent, provider.PermissionResponse{RequestID: q.PermissionID, Behavior: answer.Behavior, UpdatedInput: answer.UpdatedInput}) } func SendFollowup(ctx context.Context, client QuestionClient, agent provider.Agent, message, id string, admit func(context.Context, string) error) error { if client == nil || admit == nil || message == "" || id == "" { return runnerproto.ErrInvalid } if err := admit(ctx, id); err != nil { return err } return client.Send(ctx, agent, message, id) } // QuestionFromEvent preserves the provider request, after bounded sanitization. // Unknown request kinds stay pending; they cannot pass QuestionAnswer.Validate. func QuestionFromEvent(e provider.RecordedEvent, id, task string, secrets []string) (runnerproto.Question, error) { var envelope struct { Request json.RawMessage `json:"request"` Event struct { Request json.RawMessage `json:"request"` } `json:"event"` } if len(e.Payload) > provider.MaxEventBytes || json.Unmarshal(e.Payload, &envelope) != nil { return runnerproto.Question{}, runnerproto.ErrInvalid } raw := envelope.Request if len(raw) == 0 { raw = envelope.Event.Request } var request struct { ID string `json:"id"` Kind string `json:"kind"` } if json.Unmarshal(raw, &request) != nil || request.ID != e.PermissionID { return runnerproto.Question{}, runnerproto.ErrInvalid } 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} if err := q.Validate(); err != nil { return runnerproto.Question{}, err } q.RawRequest = RedactJSON(raw, secrets) return q, q.Validate() } // QuestionRelay records delivery intent before Respond. A lost reply remains // uncertain; it cannot trigger an automatic second response or a new turn. type QuestionRelay struct { DirectSession provider.Session TurnID string Journal *Journal Client QuestionClient Agent provider.Agent // Current returns the trusted current lease bound, capped by the attempt deadline. Current func(context.Context, runnerproto.Question) (time.Time, error) } func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, answer runnerproto.QuestionAnswer) error { 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 { return runnerproto.ErrInvalid } if r.DirectSession.AttemptKey != "" { if q.SessionID != r.DirectSession.ID || q.AgentID != r.DirectSession.AttemptKey { return runnerproto.ErrInvalid } if err := r.Journal.currentDirectTurn(ctx, r.DirectSession, r.TurnID); err != nil { return err } } var err error q.ExpiresAt, err = r.Current(ctx, q) if err != nil { return err } if q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt) { return runnerproto.ErrInvalid } key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID}) hash := runnerproto.EventHash([]any{q.ID, q.Revision, q.RawRequest, answer}) if _, err := q.NativeApproval(); err == nil && answer.Behavior == "allow" { hash = runnerproto.EventHash([]any{q.ID, q.Revision, q.RawRequest, answer, q.AnsweredBy}) } if err := r.Journal.AdmissionAllowed(ctx); err != nil { return err } tx, err := r.Journal.db.BeginTx(ctx, nil) if err != nil { return r.Journal.storageFailure(ctx, err) } defer tx.Rollback() var old, state string err = tx.QueryRowContext(ctx, "SELECT content_hash,state FROM journal_answers WHERE answer_key=?", key).Scan(&old, &state) if err == nil { if r.DirectSession.AttemptKey != "" { var attempt, turn string 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 { return runnerproto.ErrInvalid } } if old != hash { return runnerproto.ErrInvalid } if state == "delivered" { return nil } return provider.ErrUncertain } if !errors.Is(err, sql.ErrNoRows) { tx.Rollback() return r.Journal.storageFailure(ctx, err) } if err = r.journalAdmissionTx(ctx, tx); err != nil { return err } if _, err = tx.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,?,'pending')", key, hash); err != nil { tx.Rollback() return r.Journal.storageFailure(ctx, err) } if r.DirectSession.AttemptKey != "" { if _, err = tx.ExecContext(ctx, "INSERT INTO direct_answer_scopes(answer_key,attempt,turn) VALUES(?,?,?)", key, r.DirectSession.AttemptKey, r.TurnID); err != nil { return err } } if _, nativeErr := q.NativeApproval(); nativeErr == nil && answer.Behavior == "allow" { if q.AnsweredBy == "" { return runnerproto.ErrInvalid } saved := q saved.Answer = &answer raw, err := json.Marshal(saved) if err != nil { return err } if _, err = tx.ExecContext(ctx, "INSERT INTO journal_supervisor(kind,state_key,body) VALUES('profile-approval',?,?)", key, raw); err != nil { tx.Rollback() return r.Journal.storageFailure(ctx, err) } } if err = tx.Commit(); err != nil { return r.Journal.storageFailure(ctx, err) } q.ExpiresAt, err = r.Current(ctx, q) if err != nil { return err } if r.DirectSession.AttemptKey != "" { if err := r.Journal.currentDirectTurn(ctx, r.DirectSession, r.TurnID); err != nil { return err } var state string if err := r.Journal.db.QueryRowContext(ctx, "SELECT state FROM journal_answers WHERE answer_key=?", key).Scan(&state); err != nil || state != "pending" { return runnerproto.ErrInvalid } } if err = DeliverAnswer(ctx, r.Client, r.Agent, q, answer); err != nil { return err } if _, err = r.Journal.db.ExecContext(ctx, "UPDATE journal_answers SET state='delivered' WHERE answer_key=? AND state='pending'", key); err != nil { return r.Journal.storageFailure(ctx, err) } return nil } func (r *QuestionRelay) journalAdmissionTx(ctx context.Context, tx *sql.Tx) error { var blocked int if err := tx.QueryRowContext(ctx, "SELECT blocked FROM journal_state WHERE id=1").Scan(&blocked); err != nil || blocked != 0 { return ErrJournal } return nil } // Wait releases and contains expired, cancelled or invalidated waits through // the supervisor. The poll callback is the authenticated instance answer API. func (r *QuestionRelay) Wait(ctx context.Context, q runnerproto.Question, poll func(context.Context) (*runnerproto.QuestionAnswer, error), contain func(context.Context) error) error { if poll == nil || contain == nil || r.Current == nil || q.ExpiresAt.IsZero() { return runnerproto.ErrInvalid } stop := func(cause error) error { cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() invalidErr := r.Invalidate(cleanup, q) if err := contain(cleanup); err != nil { return err } if invalidErr != nil { return invalidErr } return cause } timer := time.NewTimer(time.Until(q.ExpiresAt)) defer timer.Stop() tick := time.NewTicker(time.Duration(runnerproto.LongPollSeconds) * time.Second) defer tick.Stop() for { deadline, err := r.Current(ctx, q) if err != nil { return stop(err) } q.ExpiresAt = deadline if q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt) { return stop(runnerproto.ErrInvalid) } timer.Reset(time.Until(q.ExpiresAt)) pollCtx, cancel := context.WithDeadline(ctx, q.ExpiresAt) var answer *runnerproto.QuestionAnswer err = retryAuthority(pollCtx, func() error { var e error; answer, e = poll(pollCtx); return e }) cancel() if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil && !time.Now().Before(q.ExpiresAt) { continue } if err != nil { return stop(err) } if answer != nil { if err := r.Deliver(ctx, q, *answer); err != nil { return stop(err) } return nil } select { case <-ctx.Done(): return stop(ctx.Err()) case <-timer.C: // Recheck trusted renewal before treating the prior bound as expired. case <-tick.C: } } } func (r *QuestionRelay) Invalidate(ctx context.Context, q runnerproto.Question) error { if r.Journal == nil { return runnerproto.ErrInvalid } key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID}) 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 { return r.Journal.storageFailure(ctx, err) } return nil }