package thin import ( "context" "database/sql" "errors" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/wire" ) // heldRecheck bounds how long a turn held for a connection waits before // it looks again on its own (a connection added by the terminal login, // or one whose cool-off ended, wakes it sooner). const heldRecheck = time.Minute // converse runs one turn on the person's chosen connection (spec §3). A // turn the provider refuses on quota marks that connection limited and // starts again, as a new attempt, on the next connection the choice // gives: a new session there, seeded from the notebook and the tail like // any fresh session, with the draft of the refused attempt discarded and // one quiet switched line on the reply. When no connection can answer, // the turn is held (state running, reason no_connection): the message // waits and the turn goes on its own when a connection returns. func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run, act func(kind, tool string)) TurnResult { var switched *wire.Switched held := false // The connection that answered the person last: a reply from another // one says so, whether this turn moved or waited for it. conn := connKey(person, r.Lane) last, _ := e.State.meta(ctx, conn) // An Assistant person turn's glance: asked once, beside the first // attempt, and closed when the reply's first words go or the turn // ends, so it is sent before them or never. var gl *glanceRun defer func() { if gl != nil { gl.close() } }() for { b, choice, err := e.choose(ctx, person, conn, w.connID) if errors.Is(err, ErrNoConnection) { if !held { held = true e.log("runner hold", e.State.Hold(e.ctx, *r, wire.ReasonNoConnection)) e.Notify() } if !e.waitConnection(ctx, person, w) { return TurnResult{Reason: "cancelled"} } continue } if err != nil { e.log("runner choose", err) return TurnResult{Reason: "account_unavailable"} } if held { held = false e.log("runner hold", e.State.Hold(e.ctx, *r, "")) e.Notify() } if err := e.seat(ctx, person, r.Lane, conn, w, b); err != nil { e.log("coordinator open", err) return TurnResult{Reason: "account_unavailable"} } _ = choice var offset int64 var done []string if r.Attempt > 1 { done = e.State.doneEarlier(ctx, r.TurnID, r.Attempt) } if gl == nil && e.Glance != nil && r.Lane == wire.LaneAssistant && r.Kind == wire.TurnPerson { gl = e.startGlance(ctx, person, w, r, b) } res := w.coord.Turn(ctx, TurnInput{PlacementNotes: r.PlacementNotes, Person: person, Lane: r.Lane, TurnID: r.TurnID, Kind: r.Kind, Attempt: r.Attempt, Text: r.Text, PersonText: r.PersonText, Tail: r.Tail, Attachments: r.Attachments, Earlier: r.Earlier, EarlierMore: r.EarlierMore, Received: r.Received, Activity: act, Done: done}, func(text string) { if gl != nil { gl.close() } e.Emit(wire.DeltaReport{TurnID: r.TurnID, Attempt: r.Attempt, Offset: offset, Text: text}) offset += int64(len(text)) }) if e.Conns != nil && res.Seen != nil { e.Conns.Observe(b.ID, *res.Seen, res.Plan) } if res.Limit != nil && e.Conns != nil { e.Conns.Limit(b.ID, *res.Limit) } if res.SignIn && e.Conns != nil { e.Conns.SignInAgain(b.ID) } res.rows = usageRows(res.Usage, b, r.Attempt, wire.OutcomeReplied) if res.Limit == nil && !res.SignIn || !res.Proven || ctx.Err() != nil || e.Conns == nil { if res.Reason == "" && e.Conns != nil { // An answer proves the credential, whatever a check said. e.Conns.Answered(b.ID) e.log("runner session", e.State.setMeta(context.WithoutCancel(ctx), conn, b.ID)) } if switched == nil && res.Reason == "" && last != "" && last != b.ID && e.Conns != nil { switched = e.Conns.LimitedFrom(last) } if switched != nil && res.Reason == "" { switched.To = b.Provider res.Switched = switched } res.glance = gl // The glance harness stays warm beside the Assistant's. if r.Lane == wire.LaneAssistant && res.Reason == "" { e.warmGlance(person, w, b) } return res } // Refused on quota, and the attempt's exit proven: a new attempt, // advanced durably before anything runs, on the next connection. if switched == nil { switched = e.Conns.LimitedFrom(b.ID) if res.SignIn { switched = &wire.Switched{From: b.Provider} } } w.coord.Close() w.coord = nil if err := e.State.Retry(e.ctx, r, waitReason(res), usageRows(res.Usage, b, r.Attempt, wire.OutcomeFailed)); err != nil { e.log("runner retry", err) return TurnResult{Reason: "limited"} } e.mu.Lock() w.attempt = r.Attempt e.mu.Unlock() e.Notify() } } // seat makes the worker's harness the one on connection b, closing one // on another connection; conn is the lane's connKey. func (e *Engine) seat(ctx context.Context, person, lane, conn string, w *worker, b runner.AccountBinding) error { if w.coord != nil && w.connID == b.ID { return nil } if w.coord != nil { w.coord.Close() w.coord = nil } // A session the conversation went on without is stale: coming back // to a connection starts afresh from the notebook and the tail, never // resumes a session that missed turns. if last, _ := e.State.meta(ctx, conn); last != "" && last != b.ID { e.log("runner session", e.State.deleteSession(ctx, person, lane)) } c, err := e.Open(person, lane, b) if err != nil { return err } w.coord, w.connID = c, b.ID return nil } // usageRows fills an attempt's rows with what ran it: one row with no // figures (complete false) when the harness reported nothing, so the // attempt is recorded all the same. func usageRows(rows []wire.Usage, b runner.AccountBinding, attempt int64, outcome string) []wire.Usage { if b.ID == "" { // No connection (an engine test without one): nothing to key a row by. return []wire.Usage{} } if len(rows) == 0 { rows = []wire.Usage{{}} } out := make([]wire.Usage, len(rows)) for i, u := range rows { u.Provider, u.Connection, u.Attempt, u.Outcome = b.Provider, b.ID, attempt, outcome if u.Model == "" { u.Model = b.Model } out[i] = u } return out } // waitReason is why a turn waits between attempts: its connection was // limited, or refused the credential. func waitReason(res TurnResult) string { if res.SignIn { return "sign_in_again" } return "limited" } // connKey is where the connection that answered a lane last is kept. // The coordinator's key is the one it had before the Assistant. func connKey(person, lane string) string { if lane == wire.LaneCoordinator { return "conn:" + person } return "conn:" + person + "#" + lane } // choose asks Conns for the connection of the person's lane (conn is its // connKey); without Conns (engine tests) every turn runs on a zero // binding. func (e *Engine) choose(ctx context.Context, person, conn, current string) (runner.AccountBinding, connect.Choice, error) { if e.Conns == nil { return runner.AccountBinding{}, connect.Choice{Reason: connect.ReasonOnlyOption}, nil } if current == "" { // After a restart the session's connection is the one that // answered last: stickiness holds across processes. current, _ = e.State.meta(ctx, conn) } return e.Conns.Choose(ctx, person, connect.RoleCoordinator, current, nil) } // waitConnection waits for a connection to come back: a change in the // connections, the earliest provider reset, or a minute. False means the // turn was cancelled or the runner is stopping. func (e *Engine) waitConnection(ctx context.Context, person string, w *worker) bool { wait := heldRecheck if at := e.Conns.NextCheck(person); !at.IsZero() { wait = min(wait, max(time.Until(at), 0)+time.Second) } select { case <-ctx.Done(): return false case <-w.conn: case <-time.After(wait): } return true } // Hold reports a held turn as waiting for a connection (reason // no_connection) or, with an empty reason, as running again. The run // stays held here; only the instance's view changes. func (s *State) Hold(ctx context.Context, r run, reason string) error { state := wire.TurnRunning if reason != "" { state = wire.TurnWaiting } return s.tx(ctx, func(t *sql.Tx) error { return s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: state, Reason: reason}) }) } // Retry starts a new attempt of a held run after its connection was // refused: the instance learns of it (state running, the new attempt) // in the same transaction, so a draft of the old attempt is dropped and // a cancel names the new one. func (s *State) Retry(ctx context.Context, r *run, reason string, used []wire.Usage) error { err := s.tx(ctx, func(t *sql.Tx) error { res, err := t.Exec("UPDATE runs SET attempt=attempt+1 WHERE turn_id=? AND attempt=? AND state=?", r.TurnID, r.Attempt, runRunning) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return errors.New("run not held") } if len(used) > 0 { // What the refused attempt used, recorded against it. if err = s.enqueue(t, wire.FrameUsage, r.TurnID, wire.UsageReport{TurnID: r.TurnID, Rows: used}); err != nil { return err } } // The turn waits between attempts (spec §3 step 2): the draft goes, // and the instance takes the new attempt only after it. if err = s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: wire.TurnWaiting, Reason: reason}); err != nil { return err } return s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt + 1, State: wire.TurnRunning}) }) if err == nil { r.Attempt++ } return err }