| 1 | // Package connect holds what the runner decides about connections without |
| 2 | // touching any of them: the one function that chooses a connection for a |
| 3 | // run (spec §3), the provider limit signals it reads (§2.7), and the |
| 4 | // sign-in flows that add a connection from the app (§§2.2, 2.3). |
| 5 | package connect |
| 6 | |
| 7 | import ( |
| 8 | "slices" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | // Roles a run is for. |
| 13 | const ( |
| 14 | RoleCoordinator = "coordinator" |
| 15 | RoleEngineering = "engineering" |
| 16 | RoleReview = "review" |
| 17 | // RoleResearch reads pages fetched for it (Research spec §4): no |
| 18 | // native tools on either harness. |
| 19 | RoleResearch = "research" |
| 20 | ) |
| 21 | |
| 22 | // Reasons a choice is recorded with (spec §4, slice 1 subset). |
| 23 | const ( |
| 24 | ReasonOnlyOption = "only_option" |
| 25 | ReasonHeadroom = "headroom" |
| 26 | ReasonFailover = "failover" |
| 27 | ReasonPreference = "preference" |
| 28 | ) |
| 29 | |
| 30 | // Connection states the choice reads (wire.Conn* values). |
| 31 | const ( |
| 32 | StateHealthy = "healthy" |
| 33 | StateLimited = "limited" |
| 34 | coolOff = 15 * time.Minute |
| 35 | coolOffLonger = time.Hour |
| 36 | ) |
| 37 | |
| 38 | // capable is the capability matrix (connections spec §5, connectors |
| 39 | // spec §4.4): which harness can run which role here. Codex runs |
| 40 | // Engineering and Review through the thin runner's Codex step path (the |
| 41 | // app-server in the implement or inspect containment). Pi runs them for |
| 42 | // a metered provider (TensorX), and OpenCode for OpenCode Go (slice S5); |
| 43 | // neither ever runs the coordinator. |
| 44 | var capable = map[string][]string{ |
| 45 | "copy": {"claude", "codex", "pi", "opencode"}, |
| 46 | RoleCoordinator: {"claude", "codex"}, |
| 47 | RoleEngineering: {"claude", "codex", "pi", "opencode"}, |
| 48 | RoleReview: {"claude", "codex", "pi", "opencode"}, |
| 49 | RoleResearch: {"claude", "codex"}, |
| 50 | } |
| 51 | |
| 52 | // Capable reports whether a harness can run role here. A provider's own |
| 53 | // CLI is its harness (claude, codex). |
| 54 | func Capable(harness, role string) bool { return slices.Contains(capable[role], harness) } |
| 55 | |
| 56 | // Candidate is one of the person's connections on the runner, as the |
| 57 | // runner knows it now. Used is the provider's reported utilization (0 to |
| 58 | // 1) when Known. |
| 59 | type Candidate struct { |
| 60 | ID, Provider string |
| 61 | // Harness runs the connection when it is not the provider's own CLI |
| 62 | // (Pi for TensorX). Metered: billed per token (connectors spec §2.1). |
| 63 | Harness string |
| 64 | Metered bool |
| 65 | State string |
| 66 | ResetsAt time.Time |
| 67 | Used float64 |
| 68 | Known bool |
| 69 | } |
| 70 | |
| 71 | // harness is the candidate's harness: its own, or its provider's CLI. |
| 72 | func (c Candidate) harness() string { |
| 73 | if c.Harness != "" { |
| 74 | return c.Harness |
| 75 | } |
| 76 | return c.Provider |
| 77 | } |
| 78 | |
| 79 | // Usable reports whether a connection may be chosen at now: healthy, or |
| 80 | // limited with its reset passed. A connection not yet checked is not (its |
| 81 | // keeper checks it before choosing); one connecting is not one yet. |
| 82 | func (c Candidate) Usable(now time.Time) bool { |
| 83 | switch c.State { |
| 84 | case StateHealthy: |
| 85 | return true |
| 86 | case StateLimited: |
| 87 | return !c.ResetsAt.IsZero() && !now.Before(c.ResetsAt) |
| 88 | } |
| 89 | return false |
| 90 | } |
| 91 | |
| 92 | // Choice is the connection a run goes to and why. |
| 93 | type Choice struct { |
| 94 | ID, Reason string |
| 95 | } |
| 96 | |
| 97 | // Choose picks one connection for role from the person's own candidates |
| 98 | // (in the runner's configured order), spec §3: capable of the role, |
| 99 | // usable now (healthy, or limited with its reset passed; never one |
| 100 | // connecting or unchecked), not in avoid. The current binding, when it is |
| 101 | // eligible, is kept: stickiness is a rule, a session leaves its |
| 102 | // connection only on failure, with one exception: prefer (a provider, |
| 103 | // "" for Automatic) names what the person prefers, and a session not on |
| 104 | // it moves to it when it can answer. Callers ask at a natural boundary |
| 105 | // only (a new turn, a new step), never mid-turn. Otherwise a preferred |
| 106 | // connection first, then the one with the most reported headroom, a |
| 107 | // connection whose provider reported nothing ranking below any with a |
| 108 | // figure, then the configured order. ok is false when nothing can run it. |
| 109 | // |
| 110 | // spend is the run's leave to spend metered money (connectors spec §0 |
| 111 | // decision 5 and §7: an urgent task or a released step). Without it a |
| 112 | // metered connection is never a candidate; with it, one is chosen only |
| 113 | // when no subscription connection can run the role. |
| 114 | func Choose(cs []Candidate, role, current, prefer string, avoid []string, now time.Time, spend bool) (Choice, bool) { |
| 115 | // A kept session on a metered connection stays there (connectors |
| 116 | // spec §7, rule 1) while it can run, whatever a subscription offers: |
| 117 | // the metered guard then holds it there, never moves it. |
| 118 | for _, c := range cs { |
| 119 | if current != "" && c.ID == current && c.Metered && spend && Capable(c.harness(), role) && c.Usable(now) && !slices.Contains(avoid, c.ID) { |
| 120 | return Choice{ID: c.ID, Reason: ReasonHeadroom}, true |
| 121 | } |
| 122 | } |
| 123 | var usable, metered []Candidate |
| 124 | for _, c := range cs { |
| 125 | if !Capable(c.harness(), role) || !c.Usable(now) || slices.Contains(avoid, c.ID) { |
| 126 | continue |
| 127 | } |
| 128 | switch { |
| 129 | case !c.Metered: |
| 130 | usable = append(usable, c) |
| 131 | case spend: |
| 132 | metered = append(metered, c) |
| 133 | } |
| 134 | } |
| 135 | if len(usable) == 0 { |
| 136 | usable = metered |
| 137 | } |
| 138 | if len(usable) == 0 { |
| 139 | return Choice{}, false |
| 140 | } |
| 141 | if len(usable) == 1 { |
| 142 | return Choice{ID: usable[0].ID, Reason: ReasonOnlyOption}, true |
| 143 | } |
| 144 | preferred := slices.ContainsFunc(usable, func(c Candidate) bool { return c.Provider == prefer }) |
| 145 | for _, c := range usable { |
| 146 | if c.ID == current && (!preferred || c.Provider == prefer) { |
| 147 | return Choice{ID: c.ID, Reason: ReasonHeadroom}, true |
| 148 | } |
| 149 | } |
| 150 | if preferred { |
| 151 | var mine []Candidate |
| 152 | for _, c := range usable { |
| 153 | if c.Provider == prefer { |
| 154 | mine = append(mine, c) |
| 155 | } |
| 156 | } |
| 157 | return Choice{ID: roomiest(mine).ID, Reason: ReasonPreference}, true |
| 158 | } |
| 159 | reason := ReasonHeadroom |
| 160 | if current != "" { |
| 161 | // The connection that ran this last cannot now. |
| 162 | reason = ReasonFailover |
| 163 | } |
| 164 | return Choice{ID: roomiest(usable).ID, Reason: reason}, true |
| 165 | } |
| 166 | |
| 167 | // roomiest is the candidate with the most reported headroom: one whose |
| 168 | // provider reported nothing ranks below any with a figure, then the |
| 169 | // configured order. |
| 170 | func roomiest(usable []Candidate) Candidate { |
| 171 | best := usable[0] |
| 172 | for _, c := range usable[1:] { |
| 173 | switch { |
| 174 | case c.Known && !best.Known: |
| 175 | best = c |
| 176 | case c.Known && best.Known && c.Used < best.Used: |
| 177 | best = c |
| 178 | } |
| 179 | } |
| 180 | return best |
| 181 | } |
| 182 | |
| 183 | // NextCheck is the earliest time a limited candidate becomes usable, or |
| 184 | // zero when none will on its own. |
| 185 | func NextCheck(cs []Candidate, now time.Time) time.Time { |
| 186 | var at time.Time |
| 187 | for _, c := range cs { |
| 188 | if c.State == StateLimited && !c.ResetsAt.IsZero() && c.ResetsAt.After(now) && (at.IsZero() || c.ResetsAt.Before(at)) { |
| 189 | at = c.ResetsAt |
| 190 | } |
| 191 | } |
| 192 | return at |
| 193 | } |
| 194 | |
| 195 | // LimitedUntil is when a connection the provider refused on quota may be |
| 196 | // tried again, and the cool-off used: the provider's reset when it gave |
| 197 | // one, else fifteen minutes, doubling for each refusal in a row (prev is |
| 198 | // the previous cool-off, zero after a success) up to an hour (§2.7). |
| 199 | func LimitedUntil(resets time.Time, prev time.Duration, now time.Time) (time.Time, time.Duration) { |
| 200 | if !resets.IsZero() && resets.After(now) { |
| 201 | return resets, 0 |
| 202 | } |
| 203 | wait := coolOff |
| 204 | if prev > 0 { |
| 205 | wait = min(2*prev, coolOffLonger) |
| 206 | } |
| 207 | return now.Add(wait), wait |
| 208 | } |
| 209 | |