| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "path/filepath" |
| 9 | "sync/atomic" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/runner/planflow" |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 16 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 17 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 18 | ) |
| 19 | |
| 20 | func (w *BugWorkflow) directModel(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard, current func(context.Context) error, ws workspace.Workspace, policy provider.ReadPolicy, artifacts []team.Artifact) error { |
| 21 | launcher := w.cfg.Launchers[r.Claim.Assignment.Selection.Provider] |
| 22 | if launcher == nil { |
| 23 | return provider.ErrProvider |
| 24 | } |
| 25 | profile, err := planflow.Validate(r.Claim.Assignment, r.Claim.Brief) |
| 26 | if err != nil { |
| 27 | return err |
| 28 | } |
| 29 | var proxy *ToolProxy |
| 30 | ask := w.directAsk(s, r, l, current) |
| 31 | questionCurrent := func(ctx context.Context, q runnerproto.Question) (time.Time, error) { |
| 32 | _, err := s.currentDirectQuestion(ctx, r, q, current) |
| 33 | return l.bound(), err |
| 34 | } |
| 35 | answerer := func(ctx context.Context, q runnerproto.Question) (string, error) { |
| 36 | saved, err := s.currentDirectQuestion(ctx, r, q, current) |
| 37 | return saved.AnsweredBy, err |
| 38 | } |
| 39 | b := ToolBinding{ReadPolicy: policy, Copy: w.cfg.Copy, InstanceID: w.cfg.InstanceID, TaskID: r.Claim.Assignment.TaskID, Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, Tools: profile.Tools(), LeaseDeadline: l.bound(), Agent: provider.Agent{ServerID: "direct", Provider: r.Claim.Assignment.Selection.Provider, AccountID: r.Claim.Assignment.Selection.AccountID, Family: r.Claim.Assignment.Selection.Family, Model: r.Claim.Assignment.Selection.Model}, Isolation: r.Claim.Assignment.Selection.Isolation, Journal: s.journal, Current: current} |
| 40 | b.Ask = func(ctx context.Context, bound ToolBinding, id string, args json.RawMessage) (json.RawMessage, error) { |
| 41 | relay := DirectQuestionRelay{Binding: bound, Proxy: proxy, Launcher: launcher, Current: questionCurrent, Answerer: answerer} |
| 42 | answer, err := relay.Ask(ctx, id, args, ask) |
| 43 | if err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 | pending, err := s.journal.ToolSubmissions(ctx, 128) |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | for _, submission := range pending { |
| 51 | if submission.RequestID == id && submission.Name == "ask_person" && submission.Agent == bound.Agent && submission.Attempt == bound.Attempt && submission.Fence == bound.Fence && submission.TaskID == bound.TaskID { |
| 52 | if err = s.journal.AckTool(ctx, submission); err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | if err = s.resolveDeliveredQuestions(ctx, r); err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | return answer, nil |
| 61 | } |
| 62 | if permission, ok := launcher.(interface { |
| 63 | Permission(context.Context, provider.Session, json.RawMessage) (json.RawMessage, error) |
| 64 | }); ok { |
| 65 | b.Permission = func(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) { |
| 66 | proxy.broker.mu.Lock() |
| 67 | session := proxy.broker.binding.Session |
| 68 | proxy.broker.mu.Unlock() |
| 69 | return permission.Permission(ctx, session, raw) |
| 70 | } |
| 71 | } |
| 72 | proxy, err = OpenToolProxy(ctx, b) |
| 73 | if err != nil { |
| 74 | return err |
| 75 | } |
| 76 | s.mu.Lock() |
| 77 | s.activeProxy = proxy |
| 78 | s.mu.Unlock() |
| 79 | launch, release, err := w.cfg.Launch(ctx, r.Claim, ws, proxy) |
| 80 | if release != nil { |
| 81 | s.activeRelease = release |
| 82 | } |
| 83 | if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | if err = current(ctx); err != nil { |
| 87 | return err |
| 88 | } |
| 89 | r.Phase = "opening-provider" |
| 90 | if err = s.save(ctx, r); err != nil { |
| 91 | return err |
| 92 | } |
| 93 | session, err := launcher.Open(ctx, launch) |
| 94 | if err != nil { |
| 95 | return err |
| 96 | } |
| 97 | r.Session = session |
| 98 | r.Agent = provider.Agent{ServerID: "direct", AgentID: session.AttemptKey, ProviderSessionID: session.ID, Provider: session.Provider, AccountID: session.AccountID, Family: session.Family, Model: session.Model} |
| 99 | if err = s.save(ctx, r); err != nil { |
| 100 | return err |
| 101 | } |
| 102 | if err = w.cfg.Witness.record(ctx, "session", attemptKey(r.Claim.Scope, r.Claim.Handle), r.Agent); err != nil { |
| 103 | return err |
| 104 | } |
| 105 | events, err := launcher.Events(ctx, session) |
| 106 | if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | var action atomic.Int64 |
| 110 | pump := EventPump{Journal: s.journal, Contain: func(ctx context.Context) error { return launcher.Interrupt(ctx, session) }, Upload: func(ctx context.Context, e Event) error { |
| 111 | return s.uploadDirectEvent(ctx, r, e) |
| 112 | }} |
| 113 | streamCtx, stopStream := context.WithCancel(ctx) |
| 114 | notices := make(chan provider.Event, 64) |
| 115 | drainDone := make(chan error, 1) |
| 116 | go func() { |
| 117 | for { |
| 118 | select { |
| 119 | case <-streamCtx.Done(): |
| 120 | drainDone <- streamCtx.Err() |
| 121 | return |
| 122 | case e, ok := <-events: |
| 123 | if !ok { |
| 124 | drainDone <- nil |
| 125 | return |
| 126 | } |
| 127 | template := Event{Version: 2, TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, ServerID: "direct", ActionID: team.ActionID(action.Load()), SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation} |
| 128 | if err := pump.AppendDirect(streamCtx, session, e, template); err != nil { |
| 129 | drainDone <- err |
| 130 | return |
| 131 | } |
| 132 | if e.Kind == "request" || e.Kind == "turn.completed" || e.Kind == "turn.failed" { |
| 133 | select { |
| 134 | case notices <- e: |
| 135 | case <-streamCtx.Done(): |
| 136 | drainDone <- streamCtx.Err() |
| 137 | return |
| 138 | default: |
| 139 | drainDone <- errDirectUncertain |
| 140 | return |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | }() |
| 146 | defer func() { stopStream(); <-drainDone }() |
| 147 | // Upload independently: a slow instance or person must not stall capture. |
| 148 | uploadCtx, stopUpload := context.WithCancel(ctx) |
| 149 | uploadDone := make(chan struct{}) |
| 150 | go func() { |
| 151 | defer close(uploadDone) |
| 152 | ticker := time.NewTicker(time.Second) |
| 153 | defer ticker.Stop() |
| 154 | for { |
| 155 | select { |
| 156 | case <-uploadCtx.Done(): |
| 157 | return |
| 158 | case <-ticker.C: |
| 159 | _ = pump.Flush(uploadCtx, 128) |
| 160 | } |
| 161 | } |
| 162 | }() |
| 163 | defer func() { stopUpload(); <-uploadDone }() |
| 164 | ready := Event{Version: 2, ID: r.request("ready").RequestID, TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, ServerID: "direct", AgentID: session.AttemptKey, SessionID: session.ID, Epoch: session.AttemptKey, Kind: "timeline_ready", Payload: json.RawMessage(`{}`), SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation} |
| 165 | if err = pump.Append(ctx, ready, nil); err != nil { |
| 166 | return err |
| 167 | } |
| 168 | if err = pump.Flush(ctx, 128); err != nil { |
| 169 | return err |
| 170 | } |
| 171 | message, err := buildTurnPrompt(r.Claim, artifacts) |
| 172 | if err != nil { |
| 173 | return err |
| 174 | } |
| 175 | if err = current(ctx); err != nil { |
| 176 | return err |
| 177 | } |
| 178 | payload, err := turnIntentPayload(session.Provider, session.Model, message) |
| 179 | if err != nil { |
| 180 | return err |
| 181 | } |
| 182 | q := r.request("turn-intent-0") |
| 183 | q.Intent = &team.IntentSpec{Key: q.RequestID, Operation: team.OpProviderCall, Payload: payload, Reserve: team.Usage{Calls: 1, InputTokens: 32000, OutputTokens: 4000, CostUnavailable: true}} |
| 184 | var admitted team.ActionID |
| 185 | if err = retryAuthority(ctx, func() error { return s.api.Call(ctx, "intend", q, &admitted) }); err != nil { |
| 186 | return err |
| 187 | } |
| 188 | action.Store(int64(admitted)) |
| 189 | q = r.request("turn-admit-0") |
| 190 | q.ActionID = admitted |
| 191 | dir := filepath.Join(w.cfg.StateDir, "admissions") |
| 192 | if err = runnerproto.JournalAdmission(dir, q); err != nil { |
| 193 | return err |
| 194 | } |
| 195 | var ticket team.AdmissionTicket |
| 196 | if err = s.admitDirect(ctx, r, q, &ticket); err != nil { |
| 197 | return err |
| 198 | } |
| 199 | turn := provider.Turn{ID: r.request("turn-0").RequestID, AdmissionID: q.RequestID, Prompt: message} |
| 200 | if err = proxy.BindTurn(session, turn.ID); err != nil { |
| 201 | return err |
| 202 | } |
| 203 | proxy.broker.mu.Lock() |
| 204 | bound := proxy.broker.binding |
| 205 | proxy.broker.mu.Unlock() |
| 206 | relay := DirectQuestionRelay{Binding: bound, Proxy: proxy, Launcher: launcher, Current: questionCurrent, Answerer: answerer} |
| 207 | if err = current(ctx); err != nil { |
| 208 | return err |
| 209 | } |
| 210 | if err = runnerproto.ConsumeTicket(dir, q.RequestID, ticket, time.Now().UTC(), ticket.Incarnation); err != nil { |
| 211 | return err |
| 212 | } |
| 213 | if err = DispatchDirectTurn(ctx, proxy, launcher, session, turn); err != nil { |
| 214 | return err |
| 215 | } |
| 216 | for { |
| 217 | e, err := nextDirectNotice(ctx, notices, drainDone) |
| 218 | if err != nil { |
| 219 | return err |
| 220 | } |
| 221 | if e.Kind == "request" { |
| 222 | if err = pump.Flush(ctx, 128); err != nil { |
| 223 | return err |
| 224 | } |
| 225 | // Respond returning nil is transport success, never approval evidence. |
| 226 | if err = relay.Handle(ctx, e, ask); err != nil { |
| 227 | return err |
| 228 | } |
| 229 | if err = s.resolveDeliveredQuestions(ctx, r); err != nil { |
| 230 | return err |
| 231 | } |
| 232 | continue |
| 233 | } |
| 234 | // Cancellation may have quarantined the turn before its terminal frame was normalized. |
| 235 | if e.Kind == "turn.completed" { |
| 236 | if err = s.journal.requireDirectCompletion(ctx, session, e.TurnID); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | } else if len(e.Payload) == 0 { |
| 240 | return errDirectUncertain |
| 241 | } |
| 242 | // AppendDirect committed the terminal event before publishing this notice. |
| 243 | if err = pump.Drain(ctx); err != nil { |
| 244 | return err |
| 245 | } |
| 246 | r.InFlightAction = 0 |
| 247 | if err = s.save(ctx, r); err != nil { |
| 248 | return err |
| 249 | } |
| 250 | if e.Kind == "turn.failed" { |
| 251 | return team.ErrEvidence |
| 252 | } |
| 253 | return finishDirectStream(ctx, func() error { return launcher.Close(ctx, session) }, drainDone, pump.Drain) |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | func nextDirectNotice(ctx context.Context, notices <-chan provider.Event, done chan error) (provider.Event, error) { |
| 258 | select { |
| 259 | case event := <-notices: |
| 260 | return event, nil |
| 261 | default: |
| 262 | } |
| 263 | select { |
| 264 | case event := <-notices: |
| 265 | return event, nil |
| 266 | case <-ctx.Done(): |
| 267 | return provider.Event{}, ctx.Err() |
| 268 | case err := <-done: |
| 269 | done <- err |
| 270 | if err == nil { |
| 271 | err = errDirectUncertain |
| 272 | } |
| 273 | select { |
| 274 | case event := <-notices: |
| 275 | return event, nil |
| 276 | default: |
| 277 | return provider.Event{}, err |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | func (w *BugWorkflow) directAsk(s *Supervisor, r *attemptState, l *leaseGuard, current func(context.Context) error) func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error) { |
| 283 | return func(ctx context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) { |
| 284 | q.AssignmentID = r.Claim.Assignment.ID |
| 285 | q.ExpiresAt = l.bound() |
| 286 | if err := w.cfg.Witness.record(ctx, "question", q.ID, q); err != nil { |
| 287 | return runnerproto.QuestionAnswer{}, err |
| 288 | } |
| 289 | request := r.request("question-" + q.ID) |
| 290 | request.Question = &q |
| 291 | var saved runnerproto.Question |
| 292 | if err := s.api.Call(ctx, "questions", request, &saved); err != nil { |
| 293 | return runnerproto.QuestionAnswer{}, err |
| 294 | } |
| 295 | ticker := time.NewTicker(time.Second) |
| 296 | defer ticker.Stop() |
| 297 | for { |
| 298 | if err := current(ctx); err != nil { |
| 299 | return runnerproto.QuestionAnswer{}, err |
| 300 | } |
| 301 | var answers []runnerproto.Question |
| 302 | if err := retryAuthority(ctx, func() error { return s.api.Call(ctx, "answers", r.request("answers"), &answers) }); err != nil { |
| 303 | return runnerproto.QuestionAnswer{}, err |
| 304 | } |
| 305 | for _, answer := range answers { |
| 306 | if answer.ID != saved.ID || answer.Answer == nil { |
| 307 | continue |
| 308 | } |
| 309 | if answer.Revision != saved.Revision || answer.AgentID != saved.AgentID || answer.SessionID != saved.SessionID || saved.ValidateAnswer(*answer.Answer) != nil { |
| 310 | return runnerproto.QuestionAnswer{}, provider.ErrIdentity |
| 311 | } |
| 312 | return *answer.Answer, nil |
| 313 | } |
| 314 | select { |
| 315 | case <-ctx.Done(): |
| 316 | return runnerproto.QuestionAnswer{}, ctx.Err() |
| 317 | case <-ticker.C: |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | // Resolution acknowledges delivery, never an approval inferred from Respond's return. |
| 324 | func (s *Supervisor) resolveDeliveredQuestions(ctx context.Context, r *attemptState) error { |
| 325 | var questions []runnerproto.Question |
| 326 | if err := s.journal.readStates(ctx, "witness-question", &questions); err != nil { |
| 327 | return err |
| 328 | } |
| 329 | for _, q := range questions { |
| 330 | if q.AssignmentID != r.Claim.Assignment.ID || q.TaskID != r.Claim.Assignment.TaskID || q.Attempt != int64(r.Claim.Handle.Attempt) || q.Fence != r.Claim.Handle.Fence || q.AgentID != r.Session.AttemptKey || q.SessionID != r.Session.ID { |
| 331 | continue |
| 332 | } |
| 333 | key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID}) |
| 334 | var state string |
| 335 | err := s.journal.db.QueryRowContext(ctx, "SELECT state FROM journal_answers WHERE answer_key=?", key).Scan(&state) |
| 336 | if errors.Is(err, sql.ErrNoRows) { |
| 337 | continue |
| 338 | } |
| 339 | if err != nil { |
| 340 | return err |
| 341 | } |
| 342 | if state != "delivered" { |
| 343 | continue |
| 344 | } |
| 345 | request := r.request("question-resolved-" + q.ID) |
| 346 | request.Question = &q |
| 347 | if err = s.api.Call(ctx, "question_resolved", request, nil); err != nil { |
| 348 | return err |
| 349 | } |
| 350 | } |
| 351 | return nil |
| 352 | } |
| 353 | |
| 354 | func (j *Journal) requireDirectCompletion(ctx context.Context, s provider.Session, turn string) error { |
| 355 | var state string |
| 356 | if err := j.db.QueryRowContext(ctx, "SELECT state FROM direct_turns WHERE attempt=? AND session=? AND turn=?", s.AttemptKey, s.ID, turn).Scan(&state); err != nil { |
| 357 | return err |
| 358 | } |
| 359 | if state != "completed" { |
| 360 | return errDirectUncertain |
| 361 | } |
| 362 | return nil |
| 363 | } |
| 364 | |
| 365 | func (s *Supervisor) currentDirectQuestion(ctx context.Context, r *attemptState, q runnerproto.Question, current func(context.Context) error) (runnerproto.Question, error) { |
| 366 | if err := current(ctx); err != nil { |
| 367 | return runnerproto.Question{}, err |
| 368 | } |
| 369 | var answers []runnerproto.Question |
| 370 | if err := s.api.Call(ctx, "answers", r.request("answers-current"), &answers); err != nil { |
| 371 | return runnerproto.Question{}, err |
| 372 | } |
| 373 | for _, saved := range answers { |
| 374 | if saved.ID == q.ID { |
| 375 | if saved.Revision != q.Revision || saved.PermissionID != q.PermissionID || saved.SessionID != q.SessionID || saved.AgentID != q.AgentID { |
| 376 | return runnerproto.Question{}, provider.ErrIdentity |
| 377 | } |
| 378 | if q.Answer != nil && (saved.Answer == nil || saved.AnsweredBy == "" || (q.AnsweredBy != "" && saved.AnsweredBy != q.AnsweredBy) || saved.TaskID != q.TaskID || saved.Attempt != q.Attempt || saved.Fence != q.Fence || !runnerproto.SameRequestJSON(saved.RawRequest, q.RawRequest) || runnerproto.EventHash(saved.Answer) != runnerproto.EventHash(q.Answer)) { |
| 379 | return runnerproto.Question{}, provider.ErrIdentity |
| 380 | } |
| 381 | return saved, nil |
| 382 | } |
| 383 | } |
| 384 | if q.Answer != nil { |
| 385 | return runnerproto.Question{}, provider.ErrIdentity |
| 386 | } |
| 387 | return runnerproto.Question{}, nil |
| 388 | } |
| 389 | |