package runner import ( "amadan.net/oficina/equipo/internal/chatstream" "context" "database/sql" "encoding/json" "errors" "path/filepath" "sync/atomic" "time" "amadan.net/oficina/equipo/internal/coordinator" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) type CoordinatorAPI interface { CoordinatorCall(context.Context, string, runnerproto.CoordinatorRequest, any) error } type CoordinatorService struct { release func() error retry map[string]coordinatorRetry now func() time.Time RecoverFiles func(context.Context, runnerproto.CoordinatorClaim) error Journal *Journal API CoordinatorAPI Launchers map[string]provider.Launcher OpenLaunch func(context.Context, runnerproto.CoordinatorClaim, *ToolProxy) (provider.Launch, func() error, error) Contain func(context.Context, runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) NamespaceContext func(context.Context, runnerproto.CoordinatorClaim) context.Context } type coordinatorState struct { Claim runnerproto.CoordinatorClaim Session provider.Session Finished bool Refused bool RefusalOperation string RefusalStatus int RefusalCode string DeliveryRefusal *RefusalError Containment *runnerproto.ContainmentProof } func (s *CoordinatorService) call(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { q.Version = 2 q.Capabilities = []string{runnerproto.CoordinatorCapability} err := s.API.CoordinatorCall(ctx, op, q, out) if err == nil || ctx.Err() != nil { return err } var refusal *RefusalError if errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { return refusal } // Remote contract/authentication failures cannot kill unrelated runner work. return ErrTransient } func (s *CoordinatorService) Poll(ctx context.Context) error { if s.Journal == nil || s.API == nil || s.OpenLaunch == nil || s.Contain == nil { return provider.ErrContract } if err := s.Journal.AdmissionAllowed(ctx); err != nil { return err } var turns []runnerproto.CoordinatorTurn if err := s.call(ctx, "poll", runnerproto.CoordinatorRequest{}, &turns); err != nil { return err } for _, turn := range turns { if !s.retryDue(turn.ID) { continue } var saved int if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind IN ('coordinator','coordinator-claim') AND state_key=?", turn.ID).Scan(&saved); err != nil { return err } if saved != 0 { continue } q := runnerproto.CoordinatorRequest{TurnID: turn.ID, Revision: turn.Revision} if err := s.Journal.saveState(ctx, "coordinator-claim", turn.ID, q); err != nil { return err } var c runnerproto.CoordinatorClaim if err := s.call(ctx, "claim", q, &c); err != nil { r := coordinatorState{Claim: runnerproto.CoordinatorClaim{Turn: turn}} if err = s.refusedCall(ctx, &r, "claim", err); err != nil { return err } continue } if err := s.RunTurn(ctx, c); err != nil { if errors.Is(err, ErrTransient) { s.deferRetry(c.Turn.ID) continue } return err } } return nil } func (s *CoordinatorService) RunTurn(ctx context.Context, c runnerproto.CoordinatorClaim) (result error) { state := coordinatorState{Claim: c} // No saved turn, even one interrupted before stdin, can enter RunTurn again. var count int if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind='coordinator' AND state_key=?", c.Turn.ID).Scan(&count); err != nil { return err } if count != 0 { return provider.ErrUncertain } if _, err := runnerproto.CoordinatorPrompt(c.Context); err != nil { return err } if err := s.Journal.saveState(ctx, "coordinator", c.Turn.ID, state); err != nil { return err } var proxy *ToolProxy var proxyRef atomic.Pointer[ToolProxy] var release func() error runCtx, cancel := context.WithCancel(ctx) defer cancel() if s.NamespaceContext != nil { runCtx = s.NamespaceContext(runCtx, c) } // Cleanup proves all namespaces dead before releasing the account lease. defer func() { cleanup, stop := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) defer stop() if proxy != nil { result = errors.Join(result, proxy.Close()) } proof, err := s.Contain(cleanup, c) if err != nil { result = errors.Join(result, err) return } if state.Session.AttemptKey != "" { if err = s.Journal.interruptDirect(cleanup, state.Session.AttemptKey, true); err != nil { result = errors.Join(result, err) return } } if release != nil { if err = release(); err != nil { result = errors.Join(result, err) return } s.release = nil } var deliveryErr error if result == nil { deliveryErr = s.finishDelivery(cleanup, state) } err = s.finishContained(cleanup, &state, proof, deliveryErr) result = errors.Join(result, err) }() launcher := s.Launchers[c.Brief.Selection.Provider] if launcher == nil { return provider.ErrProvider } current := func(ctx context.Context) error { var deadline time.Time if err := s.call(ctx, "renew", runnerproto.NewCoordinatorRequest(c), &deadline); err != nil { return err } if !time.Now().Before(deadline) || !time.Now().Before(c.AttemptDeadline) { return provider.ErrUncertain } if currentProxy := proxyRef.Load(); currentProxy != nil { currentProxy.coordinator.mu.Lock() currentProxy.coordinator.deadline = deadline currentProxy.coordinator.mu.Unlock() } return nil } if err := current(runCtx); err != nil { return err } var err error proxy, err = OpenCoordinatorToolProxy(runCtx, CoordinatorToolBinding{Claim: c, Journal: s.Journal, Current: current, Call: func(ctx context.Context, call runnerproto.CoordinatorToolCall) (runnerproto.CoordinatorToolResult, error) { var out runnerproto.CoordinatorToolResult q := runnerproto.NewCoordinatorRequest(c) q.ToolCall = &call err := s.call(ctx, "tool", q, &out) return out, err }}) if err != nil { return err } proxyRef.Store(proxy) // The short-lived admission is consumed before preflight's first provider // process. A saved consumption can only be reconciled after a restart. dir := filepath.Join(filepath.Dir(s.Journal.path), "coordinator-admissions") request := runnerproto.RunnerRequest{Version: 2, AssignmentID: c.Turn.ID, RequestID: c.Turn.ID, Scope: c.Scope, Handle: c.Handle, ActionID: c.Admission.Dispatch.Action} if err = runnerproto.JournalAdmission(dir, request); err != nil { return err } if err = runnerproto.ConsumeTicket(dir, c.Turn.ID, c.Admission, time.Now().UTC(), c.Admission.Incarnation); err != nil { return err } wrapped := &coordinatorLauncher{Launcher: launcher, open: func(session provider.Session) error { state.Session = session return s.Journal.saveState(runCtx, "coordinator", c.Turn.ID, state) }, start: func(ctx context.Context, session provider.Session, turn provider.Turn) error { if err := current(ctx); err != nil { return err } return proxy.BindTurn(session, turn.ID) }} stream := chatstream.Forwarder{Send: func(ctx context.Context, text string, sequence int64) error { e := chatstream.TextEvent(s.template(state), text, sequence) if err := s.Journal.Append(ctx, e); err != nil { return err } return s.flush(ctx, state) }} runtime, err := coordinator.New(coordinator.Config{Launcher: wrapped, Tools: coordinator.ToolFunc(proxy.CallCoordinatorTool), OpenLaunch: func(ctx context.Context, c runnerproto.CoordinatorClaim) (provider.Launch, error) { var l provider.Launch var err error l, release, err = s.OpenLaunch(ctx, c, proxy) s.release = release return l, err }, Record: func(ctx context.Context, e provider.Event) error { if e.Kind == "session.bound" { return s.emit(ctx, state, "session.bound", json.RawMessage(`{}`)) } pump := EventPump{Journal: s.Journal, Contain: func(ctx context.Context) error { return launcher.Interrupt(ctx, state.Session) }} if err := pump.AppendDirect(ctx, state.Session, e, s.template(state)); err != nil { return err } if e.Kind == "message.delta" { return stream.Add(ctx, e.Payload) } if e.Kind == "request" { return proxy.ApproveCoordinator(ctx, launcher, e) } return nil }}) if err != nil { return err } // Revocation and lease renewal continue even while a provider emits no frames. done := make(chan struct{}) go func() { defer close(done) tick := time.NewTicker(leaseRenewInterval) defer tick.Stop() for { select { case <-runCtx.Done(): return case <-tick.C: if current(runCtx) != nil { cancel() return } } } }() defer func() { cancel(); <-done }() result = runtime.RunTurn(runCtx, c) if result == nil { result = s.Journal.requireDirectCompletion(ctx, state.Session, c.Turn.ID) } return result } type coordinatorLauncher struct { provider.Launcher open func(provider.Session) error start func(context.Context, provider.Session, provider.Turn) error } func (l *coordinatorLauncher) Open(ctx context.Context, v provider.Launch) (provider.Session, error) { s, err := l.Launcher.Open(ctx, v) if err == nil { err = l.open(s) } if err != nil && s.ID != "" { _ = l.Launcher.Close(context.WithoutCancel(ctx), s) } return s, err } func (l *coordinatorLauncher) StartTurn(ctx context.Context, s provider.Session, t provider.Turn) error { if _, err := runnerproto.CoordinatorTurnIntentPayload(s.Provider, s.Model, t.Prompt); err != nil { return err } if err := l.start(ctx, s, t); err != nil { return err } return l.Launcher.StartTurn(ctx, s, t) } func (s *CoordinatorService) template(r coordinatorState) Event { c := r.Claim return Event{Version: 2, TaskID: c.Turn.ID, AssignmentID: c.Turn.ID, Scope: c.Scope, Handle: c.Handle, ServerID: "direct", AgentID: r.Session.AttemptKey, SessionID: r.Session.ID, TurnID: c.Turn.ID, ActionID: c.Admission.Dispatch.Action, SourceTime: time.Now().UTC(), Isolation: c.Brief.Selection.Isolation} } func (s *CoordinatorService) emit(ctx context.Context, r coordinatorState, kind string, payload json.RawMessage) error { e := s.template(r) e.Kind = kind e.ID = runnerproto.EventHash([]string{r.Claim.Turn.ID, kind, r.Session.ID}) e.Payload = payload var old []byte err := s.Journal.db.QueryRowContext(ctx, "SELECT body FROM journal_events WHERE id=?", e.ID).Scan(&old) if err == nil { if json.Unmarshal(old, &e) != nil { return ErrJournal } } else if !errors.Is(err, sql.ErrNoRows) { return err } if err = s.Journal.Append(ctx, e); err != nil { return err } return s.flush(ctx, r) } func (s *CoordinatorService) flush(ctx context.Context, r coordinatorState) error { rows, err := s.Journal.db.QueryContext(ctx, "SELECT body FROM journal_events WHERE acked=0 AND json_extract(body,'$.assignment_id')=? ORDER BY rowid", r.Claim.Turn.ID) if err != nil { return err } var events []Event for rows.Next() { var raw []byte var e Event if err = rows.Scan(&raw); err != nil { break } if err = json.Unmarshal(raw, &e); err != nil { break } events = append(events, e) } rowErr := rows.Err() rows.Close() if err != nil { return err } if rowErr != nil { return rowErr } for _, e := range events { switch e.Kind { case "coordinator.text", "namespace.owner", "namespace.launch", "session.bound", "turn.completed", "turn.failed", "turn.uncertain", "coordinator.delivery": q := runnerproto.NewCoordinatorRequest(r.Claim) q.Event = &e if err = s.call(ctx, "event", q, nil); err != nil { return err } } if err = s.Journal.Ack(ctx, e.ID); err != nil { return err } } return nil } func (s *CoordinatorService) finishDelivery(ctx context.Context, r coordinatorState) error { if err := s.flush(ctx, r); err != nil { return err } var delivered int if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_events WHERE acked=1 AND json_extract(body,'$.assignment_id')=? AND json_extract(body,'$.kind')='coordinator.delivery'", r.Claim.Turn.ID).Scan(&delivered); err != nil { return err } if delivered != 0 { return nil } var raw, body []byte err := s.Journal.db.QueryRowContext(ctx, `SELECT t.body,t.result FROM coordinator_tools t JOIN coordinator_tool_claims c ON c.claim_ref=json_extract(t.body,'$.claim_ref') WHERE c.turn_key=? AND t.acked=1 AND json_extract(t.result,'$.value.tool') IN ('propose_project','post_message','propose_plan','ask_person','route_to_task','suggest_preference','suggest_specialist','suggest_playbook') ORDER BY t.ordinal LIMIT 1`, coordinatorTurnKey(r.Claim, r.Session)).Scan(&body, &raw) if err != nil { if errors.Is(err, sql.ErrNoRows) { return provider.ErrUncertain } return err } var record coordinatorToolRecord var out runnerproto.CoordinatorToolResult if json.Unmarshal(body, &record) != nil || json.Unmarshal(raw, &out) != nil { return ErrJournal } return s.emit(ctx, r, "coordinator.delivery", marshal(map[string]string{"request_id": record.Call.RequestID, "resource_id": out.ResourceID})) }