| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "sync" |
| 7 | "time" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/runner" |
| 10 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | ) |
| 13 | |
| 14 | // TurnInput is one turn in the coordinator's lane, the Assistant's or |
| 15 | // a job's thread. |
| 16 | type TurnInput struct { |
| 17 | PlacementNotes []wire.NotebookEntry |
| 18 | Person, TurnID string |
| 19 | // Lane is wire.LaneCoordinator, wire.LaneAssistant or a job lane |
| 20 | // (wire.JobLane): a Coordinator turn in that job's own thread. |
| 21 | Lane string |
| 22 | // Kind is wire.TurnPerson, TurnMoveIn or TurnExplore; the last two |
| 23 | // carry no text: the coordinator writes their prompt from its desk. |
| 24 | Kind string |
| 25 | Attempt int64 |
| 26 | Text string |
| 27 | // PersonText is the person's own words in this turn, one entry per |
| 28 | // message (an answer is its value alone), from the instance: never |
| 29 | // parsed out of Text, which can hold model-written question text. |
| 30 | PersonText []string |
| 31 | Tail []wire.TailMessage |
| 32 | // Attachments are the files the person sent, on the desk by now. |
| 33 | Attachments []wire.AttachmentRef |
| 34 | // Earlier are the files the person attached to their Assistant |
| 35 | // messages before this turn, which the runner may still hold, and |
| 36 | // EarlierMore how many more the instance left out (an Assistant |
| 37 | // person turn only). They are listed for the model, never protected |
| 38 | // and never staged. |
| 39 | Earlier []wire.AttachmentRef |
| 40 | EarlierMore int |
| 41 | // Received is when the runner committed the frame, for timing. |
| 42 | Received time.Time |
| 43 | // Activity reports thinking or a tool starting, by tool name only. |
| 44 | Activity func(kind, tool string) |
| 45 | // Done is what earlier attempts of this turn already did (tools and |
| 46 | // their recorded results), for a turn running again after it moved |
| 47 | // connection or after a restart. |
| 48 | Done []string |
| 49 | } |
| 50 | |
| 51 | // TurnResult is a reply, or a failure with a fixed reason code. Limit is |
| 52 | // set when the provider refused the turn on quota (Reason "limited"): |
| 53 | // the engine moves the turn to another connection. Seen is headroom the |
| 54 | // provider reported on a turn that went on. |
| 55 | type TurnResult struct { |
| 56 | Text string |
| 57 | // Usage are the attempt's rows as the harness reported them (per |
| 58 | // model; empty when it reported nothing). The engine adds the |
| 59 | // attempt, outcome and connection. |
| 60 | Usage []wire.Usage |
| 61 | Reason string |
| 62 | Timing *wire.TurnTiming |
| 63 | Limit *connect.Limit |
| 64 | Seen *connect.Limit |
| 65 | Plan string |
| 66 | // SignIn: the provider refused the credential (the connection needs |
| 67 | // signing in again); the turn moves like a quota refusal. |
| 68 | SignIn bool |
| 69 | // Proven: the attempt's process exit was verified by the containment |
| 70 | // (set with Limit or SignIn); only then may another connection take |
| 71 | // the turn. |
| 72 | Proven bool |
| 73 | // Switched is set by the engine when the turn moved connection. |
| 74 | Switched *wire.Switched |
| 75 | // rows are the usage rows the engine filled in for the report. |
| 76 | rows []wire.Usage |
| 77 | // glance is the turn's glance, for the phase line. |
| 78 | glance *glanceRun |
| 79 | } |
| 80 | |
| 81 | // ConnChooser is what the engine asks about connections (Conns). |
| 82 | type ConnChooser interface { |
| 83 | Choose(ctx context.Context, person, role, current string, avoid []string) (runner.AccountBinding, connect.Choice, error) |
| 84 | Limit(id string, l connect.Limit) time.Time |
| 85 | Observe(id string, l connect.Limit, plan string) |
| 86 | LimitedFrom(id string) *wire.Switched |
| 87 | SignInAgain(id string) |
| 88 | // Answered: a run on the connection got the provider's answer. |
| 89 | Answered(id string) |
| 90 | NextCheck(person string) time.Time |
| 91 | } |
| 92 | |
| 93 | // Coordinator runs turns for one person. Cancelling ctx interrupts the |
| 94 | // turn; Turn returns only after the process for the attempt is gone. |
| 95 | type Coordinator interface { |
| 96 | Turn(ctx context.Context, in TurnInput, emit func(text string)) TurnResult |
| 97 | Close() |
| 98 | } |
| 99 | |
| 100 | // Warmer is a harness that can start its process and session ahead of |
| 101 | // the first turn, sending the model nothing: the first turn then finds |
| 102 | // it up. A warm process no turn uses closes after a while on its own. |
| 103 | type Warmer interface { |
| 104 | Warm(ctx context.Context) error |
| 105 | } |
| 106 | |
| 107 | // Engine runs each person's turns one at a time per lane from the |
| 108 | // durable runs table: the coordinator's, the Assistant's and each job's |
| 109 | // run at once. |
| 110 | type Engine struct { |
| 111 | State *State |
| 112 | // Conns chooses the connection for each turn; nil runs every turn on |
| 113 | // a zero binding (tests of the engine alone). |
| 114 | Conns ConnChooser |
| 115 | // Open starts the person's coordinator, or their Assistant, on one |
| 116 | // connection. |
| 117 | Open func(person, lane string, b runner.AccountBinding) (Coordinator, error) |
| 118 | Emit func(wire.DeltaReport) |
| 119 | // Act sends an activity report; nil drops them. |
| 120 | Act func(wire.ActivityReport) |
| 121 | Notify func() |
| 122 | // Authorize confirms with the instance, before any execution, that |
| 123 | // this runner still holds its generation. Execution waits for it. |
| 124 | Authorize func(context.Context) error |
| 125 | // ResetDesk clears a person's notebook and session once their |
| 126 | // coordinator process is closed. A pending reset is applied before |
| 127 | // any of the person's turns runs (see settleReset). |
| 128 | ResetDesk func(person string) error |
| 129 | Logger *slog.Logger |
| 130 | // Glance opens a person's glance harness on one connection (the |
| 131 | // Assistant's instant first line, glance.go); nil sends no glances. |
| 132 | // SendGlance queues one for the instance, and Glances says whether |
| 133 | // the connection speaks them (protocol 23). |
| 134 | Glance func(person string, b runner.AccountBinding) (Glancer, error) |
| 135 | SendGlance func(wire.GlanceReport) |
| 136 | Glances func() bool |
| 137 | // OpenLookup opens a lookup step's harness on one connection, in a |
| 138 | // directory made for it (lookup.go), which Lookup removes; nil fails |
| 139 | // every lookup step. LookupTimeout bounds one (LookupTimeout). |
| 140 | OpenLookup func(person string, b runner.AccountBinding) (Glancer, string, error) |
| 141 | LookupTimeout time.Duration |
| 142 | // GlanceWithin is how long after its acceptance a turn's glance may |
| 143 | // still go (DefaultGlanceWithin); GlanceSlots bounds the glance |
| 144 | // processes up at once (DefaultGlanceSlots). |
| 145 | GlanceWithin time.Duration |
| 146 | GlanceSlots int |
| 147 | |
| 148 | mu sync.Mutex |
| 149 | workers map[workerKey]*worker |
| 150 | ctx context.Context |
| 151 | wg sync.WaitGroup |
| 152 | } |
| 153 | |
| 154 | // workerKey names one worker: a person's lane. |
| 155 | type workerKey struct{ Person, Lane string } |
| 156 | |
| 157 | type worker struct { |
| 158 | wake chan struct{} |
| 159 | // warm asks the worker to start its harness ahead of a turn. |
| 160 | warm chan struct{} |
| 161 | // conn wakes a turn held for a connection. |
| 162 | conn chan struct{} |
| 163 | coord Coordinator |
| 164 | connID string |
| 165 | cancel context.CancelFunc |
| 166 | turn string |
| 167 | attempt int64 |
| 168 | // glance is the Assistant lane's glance harness, on glanceConn; |
| 169 | // glanceWarming while it starts (all under Engine.mu). |
| 170 | glance Glancer |
| 171 | glanceConn string |
| 172 | glanceWarming bool |
| 173 | } |
| 174 | |
| 175 | // Start runs workers for the lanes with held runs, after crash recovery. |
| 176 | func (e *Engine) Start(ctx context.Context) error { |
| 177 | e.mu.Lock() |
| 178 | e.ctx = ctx |
| 179 | e.workers = map[workerKey]*worker{} |
| 180 | e.mu.Unlock() |
| 181 | if err := e.State.Recover(ctx); err != nil { |
| 182 | return err |
| 183 | } |
| 184 | e.Notify() |
| 185 | keys, err := e.State.workers(ctx) |
| 186 | if err != nil { |
| 187 | return err |
| 188 | } |
| 189 | resets, err := e.State.pendingResets(ctx) |
| 190 | if err != nil { |
| 191 | return err |
| 192 | } |
| 193 | for _, p := range resets { |
| 194 | keys = append(keys, workerKey{p, wire.LaneCoordinator}) |
| 195 | } |
| 196 | for _, k := range keys { |
| 197 | e.Wake(k.Person, k.Lane) |
| 198 | } |
| 199 | return nil |
| 200 | } |
| 201 | |
| 202 | // Wait stops after ctx ends and every worker has closed its coordinator. |
| 203 | func (e *Engine) Wait() { e.wg.Wait() } |
| 204 | |
| 205 | // worker returns the lane's worker, starting it; e.mu is held. |
| 206 | func (e *Engine) worker(k workerKey) *worker { |
| 207 | w := e.workers[k] |
| 208 | if w == nil { |
| 209 | w = &worker{wake: make(chan struct{}, 1), warm: make(chan struct{}, 1), conn: make(chan struct{}, 1)} |
| 210 | e.workers[k] = w |
| 211 | e.wg.Add(1) |
| 212 | go e.loop(k, w) |
| 213 | } |
| 214 | return w |
| 215 | } |
| 216 | |
| 217 | // Wake makes sure the worker of the person's lane looks for runs. |
| 218 | func (e *Engine) Wake(person, lane string) { |
| 219 | if e == nil { |
| 220 | return |
| 221 | } |
| 222 | e.mu.Lock() |
| 223 | defer e.mu.Unlock() |
| 224 | w := e.worker(workerKey{person, lane}) |
| 225 | select { |
| 226 | case w.wake <- struct{}{}: |
| 227 | default: |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // ConnectionsChanged makes every held turn look for a connection again. |
| 232 | func (e *Engine) ConnectionsChanged() { |
| 233 | e.mu.Lock() |
| 234 | defer e.mu.Unlock() |
| 235 | for _, w := range e.workers { |
| 236 | select { |
| 237 | case w.conn <- struct{}{}: |
| 238 | default: |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // Cancel interrupts the attempt if it is the one running now, in any of |
| 244 | // the person's lanes (a job's thread included). |
| 245 | func (e *Engine) Cancel(person, turn string, attempt int64) { |
| 246 | if e == nil { |
| 247 | return |
| 248 | } |
| 249 | e.mu.Lock() |
| 250 | defer e.mu.Unlock() |
| 251 | for k, w := range e.workers { |
| 252 | if k.Person == person && w.turn == turn && w.attempt >= attempt && w.cancel != nil { |
| 253 | w.cancel() |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | func (e *Engine) log(msg string, err error) { |
| 259 | if e.Logger != nil && err != nil { |
| 260 | e.Logger.Warn(msg, "err", err) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // phases logs an Assistant turn's phases at debug level, each as the |
| 265 | // milliseconds since the runner accepted the turn: its process started |
| 266 | // (the prompt written; a cold turn includes the process's start), its |
| 267 | // first tool call, its first token, and its reply queued for the |
| 268 | // instance. Only the turn id, never text, tokens or the person. |
| 269 | func (e *Engine) phases(r run, res TurnResult) { |
| 270 | if e.Logger == nil || r.Lane != wire.LaneAssistant || r.Received.IsZero() { |
| 271 | return |
| 272 | } |
| 273 | outcome := res.Reason |
| 274 | if outcome == "" { |
| 275 | outcome = wire.TurnReplied |
| 276 | } |
| 277 | attrs := []any{"turn", r.TurnID, "attempt", r.Attempt, "outcome", outcome} |
| 278 | if t := res.Timing; t != nil { |
| 279 | at := func(ms int64) int64 { |
| 280 | if ms == 0 { |
| 281 | return 0 |
| 282 | } |
| 283 | return t.StartMs + ms |
| 284 | } |
| 285 | attrs = append(attrs, "cold", t.Cold, "started_ms", t.StartMs, "first_tool_ms", at(t.FirstToolMs), "first_token_ms", at(t.FirstTextMs)) |
| 286 | } |
| 287 | if res.glance != nil { |
| 288 | outcome, ms := res.glance.state() |
| 289 | attrs = append(attrs, "glance", outcome) |
| 290 | if outcome == "sent" { |
| 291 | attrs = append(attrs, "glance_ms", ms) |
| 292 | } |
| 293 | } |
| 294 | attrs = append(attrs, "reply_ms", time.Since(r.Received).Milliseconds()) |
| 295 | e.Logger.Debug("assistant turn", attrs...) |
| 296 | } |
| 297 | |
| 298 | func (e *Engine) loop(k workerKey, w *worker) { |
| 299 | defer e.wg.Done() |
| 300 | defer func() { |
| 301 | if w.coord != nil { |
| 302 | w.coord.Close() |
| 303 | } |
| 304 | e.mu.Lock() |
| 305 | g := w.glance |
| 306 | w.glance = nil |
| 307 | e.mu.Unlock() |
| 308 | if g != nil { |
| 309 | g.Close() |
| 310 | } |
| 311 | }() |
| 312 | for { |
| 313 | warm := false |
| 314 | select { |
| 315 | case <-e.ctx.Done(): |
| 316 | return |
| 317 | case <-w.wake: |
| 318 | case <-w.warm: |
| 319 | warm = true |
| 320 | } |
| 321 | ran := false |
| 322 | for e.ctx.Err() == nil { |
| 323 | // A reset is the person's own conversation's: the |
| 324 | // Assistant's lane and job threads go on. |
| 325 | if k.Lane == wire.LaneCoordinator && !e.settleReset(k.Person, w) { |
| 326 | break |
| 327 | } |
| 328 | r, ok, err := e.State.next(e.ctx, k.Person, k.Lane) |
| 329 | if err != nil { |
| 330 | e.log("runner state", err) |
| 331 | break |
| 332 | } |
| 333 | if !ok { |
| 334 | break |
| 335 | } |
| 336 | e.runOne(k.Person, w, r) |
| 337 | ran = true |
| 338 | } |
| 339 | // A turn that ran started the harness anyway. |
| 340 | if warm && !ran && e.ctx.Err() == nil { |
| 341 | e.warmOne(k, w) |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | // settleReset applies the person's pending reset, if any, before a turn |
| 347 | // may run: the coordinator process closes, the desk and session go, and |
| 348 | // only then is the reset done. If clearing fails no turn runs; it is |
| 349 | // tried again shortly. |
| 350 | func (e *Engine) settleReset(person string, w *worker) bool { |
| 351 | pending, err := e.State.resetPending(e.ctx, person) |
| 352 | if err != nil { |
| 353 | e.log("runner reset", err) |
| 354 | return false |
| 355 | } |
| 356 | if !pending { |
| 357 | return true |
| 358 | } |
| 359 | if w.coord != nil { |
| 360 | w.coord.Close() |
| 361 | w.coord = nil |
| 362 | } |
| 363 | if e.ResetDesk != nil { |
| 364 | err = e.ResetDesk(person) |
| 365 | } |
| 366 | if err == nil { |
| 367 | err = e.State.ResetDone(e.ctx, person) |
| 368 | } |
| 369 | if err != nil { |
| 370 | e.log("runner reset", err) |
| 371 | time.AfterFunc(time.Second, func() { e.Wake(person, wire.LaneCoordinator) }) |
| 372 | return false |
| 373 | } |
| 374 | return true |
| 375 | } |
| 376 | |
| 377 | func (e *Engine) runOne(person string, w *worker, r run) { |
| 378 | report := func(res TurnResult) { |
| 379 | var err error |
| 380 | if res.Reason == "" { |
| 381 | 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) |
| 382 | } else { |
| 383 | state := wire.TurnFailed |
| 384 | if res.Reason == "cancelled" { |
| 385 | state = wire.TurnCancelled |
| 386 | } |
| 387 | rows := res.rows |
| 388 | for i := range rows { |
| 389 | rows[i].Outcome = state |
| 390 | } |
| 391 | err = e.State.Report(e.ctx, r, nil, &wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: state, Reason: res.Reason}, rows) |
| 392 | } |
| 393 | e.log("runner report", err) |
| 394 | e.Notify() |
| 395 | e.phases(r, res) |
| 396 | } |
| 397 | if r.Cancel { |
| 398 | report(TurnResult{Reason: "cancelled"}) |
| 399 | return |
| 400 | } |
| 401 | ctx, cancel := context.WithCancel(e.ctx) |
| 402 | e.mu.Lock() |
| 403 | w.cancel, w.turn, w.attempt = cancel, r.TurnID, r.Attempt |
| 404 | e.mu.Unlock() |
| 405 | // A cancel that arrived between next() and now is still honoured. |
| 406 | if fresh, ok, _ := e.State.next(e.ctx, person, r.Lane); ok && fresh.TurnID == r.TurnID && fresh.Cancel { |
| 407 | cancel() |
| 408 | } |
| 409 | // The generation is an execution lease: no provider call without a |
| 410 | // fresh confirmation from the instance. |
| 411 | for e.Authorize != nil && ctx.Err() == nil { |
| 412 | err := e.Authorize(ctx) |
| 413 | if err == nil { |
| 414 | break |
| 415 | } |
| 416 | select { |
| 417 | case <-ctx.Done(): |
| 418 | case <-time.After(time.Second): |
| 419 | } |
| 420 | } |
| 421 | if ctx.Err() != nil { |
| 422 | e.mu.Lock() |
| 423 | w.cancel, w.turn, w.attempt = nil, "", 0 |
| 424 | e.mu.Unlock() |
| 425 | cancel() |
| 426 | if e.ctx.Err() == nil { |
| 427 | report(TurnResult{Reason: "cancelled"}) |
| 428 | } |
| 429 | return |
| 430 | } |
| 431 | act := func(kind, tool string) { |
| 432 | if e.Act != nil { |
| 433 | e.Act(wire.ActivityReport{TurnID: r.TurnID, Attempt: r.Attempt, Kind: kind, Tool: tool}) |
| 434 | } |
| 435 | } |
| 436 | res := e.converse(ctx, person, w, &r, act) |
| 437 | e.mu.Lock() |
| 438 | w.cancel, w.turn, w.attempt = nil, "", 0 |
| 439 | e.mu.Unlock() |
| 440 | cancelled := ctx.Err() != nil |
| 441 | cancel() |
| 442 | if e.ctx.Err() != nil { |
| 443 | // Shutting down: the run stays held and is recovered on restart. |
| 444 | return |
| 445 | } |
| 446 | if cancelled && res.Reason == "" { |
| 447 | res = TurnResult{Reason: "cancelled"} |
| 448 | } |
| 449 | if cancelled { |
| 450 | res.Reason = "cancelled" |
| 451 | } |
| 452 | report(res) |
| 453 | } |
| 454 | |