package runner import ( "context" "database/sql" "encoding/json" "errors" "path/filepath" "sync/atomic" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/planflow" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/runnerproto" ) 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 { launcher := w.cfg.Launchers[r.Claim.Assignment.Selection.Provider] if launcher == nil { return provider.ErrProvider } profile, err := planflow.Validate(r.Claim.Assignment, r.Claim.Brief) if err != nil { return err } var proxy *ToolProxy ask := w.directAsk(s, r, l, current) questionCurrent := func(ctx context.Context, q runnerproto.Question) (time.Time, error) { _, err := s.currentDirectQuestion(ctx, r, q, current) return l.bound(), err } answerer := func(ctx context.Context, q runnerproto.Question) (string, error) { saved, err := s.currentDirectQuestion(ctx, r, q, current) return saved.AnsweredBy, err } 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} b.Ask = func(ctx context.Context, bound ToolBinding, id string, args json.RawMessage) (json.RawMessage, error) { relay := DirectQuestionRelay{Binding: bound, Proxy: proxy, Launcher: launcher, Current: questionCurrent, Answerer: answerer} answer, err := relay.Ask(ctx, id, args, ask) if err != nil { return nil, err } pending, err := s.journal.ToolSubmissions(ctx, 128) if err != nil { return nil, err } for _, submission := range pending { if submission.RequestID == id && submission.Name == "ask_person" && submission.Agent == bound.Agent && submission.Attempt == bound.Attempt && submission.Fence == bound.Fence && submission.TaskID == bound.TaskID { if err = s.journal.AckTool(ctx, submission); err != nil { return nil, err } } } if err = s.resolveDeliveredQuestions(ctx, r); err != nil { return nil, err } return answer, nil } if permission, ok := launcher.(interface { Permission(context.Context, provider.Session, json.RawMessage) (json.RawMessage, error) }); ok { b.Permission = func(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) { proxy.broker.mu.Lock() session := proxy.broker.binding.Session proxy.broker.mu.Unlock() return permission.Permission(ctx, session, raw) } } proxy, err = OpenToolProxy(ctx, b) if err != nil { return err } s.mu.Lock() s.activeProxy = proxy s.mu.Unlock() launch, release, err := w.cfg.Launch(ctx, r.Claim, ws, proxy) if release != nil { s.activeRelease = release } if err != nil { return err } if err = current(ctx); err != nil { return err } r.Phase = "opening-provider" if err = s.save(ctx, r); err != nil { return err } session, err := launcher.Open(ctx, launch) if err != nil { return err } r.Session = session r.Agent = provider.Agent{ServerID: "direct", AgentID: session.AttemptKey, ProviderSessionID: session.ID, Provider: session.Provider, AccountID: session.AccountID, Family: session.Family, Model: session.Model} if err = s.save(ctx, r); err != nil { return err } if err = w.cfg.Witness.record(ctx, "session", attemptKey(r.Claim.Scope, r.Claim.Handle), r.Agent); err != nil { return err } events, err := launcher.Events(ctx, session) if err != nil { return err } var action atomic.Int64 pump := EventPump{Journal: s.journal, Contain: func(ctx context.Context) error { return launcher.Interrupt(ctx, session) }, Upload: func(ctx context.Context, e Event) error { return s.uploadDirectEvent(ctx, r, e) }} streamCtx, stopStream := context.WithCancel(ctx) notices := make(chan provider.Event, 64) drainDone := make(chan error, 1) go func() { for { select { case <-streamCtx.Done(): drainDone <- streamCtx.Err() return case e, ok := <-events: if !ok { drainDone <- nil return } 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} if err := pump.AppendDirect(streamCtx, session, e, template); err != nil { drainDone <- err return } if e.Kind == "request" || e.Kind == "turn.completed" || e.Kind == "turn.failed" { select { case notices <- e: case <-streamCtx.Done(): drainDone <- streamCtx.Err() return default: drainDone <- errDirectUncertain return } } } } }() defer func() { stopStream(); <-drainDone }() // Upload independently: a slow instance or person must not stall capture. uploadCtx, stopUpload := context.WithCancel(ctx) uploadDone := make(chan struct{}) go func() { defer close(uploadDone) ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-uploadCtx.Done(): return case <-ticker.C: _ = pump.Flush(uploadCtx, 128) } } }() defer func() { stopUpload(); <-uploadDone }() 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} if err = pump.Append(ctx, ready, nil); err != nil { return err } if err = pump.Flush(ctx, 128); err != nil { return err } message, err := buildTurnPrompt(r.Claim, artifacts) if err != nil { return err } if err = current(ctx); err != nil { return err } payload, err := turnIntentPayload(session.Provider, session.Model, message) if err != nil { return err } q := r.request("turn-intent-0") q.Intent = &team.IntentSpec{Key: q.RequestID, Operation: team.OpProviderCall, Payload: payload, Reserve: team.Usage{Calls: 1, InputTokens: 32000, OutputTokens: 4000, CostUnavailable: true}} var admitted team.ActionID if err = retryAuthority(ctx, func() error { return s.api.Call(ctx, "intend", q, &admitted) }); err != nil { return err } action.Store(int64(admitted)) q = r.request("turn-admit-0") q.ActionID = admitted dir := filepath.Join(w.cfg.StateDir, "admissions") if err = runnerproto.JournalAdmission(dir, q); err != nil { return err } var ticket team.AdmissionTicket if err = s.admitDirect(ctx, r, q, &ticket); err != nil { return err } turn := provider.Turn{ID: r.request("turn-0").RequestID, AdmissionID: q.RequestID, Prompt: message} if err = proxy.BindTurn(session, turn.ID); err != nil { return err } proxy.broker.mu.Lock() bound := proxy.broker.binding proxy.broker.mu.Unlock() relay := DirectQuestionRelay{Binding: bound, Proxy: proxy, Launcher: launcher, Current: questionCurrent, Answerer: answerer} if err = current(ctx); err != nil { return err } if err = runnerproto.ConsumeTicket(dir, q.RequestID, ticket, time.Now().UTC(), ticket.Incarnation); err != nil { return err } if err = DispatchDirectTurn(ctx, proxy, launcher, session, turn); err != nil { return err } for { e, err := nextDirectNotice(ctx, notices, drainDone) if err != nil { return err } if e.Kind == "request" { if err = pump.Flush(ctx, 128); err != nil { return err } // Respond returning nil is transport success, never approval evidence. if err = relay.Handle(ctx, e, ask); err != nil { return err } if err = s.resolveDeliveredQuestions(ctx, r); err != nil { return err } continue } // Cancellation may have quarantined the turn before its terminal frame was normalized. if e.Kind == "turn.completed" { if err = s.journal.requireDirectCompletion(ctx, session, e.TurnID); err != nil { return err } } else if len(e.Payload) == 0 { return errDirectUncertain } // AppendDirect committed the terminal event before publishing this notice. if err = pump.Drain(ctx); err != nil { return err } r.InFlightAction = 0 if err = s.save(ctx, r); err != nil { return err } if e.Kind == "turn.failed" { return team.ErrEvidence } return finishDirectStream(ctx, func() error { return launcher.Close(ctx, session) }, drainDone, pump.Drain) } } func nextDirectNotice(ctx context.Context, notices <-chan provider.Event, done chan error) (provider.Event, error) { select { case event := <-notices: return event, nil default: } select { case event := <-notices: return event, nil case <-ctx.Done(): return provider.Event{}, ctx.Err() case err := <-done: done <- err if err == nil { err = errDirectUncertain } select { case event := <-notices: return event, nil default: return provider.Event{}, err } } } func (w *BugWorkflow) directAsk(s *Supervisor, r *attemptState, l *leaseGuard, current func(context.Context) error) func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error) { return func(ctx context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) { q.AssignmentID = r.Claim.Assignment.ID q.ExpiresAt = l.bound() if err := w.cfg.Witness.record(ctx, "question", q.ID, q); err != nil { return runnerproto.QuestionAnswer{}, err } request := r.request("question-" + q.ID) request.Question = &q var saved runnerproto.Question if err := s.api.Call(ctx, "questions", request, &saved); err != nil { return runnerproto.QuestionAnswer{}, err } ticker := time.NewTicker(time.Second) defer ticker.Stop() for { if err := current(ctx); err != nil { return runnerproto.QuestionAnswer{}, err } var answers []runnerproto.Question if err := retryAuthority(ctx, func() error { return s.api.Call(ctx, "answers", r.request("answers"), &answers) }); err != nil { return runnerproto.QuestionAnswer{}, err } for _, answer := range answers { if answer.ID != saved.ID || answer.Answer == nil { continue } if answer.Revision != saved.Revision || answer.AgentID != saved.AgentID || answer.SessionID != saved.SessionID || saved.ValidateAnswer(*answer.Answer) != nil { return runnerproto.QuestionAnswer{}, provider.ErrIdentity } return *answer.Answer, nil } select { case <-ctx.Done(): return runnerproto.QuestionAnswer{}, ctx.Err() case <-ticker.C: } } } } // Resolution acknowledges delivery, never an approval inferred from Respond's return. func (s *Supervisor) resolveDeliveredQuestions(ctx context.Context, r *attemptState) error { var questions []runnerproto.Question if err := s.journal.readStates(ctx, "witness-question", &questions); err != nil { return err } for _, q := range questions { 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 { continue } key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID}) var state string err := s.journal.db.QueryRowContext(ctx, "SELECT state FROM journal_answers WHERE answer_key=?", key).Scan(&state) if errors.Is(err, sql.ErrNoRows) { continue } if err != nil { return err } if state != "delivered" { continue } request := r.request("question-resolved-" + q.ID) request.Question = &q if err = s.api.Call(ctx, "question_resolved", request, nil); err != nil { return err } } return nil } func (j *Journal) requireDirectCompletion(ctx context.Context, s provider.Session, turn string) error { var state string 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 { return err } if state != "completed" { return errDirectUncertain } return nil } func (s *Supervisor) currentDirectQuestion(ctx context.Context, r *attemptState, q runnerproto.Question, current func(context.Context) error) (runnerproto.Question, error) { if err := current(ctx); err != nil { return runnerproto.Question{}, err } var answers []runnerproto.Question if err := s.api.Call(ctx, "answers", r.request("answers-current"), &answers); err != nil { return runnerproto.Question{}, err } for _, saved := range answers { if saved.ID == q.ID { if saved.Revision != q.Revision || saved.PermissionID != q.PermissionID || saved.SessionID != q.SessionID || saved.AgentID != q.AgentID { return runnerproto.Question{}, provider.ErrIdentity } 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)) { return runnerproto.Question{}, provider.ErrIdentity } return saved, nil } } if q.Answer != nil { return runnerproto.Question{}, provider.ErrIdentity } return runnerproto.Question{}, nil }