oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "database/sql"
6 "encoding/json"
7 "errors"
8 "log/slog"
9 "slices"
10 "sync"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/runner"
14 "amadan.net/oficina/equipo/internal/runner/connect"
15 "amadan.net/oficina/equipo/internal/runner/metered"
16 "amadan.net/oficina/equipo/internal/runner/provider"
17 "amadan.net/oficina/equipo/internal/wire"
18)
19
20const connSchema = `
21CREATE TABLE IF NOT EXISTS conn_state (id TEXT PRIMARY KEY, state TEXT NOT NULL, resets_at TEXT NOT NULL DEFAULT '', window TEXT NOT NULL DEFAULT '', cooloff INTEGER NOT NULL DEFAULT 0, headroom TEXT NOT NULL DEFAULT '', plan TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL);
22CREATE TABLE IF NOT EXISTS conn_expiry (id TEXT PRIMARY KEY, expires_at TEXT NOT NULL);
23CREATE TABLE IF NOT EXISTS conn_validated (id TEXT PRIMARY KEY, at TEXT NOT NULL);
24`
25
26// ErrNoConnection: nothing the person connected can run the role now.
27var ErrNoConnection = errors.New("no connection can run this now")
28
29// connState is what the runner knows of one connection beyond its binding.
30type connState struct {
31 State string
32 ResetsAt time.Time
33 Window string
34 CoolOff time.Duration
35 Headroom *wire.Headroom
36 Plan string
37}
38
39// Conns is the runner's view of its connections: the bindings file (what
40// is connected, for whom) and, per connection, health from the hourly
41// refresh and limits the providers reported, kept in thin.db so a
42// restart does not hammer a limited account. It is the only place that
43// chooses a connection for a run (connect.Choose).
44type Conns struct {
45 Runner runner.Config
46 State *State
47 Logger *slog.Logger
48 // Refresh runs the official CLI in a source home under its lock.
49 Refresh func(context.Context, provider.Binding) (provider.Identity, error)
50 LockWait time.Duration
51 // Turn, when set, is the machine's turn, taken before a home's lock
52 // (a Mac: Refresh needs the turn, and a step holds it while it opens
53 // the home): the lock is never held while the turn is awaited.
54 Turn func(context.Context) (context.Context, func(), error)
55 // ClaudeStatus reads the plan alongside the existing hourly local status.
56 ClaudeStatus func(context.Context, provider.Binding) (provider.Identity, string, error)
57 ClaudeUsage *ProfileReader
58 usageMu sync.Mutex
59 // Verify checks a token connection with a real request (CheckToken);
60 // without it nothing can prove a token, so its state never improves.
61 Verify func(context.Context, runner.AccountBinding) error
62 // Changed is called when a connection may have become usable or its
63 // standing changed (a hello is due; held turns look again).
64 Changed func()
65 // Meter is the metered guard over the metered connections in
66 // thin.db (connectors spec S1); nil, none can be added.
67 Meter *metered.Meter
68 // Reading is a connection's reading probe (rev 3 §2.7: the harness's
69 // cheapest request, never a model turn), which the scheduler runs on
70 // a reading older than fifteen minutes before it decides; nil, none
71 // and a reading stays as it was last reported. Claude OAuth usage
72 // refreshes with the local status pass instead.
73 Reading func(context.Context, runner.AccountBinding) (*connect.Limit, error)
74 // Readings is told a connection's reported headroom changed: steps
75 // the scheduler holds look again.
76 Readings func()
77 // Prober runs a model's first-use probe inside a step's admission
78 // (§16.4); the Connector's, which holds the provider clients.
79 Prober ProbeFunc
80
81 mu sync.Mutex
82 live map[string]connState
83 // validated is when a real request on each connection last got the
84 // provider's answer (conn_validated): a token connection is a
85 // connection only from then; its CLI's local status never sets it.
86 validated map[string]time.Time
87 now func() time.Time
88 // probed is when each connection's reading probe last ran.
89 probed map[string]time.Time
90}
91
92func (c *Conns) clock() time.Time {
93 if c.now != nil {
94 return c.now()
95 }
96 return time.Now()
97}
98
99func (c *Conns) load(ctx context.Context) error {
100 c.mu.Lock()
101 defer c.mu.Unlock()
102 if c.live != nil {
103 return nil
104 }
105 c.live, c.validated = map[string]connState{}, map[string]time.Time{}
106 vrows, err := c.State.db.QueryContext(ctx, "SELECT id, at FROM conn_validated")
107 if err != nil {
108 return err
109 }
110 for vrows.Next() {
111 var id, at string
112 if vrows.Scan(&id, &at) == nil {
113 if t, err := time.Parse(time.RFC3339Nano, at); err == nil {
114 c.validated[id] = t
115 }
116 }
117 }
118 vrows.Close()
119 rows, err := c.State.db.QueryContext(ctx, "SELECT id, state, resets_at, window, cooloff, headroom, plan FROM conn_state")
120 if err != nil {
121 return err
122 }
123 defer rows.Close()
124 for rows.Next() {
125 var id, resets, headroom string
126 var cs connState
127 var cool int64
128 if err = rows.Scan(&id, &cs.State, &resets, &cs.Window, &cool, &headroom, &cs.Plan); err != nil {
129 return err
130 }
131 cs.ResetsAt, _ = time.Parse(time.RFC3339Nano, resets)
132 cs.CoolOff = time.Duration(cool)
133 if headroom != "" {
134 _ = json.Unmarshal([]byte(headroom), &cs.Headroom)
135 }
136 c.live[id] = cs
137 }
138 return rows.Err()
139}
140
141// save records one connection's state; c.mu is held.
142func (c *Conns) save(id string, cs connState) {
143 c.live[id] = cs
144 resets := ""
145 if !cs.ResetsAt.IsZero() {
146 resets = cs.ResetsAt.UTC().Format(time.RFC3339Nano)
147 }
148 headroom := ""
149 if cs.Headroom != nil {
150 raw, _ := json.Marshal(cs.Headroom)
151 headroom = string(raw)
152 }
153 _, err := c.State.db.Exec("INSERT INTO conn_state(id, state, resets_at, window, cooloff, headroom, plan, updated_at) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET state=excluded.state, resets_at=excluded.resets_at, window=excluded.window, cooloff=excluded.cooloff, headroom=excluded.headroom, plan=excluded.plan, updated_at=excluded.updated_at", id, cs.State, resets, cs.Window, int64(cs.CoolOff), headroom, cs.Plan, now())
154 if err != nil && c.Logger != nil {
155 c.Logger.Warn("connection state", "err", sanitize(err))
156 }
157}
158
159func (c *Conns) changed() {
160 if c.Changed != nil {
161 c.Changed()
162 }
163}
164
165// bindings are the configured connections, in the file's order.
166func (c *Conns) bindings() []runner.AccountBinding {
167 bs, err := runner.LoadBindings(c.Runner.AccountBindingsPath)
168 if err != nil {
169 return nil
170 }
171 return bs
172}
173
174// Binding is one configured connection by id.
175func (c *Conns) Binding(id string) (runner.AccountBinding, bool) {
176 for _, b := range c.bindings() {
177 if b.ID == id {
178 return b, true
179 }
180 }
181 return runner.AccountBinding{}, false
182}
183
184// Mine are the person's own connections, in the configured order. A
185// teammate's connection is never selectable for another person's work.
186func (c *Conns) Mine(person string) []runner.AccountBinding {
187 var out []runner.AccountBinding
188 for _, b := range c.bindings() {
189 if b.PersonID == person && (b.Provider == "claude" || b.Provider == "codex") {
190 out = append(out, b)
191 }
192 }
193 return out
194}
195
196func (c *Conns) candidate(b runner.AccountBinding) connect.Candidate {
197 cs := c.live[b.ID]
198 if b.Kind == wire.KindToken && c.validated[b.ID].IsZero() {
199 // Never answered a real request: not a connection yet.
200 cs.State = ""
201 }
202 cand := connect.Candidate{ID: b.ID, Provider: b.Provider, State: cs.State, ResetsAt: cs.ResetsAt}
203 if cs.Headroom != nil && cs.Headroom.Utilization != nil {
204 cand.Used, cand.Known = *cs.Headroom.Utilization, true
205 }
206 return cand
207}
208
209// MeteredMine are the person's metered connections (connectors spec
210// S1), as bindings a step can be chosen onto: provider TensorX, run by
211// Pi, the family of the connection's one model. Only validated ones,
212// not being signed out.
213func (c *Conns) MeteredMine(ctx context.Context, person string) []runner.AccountBinding {
214 if c.Meter == nil {
215 return nil
216 }
217 conns, err := metered.List(ctx, c.State.db)
218 if err != nil {
219 c.warn("metered connections", err)
220 return nil
221 }
222 var out []runner.AccountBinding
223 for _, m := range conns {
224 if m.Person == person && m.Validated && !m.Retiring && meteredHarness(m.Provider, m.Harness) {
225 out = append(out, meteredBinding(m))
226 }
227 }
228 return out
229}
230
231// meteredBinding is a metered connection as a binding: its id is its
232// local id (the usage rows' connection, as the ledger keys them).
233func meteredBinding(m metered.Conn) runner.AccountBinding {
234 return runner.AccountBinding{ID: m.LocalID, LocalID: m.LocalID, PersonID: m.Person, Provider: m.Provider, Family: meteredFamily(m.Provider, m.Model), Model: m.Model, AccountID: m.LocalID, CredentialHome: m.Home, Kind: wire.KindAPIKey}
235}
236
237// Metered reports whether a binding is a metered connection's.
238func Metered(b runner.AccountBinding) bool { return b.Kind == wire.KindAPIKey }
239
240// meteredCandidate is a metered connection as Choose sees it: usable
241// while its key was not refused (the guard looks at the slot, the
242// budget and the spend at admission), unless limited.
243func (c *Conns) meteredCandidate(ctx context.Context, b runner.AccountBinding) connect.Candidate {
244 cand := connect.Candidate{ID: b.ID, Provider: b.Provider, Harness: harnessOf(b), Metered: true, State: connect.StateHealthy}
245 if m, ok, err := metered.Get(ctx, c.State.db, b.LocalID); err != nil || !ok || m.Refused {
246 cand.State = wire.ConnSignInAgain
247 }
248 if cs := c.live[b.ID]; cs.State == wire.ConnLimited || cs.State == wire.ConnSignInAgain {
249 cand.State, cand.ResetsAt = cs.State, cs.ResetsAt
250 }
251 return cand
252}
253
254// Choose picks the person's connection for role (connect.Choose), with
255// no leave to spend: never a metered connection (the coordinator's
256// turns, and any run that carries no leave). It returns
257// ErrNoConnection when none can run it now.
258func (c *Conns) Choose(ctx context.Context, person, role, current string, avoid []string) (runner.AccountBinding, connect.Choice, error) {
259 return c.ChooseFor(ctx, person, role, current, avoid, false)
260}
261
262// ChooseFor is Choose for a run that says whether it has leave to spend
263// metered money (connectors spec §0 decision 5: an urgent task or a
264// released step); without it no metered connection is a candidate.
265func (c *Conns) ChooseFor(ctx context.Context, person, role, current string, avoid []string, spend bool) (runner.AccountBinding, connect.Choice, error) {
266 if err := c.load(ctx); err != nil {
267 return runner.AccountBinding{}, connect.Choice{}, err
268 }
269 mine := c.Mine(person)
270 var metered []runner.AccountBinding
271 if spend {
272 metered = c.MeteredMine(ctx, person)
273 }
274 // Only a checked connection is chosen: one never checked (just added
275 // by the terminal login, or first seen after a restage) is checked now.
276 for _, b := range mine {
277 c.mu.Lock()
278 unknown := c.live[b.ID].State == ""
279 c.mu.Unlock()
280 if unknown && connect.Capable(b.Provider, role) {
281 c.checkOne(ctx, b)
282 }
283 }
284 c.mu.Lock()
285 var cs []connect.Candidate
286 for _, b := range mine {
287 cs = append(cs, c.candidate(b))
288 }
289 for _, b := range metered {
290 cs = append(cs, c.meteredCandidate(ctx, b))
291 }
292 c.mu.Unlock()
293 prefer, err := c.Preference(ctx, person)
294 if err != nil {
295 return runner.AccountBinding{}, connect.Choice{}, err
296 }
297 choice, ok := connect.Choose(cs, role, current, prefer.Provider, avoid, c.clock(), spend)
298 if !ok {
299 return runner.AccountBinding{}, connect.Choice{}, ErrNoConnection
300 }
301 for _, b := range append(mine, metered...) {
302 if b.ID == choice.ID {
303 return b, choice, nil
304 }
305 }
306 return runner.AccountBinding{}, connect.Choice{}, ErrNoConnection
307}
308
309// Preference is the person's preference as the instance last sent it;
310// one whose end has passed is Automatic (connectors spec §7).
311func (c *Conns) Preference(ctx context.Context, person string) (wire.Preferences, error) {
312 var p wire.Preferences
313 raw, err := c.State.meta(ctx, "prefer:"+person)
314 if err != nil || raw == "" {
315 return p, err
316 }
317 if err := json.Unmarshal([]byte(raw), &p); err != nil {
318 return p, err
319 }
320 if p.Until != nil && !c.clock().Before(*p.Until) {
321 p.Provider, p.Until = "", nil
322 }
323 return p, nil
324}
325
326// Prefer records the person's preference (a durable frame, once); an
327// older revision than the one held changes nothing.
328func (c *Conns) Prefer(ctx context.Context, frameID string, cmd wire.PreferenceCommand) error {
329 if !wire.PreferenceProviders[cmd.Provider] {
330 return nil
331 }
332 err := c.State.tx(ctx, func(t *sql.Tx) error {
333 fresh, err := seen(t, frameID)
334 if err != nil || !fresh {
335 return err
336 }
337 var raw string
338 err = t.QueryRowContext(ctx, "SELECT value FROM meta WHERE key=?", "prefer:"+cmd.Person).Scan(&raw)
339 if err != nil && !errors.Is(err, sql.ErrNoRows) {
340 return err
341 }
342 var held wire.Preferences
343 if raw != "" {
344 _ = json.Unmarshal([]byte(raw), &held)
345 }
346 if cmd.Revision <= held.Revision {
347 return nil
348 }
349 next, _ := json.Marshal(wire.Preferences{Provider: cmd.Provider, Revision: cmd.Revision, Until: cmd.Until})
350 _, err = t.ExecContext(ctx, "INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", "prefer:"+cmd.Person, string(next))
351 return err
352 })
353 if err == nil {
354 c.changed()
355 }
356 return err
357}
358
359// Usable reports whether a connection may run now (healthy, not
360// limited): a question pinned to its step's account asks this.
361func (c *Conns) Usable(id string) bool {
362 if c.load(context.Background()) != nil {
363 return false
364 }
365 b, ok := c.Binding(id)
366 if !ok {
367 return false
368 }
369 c.mu.Lock()
370 defer c.mu.Unlock()
371 return c.candidate(b).Usable(c.clock())
372}
373
374// NextCheck is when a limited connection of the person's comes back on
375// its own, or zero.
376func (c *Conns) NextCheck(person string) time.Time {
377 if c.load(context.Background()) != nil {
378 return time.Time{}
379 }
380 mine := c.Mine(person)
381 c.mu.Lock()
382 defer c.mu.Unlock()
383 var cs []connect.Candidate
384 for _, b := range mine {
385 cs = append(cs, c.candidate(b))
386 }
387 return connect.NextCheck(cs, c.clock())
388}
389
390// Limit records a provider's quota refusal on a connection (spec §2.7):
391// limited until the provider's reset, or a cool-off when it gave none.
392func (c *Conns) Limit(id string, l connect.Limit) time.Time {
393 if c.load(context.Background()) != nil {
394 return time.Time{}
395 }
396 c.mu.Lock()
397 cs := c.live[id]
398 until, wait := connect.LimitedUntil(l.ResetsAt, cs.CoolOff, c.clock())
399 cs.State, cs.ResetsAt, cs.CoolOff, cs.Window = wire.ConnLimited, until, wait, l.Window
400 if l.Headroom != nil {
401 h := c.stamped(l.Headroom)
402 if !h.Fetched && cs.Headroom != nil {
403 h.Unavailable = cs.Headroom.Unavailable
404 }
405 cs.Headroom = h
406 }
407 c.save(id, cs)
408 c.mu.Unlock()
409 if c.Logger != nil {
410 c.Logger.Info("connection limited", "connection", id, "until", until.UTC().Format(time.RFC3339), "reported", !l.ResetsAt.IsZero())
411 }
412 c.changed()
413 return until
414}
415
416// Observe records headroom a provider reported on a run that went on;
417// a connection that answered is no longer limited.
418func (c *Conns) Observe(id string, l connect.Limit, plan string) {
419 if c.load(context.Background()) != nil {
420 return
421 }
422 if l.Limited {
423 c.Limit(id, l)
424 return
425 }
426 c.mu.Lock()
427 cs := c.live[id]
428 was := cs.State
429 read := false
430 if l.Headroom != nil {
431 h := c.stamped(l.Headroom)
432 if !h.Fetched && cs.Headroom != nil {
433 h.Unavailable = cs.Headroom.Unavailable
434 }
435 read = reported(cs.Headroom) != reported(h)
436 cs.Headroom = h
437 }
438 if plan != "" {
439 cs.Plan = plan
440 }
441 if cs.State == wire.ConnLimited || cs.State == "" {
442 cs.State, cs.ResetsAt, cs.CoolOff, cs.Window = wire.ConnHealthy, time.Time{}, 0, ""
443 }
444 c.save(id, cs)
445 c.mu.Unlock()
446 if was != cs.State {
447 c.changed()
448 } else if read && c.Readings != nil {
449 // A new reading: steps the scheduler holds look again.
450 c.Readings()
451 }
452}
453
454// stamped is a reading as taken now: the provider's figures and the
455// time the runner read them (connectors spec rev 3.2 §6), so the age of
456// every reading can be shown. A copy: the caller's is untouched.
457func (c *Conns) stamped(h *wire.Headroom) *wire.Headroom {
458 out := *h
459 out.Windows = slices.Clone(h.Windows)
460 at := c.clock().UTC()
461 out.CheckedAt = &at
462 return &out
463}
464
465// reported is what a reading says, without when it was taken: a reading
466// that says the same again is no new reading for held steps.
467func reported(h *wire.Headroom) string {
468 if h == nil {
469 return ""
470 }
471 v := *h
472 v.CheckedAt = nil
473 raw, _ := json.Marshal(v)
474 return string(raw)
475}
476
477// LimitedFrom is what a switched line says about a connection the
478// provider refused: its provider, the window and the reset it reported.
479func (c *Conns) LimitedFrom(id string) *wire.Switched {
480 b, _ := c.Binding(id)
481 c.mu.Lock()
482 defer c.mu.Unlock()
483 cs := c.live[id]
484 s := &wire.Switched{From: b.Provider, Window: cs.Window}
485 // Only a reset the provider reported is shown, never a cool-off.
486 if cs.CoolOff == 0 && !cs.ResetsAt.IsZero() {
487 at := cs.ResetsAt.UTC()
488 s.ResetsAt = &at
489 }
490 return s
491}
492
493// Held is hello's connection list: every configured connection with how
494// it stands. No path, no secret.
495func (c *Conns) Held() []wire.HeldConnection {
496 out := []wire.HeldConnection{}
497 if c.load(context.Background()) != nil {
498 return out
499 }
500 bs := c.bindings()
501 expiries := c.expiries()
502 emails := c.State.profileEmails()
503 c.mu.Lock()
504 defer c.mu.Unlock()
505 now := c.clock()
506 for _, b := range bs {
507 if b.Kind == wire.KindToken && c.validated[b.ID].IsZero() {
508 // Saved, never validated by a real request: its attempt is
509 // still running (or ends undone); not a connection to show.
510 continue
511 }
512 cs := c.live[b.ID]
513 state := cs.State
514 if state == "" || state == wire.ConnLimited && c.candidate(b).Usable(now) {
515 state = wire.ConnHealthy
516 }
517 kind := b.Kind
518 if kind == "" {
519 kind = wire.KindSubscription
520 }
521 held := wire.HeldConnection{LocalID: b.ID, Person: b.PersonID, Provider: b.Provider, Kind: kind, Label: b.AccountID, State: state, Plan: cs.Plan, Headroom: cs.Headroom}
522 if kind == wire.KindToken {
523 held.Label = profileLabel(b, emails)
524 if at, ok := expiries[b.ID]; ok {
525 // Paste time plus a year: neither the token nor the
526 // pinned CLI (which holds an environment token with no
527 // expiry) says when it really ends.
528 held.ExpiresAt, held.ExpiresEstimated = &at, true
529 }
530 }
531 out = append(out, held)
532 }
533 return append(out, c.heldMetered(now)...)
534}
535
536// heldMetered are the metered connections for hello: each validated one
537// with its facts, budget and spend (a refused key reads sign_in_again).
538func (c *Conns) heldMetered(now time.Time) []wire.HeldConnection {
539 if c.Meter == nil {
540 return nil
541 }
542 ctx := context.Background()
543 conns, err := metered.List(ctx, c.State.db)
544 if err != nil {
545 c.warn("metered connections", err)
546 return nil
547 }
548 var out []wire.HeldConnection
549 for _, m := range conns {
550 if !m.Validated {
551 continue
552 }
553 spend, err := metered.SpendOf(ctx, c.State.db, m, now)
554 if err != nil {
555 c.warn("metered spend", err)
556 continue
557 }
558 state := wire.ConnHealthy
559 if m.Refused {
560 state = wire.ConnSignInAgain
561 }
562 budget := m.Budget
563 // The allowed set it applied, with each model's state (§16.1): a
564 // reconnect sends the set again when this is behind.
565 out = append(out, wire.HeldConnection{LocalID: m.LocalID, Person: m.Person, Provider: m.Provider, Kind: wire.KindAPIKey, State: state, Harness: m.Harness, Upstream: m.Upstream, Billing: m.Billing, Model: m.Model, Budget: &budget, Spend: &spend, Models: heldModels(ctx, c.State.db, m), ModelsRevision: m.ModelsRevision, Choices: heldChoices(ctx, c.State.db, m)})
566 }
567 return out
568}
569
570func (c *Conns) warn(msg string, err error) {
571 if c.Logger != nil {
572 c.Logger.Warn(msg, "err", sanitize(err))
573 }
574}
575
576// setExpiry records when a token connection's token expires, so the
577// date stays the same across restarts.
578func (c *Conns) setExpiry(id string, at time.Time) error {
579 _, err := c.State.db.Exec("INSERT INTO conn_expiry(id, expires_at) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET expires_at=excluded.expires_at", id, at.UTC().Format(time.RFC3339Nano))
580 return err
581}
582
583// forgetExpiry drops a signed-out connection's expiry.
584func (c *Conns) forgetExpiry(id string) {
585 _, err := c.State.db.Exec("DELETE FROM conn_expiry WHERE id=?", id)
586 if err != nil && c.Logger != nil {
587 c.Logger.Warn("connection expiry", "err", sanitize(err))
588 }
589}
590
591// expiries are the recorded token expiries by connection.
592func (c *Conns) expiries() map[string]time.Time {
593 out := map[string]time.Time{}
594 rows, err := c.State.db.Query("SELECT id, expires_at FROM conn_expiry")
595 if err != nil {
596 return out
597 }
598 defer rows.Close()
599 for rows.Next() {
600 var id, at string
601 if rows.Scan(&id, &at) != nil {
602 continue
603 }
604 if t, err := time.Parse(time.RFC3339Nano, at); err == nil {
605 out[id] = t.UTC()
606 }
607 }
608 return out
609}
610
611// Loop refreshes each Claude and Codex home on start and hourly under its
612// lock, with the same CLI-native refresh the runs use: a refresh that
613// fails marks the connection sign_in_again (the provider revoked it) or
614// error; one that succeeds clears both. A token connection gets only the
615// CLI's local status here, which costs nothing and says signed in for
616// any token: it never clears a rejection. Its real check (Verify, one
617// small request) runs at connect and when the person asks (CheckAgain),
618// and any answer on it (Answered) clears sign_in_again too.
619func (c *Conns) Loop(ctx context.Context) {
620 // The first check waits a little so it does not contend with a first
621 // turn (a turn checks a connection it would choose itself).
622 wait := 20 * time.Second
623 for {
624 select {
625 case <-ctx.Done():
626 return
627 case <-time.After(wait):
628 }
629 c.Check(ctx)
630 wait = time.Hour
631 }
632}
633
634// Check refreshes every connection once.
635func (c *Conns) Check(ctx context.Context) {
636 if c.load(ctx) != nil {
637 return
638 }
639 for _, b := range c.bindings() {
640 if b.Provider != "claude" && b.Provider != "codex" {
641 continue
642 }
643 c.checkOne(ctx, b)
644 if ctx.Err() != nil {
645 return
646 }
647 }
648}
649
650// checkOne refreshes one connection with its CLI under the source lock.
651func (c *Conns) checkOne(ctx context.Context, b runner.AccountBinding) {
652 if c.Turn != nil {
653 tctx, give, err := c.Turn(ctx)
654 if err != nil {
655 return
656 }
657 defer give()
658 ctx = tctx
659 }
660 direct, err := c.Runner.DirectBinding(b)
661 if err == nil {
662 var lease *provider.AccountLease
663 refresh := c.Refresh
664 var plan string
665 if b.Provider == wire.ProviderClaude && b.Kind != wire.KindToken && c.ClaudeStatus != nil {
666 refresh = func(ctx context.Context, pb provider.Binding) (provider.Identity, error) {
667 var id provider.Identity
668 var e error
669 id, plan, e = c.ClaudeStatus(ctx, pb)
670 return id, e
671 }
672 }
673 lease, err = provider.OpenRuntimeCopy(ctx, direct, refresh, c.LockWait)
674 if lease != nil {
675 if err == nil && b.Provider == wire.ProviderClaude && b.Kind != wire.KindToken {
676 c.mu.Lock()
677 cs := c.live[b.ID]
678 planChanged := cs.Plan != plan
679 cs.Plan = plan
680 c.save(b.ID, cs)
681 c.mu.Unlock()
682 if planChanged {
683 c.changed()
684 }
685 if c.ClaudeUsage != nil {
686 if token, e := lease.ClaudeOAuthToken(); e == nil {
687 c.readClaudeUsage(ctx, b.ID, token)
688 clear(token)
689 }
690 }
691 }
692 lease.Close()
693 }
694 }
695 if ctx.Err() != nil {
696 return
697 }
698 if b.Kind == wire.KindToken && err == nil {
699 // The CLI's status for a token proves only that it is there: it
700 // never makes a token healthy or validated.
701 return
702 }
703 c.checked(b.ID, err)
704}
705
706// CheckAgain is the person's Check again: the connection's real check
707// (for a token, one small request), which alone can clear a rejection.
708func (c *Conns) CheckAgain(ctx context.Context, id string) {
709 if c.load(ctx) != nil {
710 return
711 }
712 b, ok := c.Binding(id)
713 if !ok {
714 return
715 }
716 if b.Kind == wire.KindToken {
717 c.checkToken(ctx, b)
718 return
719 }
720 c.checkOne(ctx, b)
721}
722
723// Answered records that a run on the connection got an answer from the
724// provider: its credential works, whatever a check said before.
725func (c *Conns) Answered(id string) {
726 if c.load(context.Background()) != nil {
727 return
728 }
729 c.Validated(id)
730}
731
732// Validated records a real request on the connection answered by the
733// provider (a token's check, Check again, or any answered run): durably,
734// then the state it proves.
735func (c *Conns) Validated(id string) {
736 if c.load(context.Background()) != nil {
737 return
738 }
739 at := c.clock().UTC()
740 if _, err := c.State.db.Exec("INSERT INTO conn_validated(id, at) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET at=excluded.at", id, at.Format(time.RFC3339Nano)); err != nil {
741 if c.Logger != nil {
742 c.Logger.Warn("connection validated", "err", sanitize(err))
743 }
744 return
745 }
746 c.mu.Lock()
747 c.validated[id] = at
748 c.mu.Unlock()
749 c.checked(id, nil)
750}
751
752// ValidatedAt is when a real request on the connection was last answered.
753func (c *Conns) ValidatedAt(id string) time.Time {
754 if c.load(context.Background()) != nil {
755 return time.Time{}
756 }
757 c.mu.Lock()
758 defer c.mu.Unlock()
759 return c.validated[id]
760}
761
762// checkToken checks a token connection (a busy home proves nothing).
763func (c *Conns) checkToken(ctx context.Context, b runner.AccountBinding) {
764 if c.Verify == nil {
765 return
766 }
767 err := c.Verify(ctx, b)
768 if ctx.Err() != nil || errors.Is(err, provider.ErrAccountBusy) {
769 return
770 }
771 if err == nil {
772 c.Validated(b.ID)
773 return
774 }
775 c.checked(b.ID, err)
776}
777
778// checked records one refresh's outcome. A refused credential stays so
779// until a check succeeds; any other failure proves nothing about it.
780func (c *Conns) checked(id string, err error) {
781 c.mu.Lock()
782 cs := c.live[id]
783 was := cs.State
784 switch {
785 case err == nil && (cs.State == wire.ConnSignInAgain || cs.State == wire.ConnError || cs.State == ""):
786 cs.State = wire.ConnHealthy
787 case errors.Is(err, provider.ErrAccountBusy) && cs.State == "":
788 // Another process holds the home's lock for its own refresh: the
789 // account is in use, so it is signed in.
790 cs.State = wire.ConnHealthy
791 case errors.Is(err, provider.ErrLoginRequired):
792 cs.State = wire.ConnSignInAgain
793 case err != nil && !errors.Is(err, provider.ErrAccountBusy) && cs.State != wire.ConnSignInAgain:
794 cs.State = wire.ConnError
795 }
796 if cs.State != was {
797 c.save(id, cs)
798 }
799 c.mu.Unlock()
800 if cs.State != was {
801 if c.Logger != nil {
802 c.Logger.Info("connection checked", "connection", id, "state", cs.State)
803 }
804 c.changed()
805 }
806}
807
808// SignInAgain records a provider's refusal of a connection's credential.
809func (c *Conns) SignInAgain(id string) {
810 if c.load(context.Background()) != nil {
811 return
812 }
813 c.checked(id, provider.ErrLoginRequired)
814}
815
816// Forget drops a connection's state (it was signed out or never finished).
817func (c *Conns) Forget(id string) {
818 c.mu.Lock()
819 defer c.mu.Unlock()
820 delete(c.live, id)
821 if c.validated != nil {
822 delete(c.validated, id)
823 }
824 _, _ = c.State.db.Exec("DELETE FROM conn_state WHERE id=?", id)
825 _, _ = c.State.db.Exec("DELETE FROM conn_validated WHERE id=?", id)
826 _, _ = c.State.db.Exec("DELETE FROM conn_profile WHERE id=?", id)
827 _, _ = c.State.db.Exec("DELETE FROM conn_usage WHERE id=?", id)
828}
829