// Package connect holds what the runner decides about connections without // touching any of them: the one function that chooses a connection for a // run (spec §3), the provider limit signals it reads (§2.7), and the // sign-in flows that add a connection from the app (§§2.2, 2.3). package connect import ( "slices" "time" ) // Roles a run is for. const ( RoleCoordinator = "coordinator" RoleEngineering = "engineering" RoleReview = "review" // RoleResearch reads pages fetched for it (Research spec §4): no // native tools on either harness. RoleResearch = "research" ) // Reasons a choice is recorded with (spec §4, slice 1 subset). const ( ReasonOnlyOption = "only_option" ReasonHeadroom = "headroom" ReasonFailover = "failover" ReasonPreference = "preference" ) // Connection states the choice reads (wire.Conn* values). const ( StateHealthy = "healthy" StateLimited = "limited" coolOff = 15 * time.Minute coolOffLonger = time.Hour ) // capable is the capability matrix (connections spec §5, connectors // spec §4.4): which harness can run which role here. Codex runs // Engineering and Review through the thin runner's Codex step path (the // app-server in the implement or inspect containment). Pi runs them for // a metered provider (TensorX), and OpenCode for OpenCode Go (slice S5); // neither ever runs the coordinator. var capable = map[string][]string{ "copy": {"claude", "codex", "pi", "opencode"}, RoleCoordinator: {"claude", "codex"}, RoleEngineering: {"claude", "codex", "pi", "opencode"}, RoleReview: {"claude", "codex", "pi", "opencode"}, RoleResearch: {"claude", "codex"}, } // Capable reports whether a harness can run role here. A provider's own // CLI is its harness (claude, codex). func Capable(harness, role string) bool { return slices.Contains(capable[role], harness) } // Candidate is one of the person's connections on the runner, as the // runner knows it now. Used is the provider's reported utilization (0 to // 1) when Known. type Candidate struct { ID, Provider string // Harness runs the connection when it is not the provider's own CLI // (Pi for TensorX). Metered: billed per token (connectors spec §2.1). Harness string Metered bool State string ResetsAt time.Time Used float64 Known bool } // harness is the candidate's harness: its own, or its provider's CLI. func (c Candidate) harness() string { if c.Harness != "" { return c.Harness } return c.Provider } // Usable reports whether a connection may be chosen at now: healthy, or // limited with its reset passed. A connection not yet checked is not (its // keeper checks it before choosing); one connecting is not one yet. func (c Candidate) Usable(now time.Time) bool { switch c.State { case StateHealthy: return true case StateLimited: return !c.ResetsAt.IsZero() && !now.Before(c.ResetsAt) } return false } // Choice is the connection a run goes to and why. type Choice struct { ID, Reason string } // Choose picks one connection for role from the person's own candidates // (in the runner's configured order), spec §3: capable of the role, // usable now (healthy, or limited with its reset passed; never one // connecting or unchecked), not in avoid. The current binding, when it is // eligible, is kept: stickiness is a rule, a session leaves its // connection only on failure, with one exception: prefer (a provider, // "" for Automatic) names what the person prefers, and a session not on // it moves to it when it can answer. Callers ask at a natural boundary // only (a new turn, a new step), never mid-turn. Otherwise a preferred // connection first, then the one with the most reported headroom, a // connection whose provider reported nothing ranking below any with a // figure, then the configured order. ok is false when nothing can run it. // // spend is the run's leave to spend metered money (connectors spec §0 // decision 5 and §7: an urgent task or a released step). Without it a // metered connection is never a candidate; with it, one is chosen only // when no subscription connection can run the role. func Choose(cs []Candidate, role, current, prefer string, avoid []string, now time.Time, spend bool) (Choice, bool) { // A kept session on a metered connection stays there (connectors // spec §7, rule 1) while it can run, whatever a subscription offers: // the metered guard then holds it there, never moves it. for _, c := range cs { if current != "" && c.ID == current && c.Metered && spend && Capable(c.harness(), role) && c.Usable(now) && !slices.Contains(avoid, c.ID) { return Choice{ID: c.ID, Reason: ReasonHeadroom}, true } } var usable, metered []Candidate for _, c := range cs { if !Capable(c.harness(), role) || !c.Usable(now) || slices.Contains(avoid, c.ID) { continue } switch { case !c.Metered: usable = append(usable, c) case spend: metered = append(metered, c) } } if len(usable) == 0 { usable = metered } if len(usable) == 0 { return Choice{}, false } if len(usable) == 1 { return Choice{ID: usable[0].ID, Reason: ReasonOnlyOption}, true } preferred := slices.ContainsFunc(usable, func(c Candidate) bool { return c.Provider == prefer }) for _, c := range usable { if c.ID == current && (!preferred || c.Provider == prefer) { return Choice{ID: c.ID, Reason: ReasonHeadroom}, true } } if preferred { var mine []Candidate for _, c := range usable { if c.Provider == prefer { mine = append(mine, c) } } return Choice{ID: roomiest(mine).ID, Reason: ReasonPreference}, true } reason := ReasonHeadroom if current != "" { // The connection that ran this last cannot now. reason = ReasonFailover } return Choice{ID: roomiest(usable).ID, Reason: reason}, true } // roomiest is the candidate with the most reported headroom: one whose // provider reported nothing ranks below any with a figure, then the // configured order. func roomiest(usable []Candidate) Candidate { best := usable[0] for _, c := range usable[1:] { switch { case c.Known && !best.Known: best = c case c.Known && best.Known && c.Used < best.Used: best = c } } return best } // NextCheck is the earliest time a limited candidate becomes usable, or // zero when none will on its own. func NextCheck(cs []Candidate, now time.Time) time.Time { var at time.Time for _, c := range cs { if c.State == StateLimited && !c.ResetsAt.IsZero() && c.ResetsAt.After(now) && (at.IsZero() || c.ResetsAt.Before(at)) { at = c.ResetsAt } } return at } // LimitedUntil is when a connection the provider refused on quota may be // tried again, and the cool-off used: the provider's reset when it gave // one, else fifteen minutes, doubling for each refusal in a row (prev is // the previous cool-off, zero after a success) up to an hour (§2.7). func LimitedUntil(resets time.Time, prev time.Duration, now time.Time) (time.Time, time.Duration) { if !resets.IsZero() && resets.After(now) { return resets, 0 } wait := coolOff if prev > 0 { wait = min(2*prev, coolOffLonger) } return now.Add(wait), wait }