| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "math" |
| 6 | |
| 7 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 8 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 9 | "amadan.net/oficina/equipo/internal/schedule" |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | ) |
| 12 | |
| 13 | // Paused work (spec 2026-11-24-paused-work-design.md). A step the runner |
| 14 | // holds, or one waiting for its runner while that runner is offline, is |
| 15 | // paused: it carries on by itself, or by the person's tap. The runner |
| 16 | // says why it holds a step; what the instance adds is when it began, how |
| 17 | // full the held subscription is, and what Run now would do, so every |
| 18 | // client (the web, the apps, Base) words the same answer. |
| 19 | |
| 20 | // stepPaused is what the instance adds to step s of task k, nil when it |
| 21 | // does not wait. A read that fails leaves the prediction out: an offer |
| 22 | // the instance cannot make is not made. |
| 23 | func (t *txn) stepPaused(k taskRecord, s stepRecord) *wire.StepPaused { |
| 24 | if wire.FinalStage(k.Stage) || k.CancelRequested || wire.StepTerminal(s.State) { |
| 25 | return nil |
| 26 | } |
| 27 | h := stepHold(s) |
| 28 | out := &wire.StepPaused{} |
| 29 | if s.RunnerID != "" && (h != nil || s.State == wire.StepQueued) { |
| 30 | if rs, err := t.runners(s.Person); err == nil { |
| 31 | for _, r := range rs { |
| 32 | if r.ID == s.RunnerID && !r.Online { |
| 33 | out.Offline = true |
| 34 | if !r.SeenAt.IsZero() { |
| 35 | at := r.SeenAt.UTC() |
| 36 | out.Since = &at |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | if out.Offline { |
| 43 | return out |
| 44 | } |
| 45 | if h == nil { |
| 46 | return nil |
| 47 | } |
| 48 | if s.HeldAt != nil { |
| 49 | at := s.HeldAt.UTC() |
| 50 | out.Since = &at |
| 51 | } |
| 52 | recs, err := t.connections(s.Person) |
| 53 | if err != nil { |
| 54 | return out |
| 55 | } |
| 56 | mine := make([]connectionRecord, 0, len(recs)) |
| 57 | for _, r := range recs { |
| 58 | if r.RunnerID == s.RunnerID && r.LocalID != "" && labelled(connectionView(r)) { |
| 59 | mine = append(mine, r) |
| 60 | } |
| 61 | } |
| 62 | for _, r := range mine { |
| 63 | if r.LocalID == h.Connection && r.Kind != wire.KindAPIKey { |
| 64 | if used, ok := usedPercent(r); ok { |
| 65 | out.UsedPercent = &used |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | out.RunNow = t.runNowOffer(k, s, h, mine) |
| 70 | return out |
| 71 | } |
| 72 | |
| 73 | // usedPercent is a subscription's fullest reported window, in percent, |
| 74 | // 100 when it is limited; ok false when nothing was read. |
| 75 | func usedPercent(r connectionRecord) (int, bool) { |
| 76 | if r.State == wire.ConnLimited { |
| 77 | return 100, true |
| 78 | } |
| 79 | ws := windowsOfRecord(r) |
| 80 | if len(ws) == 0 { |
| 81 | return 0, false |
| 82 | } |
| 83 | m := 0.0 |
| 84 | for _, w := range ws { |
| 85 | m = max(m, w.Used) |
| 86 | } |
| 87 | return int(math.Min(100, math.Round(m*100))), true |
| 88 | } |
| 89 | |
| 90 | // windowsOfRecord are a connection's reported windows as Decide reads |
| 91 | // them (the runner's windowsOf): used from 0 to 1, Claude's one figure |
| 92 | // as one window when it gave no windows. |
| 93 | func windowsOfRecord(r connectionRecord) []schedule.Window { |
| 94 | if r.Headroom == "" { |
| 95 | return nil |
| 96 | } |
| 97 | var h wire.Headroom |
| 98 | if json.Unmarshal([]byte(r.Headroom), &h) != nil { |
| 99 | return nil |
| 100 | } |
| 101 | var out []schedule.Window |
| 102 | for _, w := range h.Windows { |
| 103 | out = append(out, schedule.Window{Name: w.Name, Used: w.UsedPercent / 100, Minutes: w.Minutes, ResetsAt: w.ResetsAt}) |
| 104 | } |
| 105 | if len(out) == 0 && h.Utilization != nil { |
| 106 | out = append(out, schedule.Window{Name: "utilization", Used: *h.Utilization, ResetsAt: h.ResetsAt}) |
| 107 | } |
| 108 | return out |
| 109 | } |
| 110 | |
| 111 | // roleOf is the scheduler's role for a step's specialist ("" for one it |
| 112 | // does not schedule). |
| 113 | func roleOf(specialist string) string { |
| 114 | switch specialist { |
| 115 | case wire.SpecialistEngineering: |
| 116 | return schedule.RoleEngineering |
| 117 | case wire.SpecialistReview: |
| 118 | return schedule.RoleReview |
| 119 | case wire.SpecialistResearch: |
| 120 | return schedule.RoleResearch |
| 121 | } |
| 122 | return "" |
| 123 | } |
| 124 | |
| 125 | // runNowOffer is what Run now would do for the held step (decision 2). |
| 126 | // Nil when Run now cannot pass the hold (a spending bar, housekeeping's |
| 127 | // own attempt, a runner below the scheduler), when the step's role is not |
| 128 | // scheduled, when a Run now for this hold was already written (S2: it is |
| 129 | // on its way, or the runner could not honour it), or when Decide would |
| 130 | // hold it anyway. A runner below protocol 29 cannot be held to a |
| 131 | // connection, so it is offered plain Run now, naming nothing (Plain). |
| 132 | func (t *txn) runNowOffer(k taskRecord, s stepRecord, h *wire.StepHold, mine []connectionRecord) *wire.RunNowOffer { |
| 133 | o, _ := t.predictRunNow(k, s, h, mine) |
| 134 | return o |
| 135 | } |
| 136 | |
| 137 | // predictRunNow is runNowOffer and the runner's local id of the |
| 138 | // connection it names, which pins the release (protocol 29). |
| 139 | func (t *txn) predictRunNow(k taskRecord, s stepRecord, h *wire.StepHold, mine []connectionRecord) (*wire.RunNowOffer, string) { |
| 140 | role := roleOf(s.Specialist) |
| 141 | if role == "" || h.Reason == wire.HoldBudget || h.Reason == wire.HoldSpendUnknown || housekeepingAttempt(s) { |
| 142 | return nil, "" |
| 143 | } |
| 144 | var prior releaseRecord |
| 145 | if err := t.db.Where("step_id = ? AND step_revision = ?", s.ID, h.StepRevision).Limit(1).Find(&prior).Error; err != nil || prior.ID != "" { |
| 146 | return nil, "" |
| 147 | } |
| 148 | proto, err := t.runnerProtocol(s.Person, s.RunnerID) |
| 149 | switch { |
| 150 | case err != nil || proto < wire.ProtocolScheduler: |
| 151 | return nil, "" |
| 152 | case proto < wire.ProtocolPinnedRelease: |
| 153 | // It may bill when a connection that bills per use could take it. |
| 154 | o := &wire.RunNowOffer{Plain: true} |
| 155 | for _, r := range mine { |
| 156 | if c, ok := scheduleConn(r, role); ok && c.Billing == schedule.Metered && c.Capable && len(c.Models) > 0 { |
| 157 | o.MayBill = true |
| 158 | } |
| 159 | } |
| 160 | return o, "" |
| 161 | } |
| 162 | in, by, err := t.scheduleInput(k, s, role, mine) |
| 163 | if err != nil { |
| 164 | return nil, "" |
| 165 | } |
| 166 | d := decideRelease(in, role, t.coordinatorFamily(s.Person, mine)) |
| 167 | r, ok := by[d.Connection] |
| 168 | if !d.Run || !ok { |
| 169 | return nil, "" |
| 170 | } |
| 171 | o := &wire.RunNowOffer{Connection: r.ID, Provider: r.Provider, Name: ProviderName(r.Provider), Billing: wire.BillingSubscription, Same: r.LocalID == h.Connection} |
| 172 | if r.Kind == wire.KindAPIKey { |
| 173 | o.Billing = wire.BillingMetered |
| 174 | } |
| 175 | if o.Same && o.Billing == wire.BillingSubscription { |
| 176 | if used, ok := usedPercent(r); ok { |
| 177 | o.LeftPercent = max(0, 100-used) |
| 178 | } |
| 179 | } |
| 180 | return o, r.LocalID |
| 181 | } |
| 182 | |
| 183 | // scheduleInput is the step's Decide input with Run now's leave, built |
| 184 | // from what the instance holds the way the runner builds its own |
| 185 | // (thin/schedule.go stepInput): the connections on the step's runner, |
| 186 | // the preference, and the step's own facts: Review's Engineer (the family |
| 187 | // rule), and an Engineering fix round's kept session. |
| 188 | func (t *txn) scheduleInput(k taskRecord, s stepRecord, role string, mine []connectionRecord) (schedule.Input, map[string]connectionRecord, error) { |
| 189 | pref, err := t.preferenceOf(s.Person) |
| 190 | if err != nil { |
| 191 | return schedule.Input{}, nil, err |
| 192 | } |
| 193 | in := schedule.Input{Version: schedule.Version, Now: t.now(), Preference: schedule.Preference{Provider: pref.Provider, Until: pref.Until}, |
| 194 | Step: schedule.Step{Role: role, Priority: k.Priority, By: k.DueBy, DeadlineNotified: true, Release: "run_now"}} |
| 195 | by := map[string]connectionRecord{} |
| 196 | for _, r := range mine { |
| 197 | c, ok := scheduleConn(r, role) |
| 198 | if !ok { |
| 199 | continue |
| 200 | } |
| 201 | in.Conns = append(in.Conns, c) |
| 202 | by[c.ID] = r |
| 203 | } |
| 204 | steps, err := t.steps(k.ID) |
| 205 | if err != nil { |
| 206 | return schedule.Input{}, nil, err |
| 207 | } |
| 208 | switch s.Specialist { |
| 209 | case wire.SpecialistReview: |
| 210 | // Engineering's connection, as the dispatch names it (AvoidAccount |
| 211 | // is the review step's Account), and the families pushed before. |
| 212 | if s.Account != "" { |
| 213 | e := &schedule.Engineer{ID: s.Account} |
| 214 | for _, c := range in.Conns { |
| 215 | if c.ID == s.Account { |
| 216 | e.Family, e.Account = c.Family, c.Account |
| 217 | } |
| 218 | } |
| 219 | for _, st := range steps { |
| 220 | if st.Specialist == wire.SpecialistEngineering && st.Account == s.Account && st.Family != "" { |
| 221 | e.Family = st.Family |
| 222 | } |
| 223 | } |
| 224 | in.Step.Engineer = e |
| 225 | } |
| 226 | case wire.SpecialistEngineering: |
| 227 | // A fix round resumes the session the round before ran on. |
| 228 | if s.Round > 0 { |
| 229 | for _, st := range steps { |
| 230 | if st.Specialist == wire.SpecialistEngineering && st.Idx < s.Idx && st.Account != "" { |
| 231 | in.Step.Kept, in.Step.KeptModel = st.Account, st.Model |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | return in, by, nil |
| 237 | } |
| 238 | |
| 239 | // decideRelease is what a release would do (the runner's own order, |
| 240 | // thin/research.go): Research first with every subscription of another |
| 241 | // family than the coordinator's avoided, then with none; anything else, |
| 242 | // Decide. |
| 243 | func decideRelease(in schedule.Input, role, family string) schedule.Decision { |
| 244 | if role != schedule.RoleResearch || family == "" { |
| 245 | return schedule.Decide(in) |
| 246 | } |
| 247 | first := in |
| 248 | first.Step.Avoid = nil |
| 249 | for _, c := range in.Conns { |
| 250 | if c.Billing != schedule.Metered && c.Family != family { |
| 251 | first.Step.Avoid = append(first.Step.Avoid, c.ID) |
| 252 | } |
| 253 | } |
| 254 | if d := schedule.Decide(first); d.Run { |
| 255 | return d |
| 256 | } |
| 257 | return schedule.Decide(in) |
| 258 | } |
| 259 | |
| 260 | // coordinatorFamily is the family of the connection the person's |
| 261 | // coordinator last answered on ("" unknown), Research's first choice. |
| 262 | func (t *txn) coordinatorFamily(person string, mine []connectionRecord) string { |
| 263 | var r turnRecord |
| 264 | if t.db.Where("person = ? AND coalesce(connection, '') <> ''", person).Order("created_at DESC, id DESC").Limit(1).Find(&r).Error != nil { |
| 265 | return "" |
| 266 | } |
| 267 | for _, c := range mine { |
| 268 | if c.LocalID == r.Connection && c.Kind != wire.KindAPIKey { |
| 269 | return c.Provider |
| 270 | } |
| 271 | } |
| 272 | return "" |
| 273 | } |
| 274 | |
| 275 | // scheduleConn is one connection as Decide reads it, from what the |
| 276 | // instance last heard (the runner's scheduleFacts, from thin.db). ok |
| 277 | // false for one Decide would never take. |
| 278 | func scheduleConn(r connectionRecord, role string) (schedule.Conn, bool) { |
| 279 | if r.State != wire.ConnHealthy && r.State != wire.ConnLimited { |
| 280 | return schedule.Conn{}, false |
| 281 | } |
| 282 | c := schedule.Conn{ID: r.LocalID, Provider: r.Provider, Family: provider.SubscriptionFamily(r.Provider), Account: r.Label, State: r.State, Billing: schedule.Subscription, Capable: connect.Capable(r.Provider, role), Windows: windowsOfRecord(r)} |
| 283 | if r.State == wire.ConnLimited { |
| 284 | var h wire.Headroom |
| 285 | if json.Unmarshal([]byte(r.Headroom), &h) == nil && h.ResetsAt != nil { |
| 286 | c.LimitedUntil = *h.ResetsAt |
| 287 | } |
| 288 | } |
| 289 | if r.Kind != wire.KindAPIKey { |
| 290 | return c, true |
| 291 | } |
| 292 | v := connectionView(r) |
| 293 | c.Billing, c.Capable, c.Windows, c.Family = schedule.Metered, connect.Capable(r.Harness, role), nil, "" |
| 294 | if v.Budget == nil || v.Spend == nil { |
| 295 | // A metered connection with no budget or spend read takes |
| 296 | // nothing (the runner's guard). |
| 297 | return schedule.Conn{}, false |
| 298 | } |
| 299 | c.SpendUnknown, c.Busy = v.Spend.Unknown, v.Spend.Running |
| 300 | c.SpendDay, c.SpendMonth, c.BudgetDay, c.BudgetMonth = v.Spend.Day, v.Spend.Month, v.Budget.Day, v.Budget.Month |
| 301 | for _, m := range v.Models { |
| 302 | if m.Allowed && m.Eligible && m.State != wire.ModelUnhealthy { |
| 303 | c.Models = append(c.Models, schedule.Model{ID: m.ID, Family: m.Family, Tier: m.Tier}) |
| 304 | } |
| 305 | } |
| 306 | return c, true |
| 307 | } |
| 308 | |