package thin import ( "context" "log/slog" "sync" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/wire" ) // TurnInput is one turn in the coordinator's lane, the Assistant's or // a job's thread. type TurnInput struct { PlacementNotes []wire.NotebookEntry Person, TurnID string // Lane is wire.LaneCoordinator, wire.LaneAssistant or a job lane // (wire.JobLane): a Coordinator turn in that job's own thread. Lane string // Kind is wire.TurnPerson, TurnMoveIn or TurnExplore; the last two // carry no text: the coordinator writes their prompt from its desk. Kind string Attempt int64 Text string // PersonText is the person's own words in this turn, one entry per // message (an answer is its value alone), from the instance: never // parsed out of Text, which can hold model-written question text. PersonText []string Tail []wire.TailMessage // Attachments are the files the person sent, on the desk by now. Attachments []wire.AttachmentRef // Earlier are the files the person attached to their Assistant // messages before this turn, which the runner may still hold, and // EarlierMore how many more the instance left out (an Assistant // person turn only). They are listed for the model, never protected // and never staged. Earlier []wire.AttachmentRef EarlierMore int // Received is when the runner committed the frame, for timing. Received time.Time // Activity reports thinking or a tool starting, by tool name only. Activity func(kind, tool string) // Done is what earlier attempts of this turn already did (tools and // their recorded results), for a turn running again after it moved // connection or after a restart. Done []string } // TurnResult is a reply, or a failure with a fixed reason code. Limit is // set when the provider refused the turn on quota (Reason "limited"): // the engine moves the turn to another connection. Seen is headroom the // provider reported on a turn that went on. type TurnResult struct { Text string // Usage are the attempt's rows as the harness reported them (per // model; empty when it reported nothing). The engine adds the // attempt, outcome and connection. Usage []wire.Usage Reason string Timing *wire.TurnTiming Limit *connect.Limit Seen *connect.Limit Plan string // SignIn: the provider refused the credential (the connection needs // signing in again); the turn moves like a quota refusal. SignIn bool // Proven: the attempt's process exit was verified by the containment // (set with Limit or SignIn); only then may another connection take // the turn. Proven bool // Switched is set by the engine when the turn moved connection. Switched *wire.Switched // rows are the usage rows the engine filled in for the report. rows []wire.Usage // glance is the turn's glance, for the phase line. glance *glanceRun } // ConnChooser is what the engine asks about connections (Conns). type ConnChooser interface { Choose(ctx context.Context, person, role, current string, avoid []string) (runner.AccountBinding, connect.Choice, error) Limit(id string, l connect.Limit) time.Time Observe(id string, l connect.Limit, plan string) LimitedFrom(id string) *wire.Switched SignInAgain(id string) // Answered: a run on the connection got the provider's answer. Answered(id string) NextCheck(person string) time.Time } // Coordinator runs turns for one person. Cancelling ctx interrupts the // turn; Turn returns only after the process for the attempt is gone. type Coordinator interface { Turn(ctx context.Context, in TurnInput, emit func(text string)) TurnResult Close() } // Warmer is a harness that can start its process and session ahead of // the first turn, sending the model nothing: the first turn then finds // it up. A warm process no turn uses closes after a while on its own. type Warmer interface { Warm(ctx context.Context) error } // Engine runs each person's turns one at a time per lane from the // durable runs table: the coordinator's, the Assistant's and each job's // run at once. type Engine struct { State *State // Conns chooses the connection for each turn; nil runs every turn on // a zero binding (tests of the engine alone). Conns ConnChooser // Open starts the person's coordinator, or their Assistant, on one // connection. Open func(person, lane string, b runner.AccountBinding) (Coordinator, error) Emit func(wire.DeltaReport) // Act sends an activity report; nil drops them. Act func(wire.ActivityReport) Notify func() // Authorize confirms with the instance, before any execution, that // this runner still holds its generation. Execution waits for it. Authorize func(context.Context) error // ResetDesk clears a person's notebook and session once their // coordinator process is closed. A pending reset is applied before // any of the person's turns runs (see settleReset). ResetDesk func(person string) error Logger *slog.Logger // Glance opens a person's glance harness on one connection (the // Assistant's instant first line, glance.go); nil sends no glances. // SendGlance queues one for the instance, and Glances says whether // the connection speaks them (protocol 23). Glance func(person string, b runner.AccountBinding) (Glancer, error) SendGlance func(wire.GlanceReport) Glances func() bool // OpenLookup opens a lookup step's harness on one connection, in a // directory made for it (lookup.go), which Lookup removes; nil fails // every lookup step. LookupTimeout bounds one (LookupTimeout). OpenLookup func(person string, b runner.AccountBinding) (Glancer, string, error) LookupTimeout time.Duration // GlanceWithin is how long after its acceptance a turn's glance may // still go (DefaultGlanceWithin); GlanceSlots bounds the glance // processes up at once (DefaultGlanceSlots). GlanceWithin time.Duration GlanceSlots int mu sync.Mutex workers map[workerKey]*worker ctx context.Context wg sync.WaitGroup } // workerKey names one worker: a person's lane. type workerKey struct{ Person, Lane string } type worker struct { wake chan struct{} // warm asks the worker to start its harness ahead of a turn. warm chan struct{} // conn wakes a turn held for a connection. conn chan struct{} coord Coordinator connID string cancel context.CancelFunc turn string attempt int64 // glance is the Assistant lane's glance harness, on glanceConn; // glanceWarming while it starts (all under Engine.mu). glance Glancer glanceConn string glanceWarming bool } // Start runs workers for the lanes with held runs, after crash recovery. func (e *Engine) Start(ctx context.Context) error { e.mu.Lock() e.ctx = ctx e.workers = map[workerKey]*worker{} e.mu.Unlock() if err := e.State.Recover(ctx); err != nil { return err } e.Notify() keys, err := e.State.workers(ctx) if err != nil { return err } resets, err := e.State.pendingResets(ctx) if err != nil { return err } for _, p := range resets { keys = append(keys, workerKey{p, wire.LaneCoordinator}) } for _, k := range keys { e.Wake(k.Person, k.Lane) } return nil } // Wait stops after ctx ends and every worker has closed its coordinator. func (e *Engine) Wait() { e.wg.Wait() } // worker returns the lane's worker, starting it; e.mu is held. func (e *Engine) worker(k workerKey) *worker { w := e.workers[k] if w == nil { w = &worker{wake: make(chan struct{}, 1), warm: make(chan struct{}, 1), conn: make(chan struct{}, 1)} e.workers[k] = w e.wg.Add(1) go e.loop(k, w) } return w } // Wake makes sure the worker of the person's lane looks for runs. func (e *Engine) Wake(person, lane string) { if e == nil { return } e.mu.Lock() defer e.mu.Unlock() w := e.worker(workerKey{person, lane}) select { case w.wake <- struct{}{}: default: } } // ConnectionsChanged makes every held turn look for a connection again. func (e *Engine) ConnectionsChanged() { e.mu.Lock() defer e.mu.Unlock() for _, w := range e.workers { select { case w.conn <- struct{}{}: default: } } } // Cancel interrupts the attempt if it is the one running now, in any of // the person's lanes (a job's thread included). func (e *Engine) Cancel(person, turn string, attempt int64) { if e == nil { return } e.mu.Lock() defer e.mu.Unlock() for k, w := range e.workers { if k.Person == person && w.turn == turn && w.attempt >= attempt && w.cancel != nil { w.cancel() } } } func (e *Engine) log(msg string, err error) { if e.Logger != nil && err != nil { e.Logger.Warn(msg, "err", err) } } // phases logs an Assistant turn's phases at debug level, each as the // milliseconds since the runner accepted the turn: its process started // (the prompt written; a cold turn includes the process's start), its // first tool call, its first token, and its reply queued for the // instance. Only the turn id, never text, tokens or the person. func (e *Engine) phases(r run, res TurnResult) { if e.Logger == nil || r.Lane != wire.LaneAssistant || r.Received.IsZero() { return } outcome := res.Reason if outcome == "" { outcome = wire.TurnReplied } attrs := []any{"turn", r.TurnID, "attempt", r.Attempt, "outcome", outcome} if t := res.Timing; t != nil { at := func(ms int64) int64 { if ms == 0 { return 0 } return t.StartMs + ms } attrs = append(attrs, "cold", t.Cold, "started_ms", t.StartMs, "first_tool_ms", at(t.FirstToolMs), "first_token_ms", at(t.FirstTextMs)) } if res.glance != nil { outcome, ms := res.glance.state() attrs = append(attrs, "glance", outcome) if outcome == "sent" { attrs = append(attrs, "glance_ms", ms) } } attrs = append(attrs, "reply_ms", time.Since(r.Received).Milliseconds()) e.Logger.Debug("assistant turn", attrs...) } func (e *Engine) loop(k workerKey, w *worker) { defer e.wg.Done() defer func() { if w.coord != nil { w.coord.Close() } e.mu.Lock() g := w.glance w.glance = nil e.mu.Unlock() if g != nil { g.Close() } }() for { warm := false select { case <-e.ctx.Done(): return case <-w.wake: case <-w.warm: warm = true } ran := false for e.ctx.Err() == nil { // A reset is the person's own conversation's: the // Assistant's lane and job threads go on. if k.Lane == wire.LaneCoordinator && !e.settleReset(k.Person, w) { break } r, ok, err := e.State.next(e.ctx, k.Person, k.Lane) if err != nil { e.log("runner state", err) break } if !ok { break } e.runOne(k.Person, w, r) ran = true } // A turn that ran started the harness anyway. if warm && !ran && e.ctx.Err() == nil { e.warmOne(k, w) } } } // settleReset applies the person's pending reset, if any, before a turn // may run: the coordinator process closes, the desk and session go, and // only then is the reset done. If clearing fails no turn runs; it is // tried again shortly. func (e *Engine) settleReset(person string, w *worker) bool { pending, err := e.State.resetPending(e.ctx, person) if err != nil { e.log("runner reset", err) return false } if !pending { return true } if w.coord != nil { w.coord.Close() w.coord = nil } if e.ResetDesk != nil { err = e.ResetDesk(person) } if err == nil { err = e.State.ResetDone(e.ctx, person) } if err != nil { e.log("runner reset", err) time.AfterFunc(time.Second, func() { e.Wake(person, wire.LaneCoordinator) }) return false } return true } func (e *Engine) runOne(person string, w *worker, r run) { report := func(res TurnResult) { var err error if res.Reason == "" { err = e.State.Report(e.ctx, r, &wire.Reply{TurnID: r.TurnID, Attempt: r.Attempt, Text: res.Text, Usage: res.rows, Timing: res.Timing, Switched: res.Switched}, nil, nil) } else { state := wire.TurnFailed if res.Reason == "cancelled" { state = wire.TurnCancelled } rows := res.rows for i := range rows { rows[i].Outcome = state } err = e.State.Report(e.ctx, r, nil, &wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: state, Reason: res.Reason}, rows) } e.log("runner report", err) e.Notify() e.phases(r, res) } if r.Cancel { report(TurnResult{Reason: "cancelled"}) return } ctx, cancel := context.WithCancel(e.ctx) e.mu.Lock() w.cancel, w.turn, w.attempt = cancel, r.TurnID, r.Attempt e.mu.Unlock() // A cancel that arrived between next() and now is still honoured. if fresh, ok, _ := e.State.next(e.ctx, person, r.Lane); ok && fresh.TurnID == r.TurnID && fresh.Cancel { cancel() } // The generation is an execution lease: no provider call without a // fresh confirmation from the instance. for e.Authorize != nil && ctx.Err() == nil { err := e.Authorize(ctx) if err == nil { break } select { case <-ctx.Done(): case <-time.After(time.Second): } } if ctx.Err() != nil { e.mu.Lock() w.cancel, w.turn, w.attempt = nil, "", 0 e.mu.Unlock() cancel() if e.ctx.Err() == nil { report(TurnResult{Reason: "cancelled"}) } return } act := func(kind, tool string) { if e.Act != nil { e.Act(wire.ActivityReport{TurnID: r.TurnID, Attempt: r.Attempt, Kind: kind, Tool: tool}) } } res := e.converse(ctx, person, w, &r, act) e.mu.Lock() w.cancel, w.turn, w.attempt = nil, "", 0 e.mu.Unlock() cancelled := ctx.Err() != nil cancel() if e.ctx.Err() != nil { // Shutting down: the run stays held and is recovered on restart. return } if cancelled && res.Reason == "" { res = TurnResult{Reason: "cancelled"} } if cancelled { res.Reason = "cancelled" } report(res) }