oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "encoding/base64"
6 "encoding/json"
7 "errors"
8 "slices"
9 "strings"
10 "time"
11 "unicode"
12 "unicode/utf8"
13
14 "amadan.net/oficina/equipo/internal/wire"
15 "gorm.io/gorm"
16 "gorm.io/gorm/clause"
17)
18
19// Connections (Equipo Connections spec §§2, 7, slice 1): the instance
20// keeps a record of each of a person's connections and never a secret.
21// A record comes from the runner's hello (what it holds) or from a
22// connection attempt the person started here.
23
24// ErrRunnerOffline: a connection attempt needs the person's runner.
25var ErrRunnerOffline = errors.New("runner offline")
26
27// connectionAttemptLimit ends an attempt that made no progress (the
28// device code itself expires after fifteen minutes).
29const connectionAttemptLimit = 15 * time.Minute
30
31// headroomEvery throttles events for headroom-only changes.
32const headroomEvery = time.Minute
33
34type connectionRecord struct {
35 ID string `gorm:"primaryKey"`
36 Person string `gorm:"index:chat_connection_person"`
37 RunnerID string
38 LocalID string
39 Provider string
40 Kind string
41 Label string
42 State string
43 Reason string
44 Plan string
45 Headroom string
46 Prompt string
47 Revision int64
48 CreatedAt time.Time
49 UpdatedAt time.Time
50 // ExpiresAt is when a pasted token expires, as the runner reports it;
51 // ExpiresEstimated says the date is an estimate.
52 ExpiresAt *time.Time
53 ExpiresEstimated bool
54 // StatedEmail is the account email the person typed for a token
55 // connection, kept apart from Label (what the provider said): shown
56 // beside the row as theirs, never matched, deduplicated or routed on,
57 // and never sent to the runner.
58 StatedEmail string
59 // An API-key connection (connectors spec S1): its harness, origin,
60 // billing and model; when the person confirmed the provider-side
61 // limit and, for an overflow subscription, pay-as-you-go off; the
62 // budget the person set (JSON wire.Budget) and the highest revision
63 // the runner applied; its spend as the runner last reported it (JSON
64 // wire.Spend).
65 Harness string
66 Upstream string
67 Billing string
68 Model string
69 LimitConfirmedAt *time.Time
70 PaygOffConfirmedAt *time.Time
71 Budget string
72 BudgetApplied int64
73 Spend string
74 // The allowed set (connectors spec rev 3.3 §16.1): the person's
75 // latest set (JSON list) at ModelsRevision, the highest revision the
76 // runner applied, each allowed model's state there (JSON
77 // []wire.ModelState) and every model the key listed when the runner
78 // last read it (JSON []wire.ModelChoice).
79 Models string
80 ModelsRevision int64
81 ModelsApplied int64
82 ModelsState string
83 ModelsListed string
84}
85
86func (connectionRecord) TableName() string { return "chat_connections" }
87
88// usageRecord is one turn's, step attempt's or answer's token use, as the
89// runner reported it from the harness (spec §6, recorded from day one).
90type usageRecord struct {
91 ID int64 `gorm:"primaryKey"`
92 Person string `gorm:"index:chat_usage_person,priority:1"`
93 // RunnerID is the runner that reported the row: a connection is its
94 // runner and local id (local ids repeat across runners). Rows before
95 // slice F, and rows below 37, name none (NULL): the main runner's.
96 RunnerID *string
97 Connection string `gorm:"uniqueIndex:chat_usage_key,priority:4"`
98 Provider string
99 Model string `gorm:"uniqueIndex:chat_usage_key,priority:5"`
100 Role string
101 TaskID string
102 // StepID is a step's, a question's or a health check's; TurnID a
103 // coordinator turn's.
104 StepID string `gorm:"uniqueIndex:chat_usage_key,priority:2"`
105 TurnID string `gorm:"uniqueIndex:chat_usage_key,priority:1"`
106 Attempt int64 `gorm:"uniqueIndex:chat_usage_key,priority:3"`
107 Outcome string
108 Complete bool
109 // Round is the fix round of the step (or of the step a question
110 // asked): 0 for the first, and for coordinator turns and checks.
111 // Turns is how many model requests the attempt made (null: unknown).
112 Round int
113 Turns *int64
114 // Overcount: a Claude coordinator turn's or answer's row from a runner
115 // before ProtocolSpend, which read the session's running total
116 // (modelUsage) as the turn's own. It is at most what was used, often
117 // more; sums leave it out and say so.
118 Overcount bool
119 // A metered connection's charge: the cost the runner priced (null
120 // when it could not), its currency and price table version, and the
121 // cost the harness reported itself.
122 CostMicros *int64
123 Currency string
124 PriceVersion string
125 CostReportedMicros *int64
126 // The row's model's family and tier under the runner's tier table, the
127 // table's version, and whether the provider reported another model
128 // than the one Equipo chose (§16.5).
129 Family string
130 Tier string
131 TierVersion string
132 ModelMismatch bool
133 // Figures the harness did not report stay null, never zero.
134 InputTokens *int64
135 CachedInputTokens *int64
136 CacheWriteTokens *int64
137 OutputTokens *int64
138 ReasoningOutputTokens *int64
139 RecordedAt time.Time `gorm:"index:chat_usage_person,priority:2"`
140}
141
142func (usageRecord) TableName() string { return "chat_usage" }
143
144func connectionView(r connectionRecord) wire.Connection {
145 v := wire.Connection{ID: r.ID, Revision: r.Revision, RunnerID: r.RunnerID, LocalID: r.LocalID, Provider: r.Provider, Kind: r.Kind, Label: r.Label, State: r.State, Reason: r.Reason, Plan: r.Plan, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, ExpiresAt: r.ExpiresAt, ExpiresEstimated: r.ExpiresEstimated}
146 if r.Headroom != "" {
147 v.Headroom = &wire.Headroom{}
148 if json.Unmarshal([]byte(r.Headroom), v.Headroom) != nil {
149 v.Headroom = nil
150 }
151 }
152 if r.Prompt != "" && r.State == wire.ConnConnecting {
153 v.Prompt = &wire.ConnectPrompt{}
154 if json.Unmarshal([]byte(r.Prompt), v.Prompt) != nil {
155 v.Prompt = nil
156 }
157 }
158 if r.Kind == wire.KindAPIKey {
159 v.Harness, v.Upstream, v.Billing, v.Model, v.LimitConfirmedAt, v.PaygOffConfirmedAt = r.Harness, r.Upstream, r.Billing, r.Model, r.LimitConfirmedAt, r.PaygOffConfirmedAt
160 if b, ok := budgetOf(r); ok {
161 // The budget a connection was made with rides its connect
162 // frame; a change after is pending until the runner applies it.
163 v.Budget, v.BudgetPending = &b, b.Revision > r.BudgetApplied && r.State != wire.ConnConnecting
164 }
165 if r.Spend != "" {
166 v.Spend = &wire.Spend{}
167 if json.Unmarshal([]byte(r.Spend), v.Spend) != nil {
168 v.Spend = nil
169 }
170 }
171 if r.State != wire.ConnConnecting {
172 // While it connects the card lists the key's models.
173 v.Models, v.ModelsRevision = modelsView(r), r.ModelsRevision
174 v.ModelsPending = r.ModelsRevision > r.ModelsApplied
175 }
176 }
177 return v
178}
179
180// modelsView is a metered connection's models for its page (§16.1):
181// every model the key listed and every model allowed or applied, each
182// with whether it can be allowed, whether the person allows it (the
183// latest set), whether the runner applied that, and its state there.
184func modelsView(r connectionRecord) []wire.ConnectionModel {
185 allowed := modelsOf(r)
186 var listed []wire.ModelChoice
187 var states []wire.ModelState
188 _ = json.Unmarshal([]byte(firstSet(r.ModelsListed, "null")), &listed)
189 _ = json.Unmarshal([]byte(firstSet(r.ModelsState, "null")), &states)
190 by := map[string]*wire.ConnectionModel{}
191 get := func(id string) *wire.ConnectionModel {
192 if m, ok := by[id]; ok {
193 return m
194 }
195 m := &wire.ConnectionModel{ID: id}
196 by[id] = m
197 return m
198 }
199 for _, c := range listed {
200 m := get(c.ID)
201 m.Eligible, m.Family, m.Tier = c.Eligible, c.Family, c.Tier
202 }
203 for _, s := range states {
204 m := get(s.ID)
205 m.Applied, m.State, m.Reason, m.FailedAt = true, s.State, s.Reason, s.FailedAt
206 m.Family, m.Tier = firstSet(m.Family, s.Family), firstSet(m.Tier, s.Tier)
207 if len(listed) == 0 {
208 // Listed before the runner kept the key's list: what it runs is
209 // what can be allowed, until Check again reads the list.
210 m.Eligible = s.Family != "" && s.Tier != ""
211 }
212 }
213 for _, id := range allowed {
214 m := get(id)
215 m.Allowed = true
216 if len(listed) == 0 && len(states) == 0 {
217 // Nothing reported yet: the set the person sent was checked
218 // against the key's list when it was made.
219 m.Eligible = true
220 }
221 }
222 if len(by) == 0 {
223 return nil
224 }
225 out := make([]wire.ConnectionModel, 0, len(by))
226 for _, m := range by {
227 out = append(out, *m)
228 }
229 slices.SortFunc(out, func(a, b wire.ConnectionModel) int { return strings.Compare(a.ID, b.ID) })
230 return out
231}
232
233// modelsOf is the person's latest allowed set.
234func modelsOf(r connectionRecord) []string {
235 var out []string
236 if r.Models == "" || json.Unmarshal([]byte(r.Models), &out) != nil {
237 return nil
238 }
239 return out
240}
241
242// budgetOf is the budget the person set on a metered connection.
243func budgetOf(r connectionRecord) (wire.Budget, bool) {
244 var b wire.Budget
245 if r.Budget == "" || json.Unmarshal([]byte(r.Budget), &b) != nil {
246 return b, false
247 }
248 return b, true
249}
250
251func asJSON(v any) string {
252 if v == nil {
253 return ""
254 }
255 raw, _ := json.Marshal(v)
256 if string(raw) == "null" {
257 return ""
258 }
259 return string(raw)
260}
261
262// saveConnection writes a connection and its event in the transaction.
263func (t *txn) saveConnection(r *connectionRecord, fresh bool) error {
264 r.Revision++
265 r.UpdatedAt = t.now()
266 var err error
267 if fresh {
268 r.CreatedAt = r.UpdatedAt
269 err = t.db.Create(r).Error
270 } else {
271 err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("kind", "local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at", "expires_at", "expires_estimated", "harness", "upstream", "billing", "model", "budget", "budget_applied", "spend", "models", "models_revision", "models_applied", "models_state", "models_listed").Updates(r).Error
272 }
273 if err != nil {
274 return err
275 }
276 return t.event("", r.Person, wire.EventConnection, "connection", r.ID, r.Revision, "", "", 0, connectionView(*r))
277}
278
279func (t *txn) connections(person string) ([]connectionRecord, error) {
280 var rows []connectionRecord
281 err := t.db.Where("person = ?", person).Order("created_at, id").Find(&rows).Error
282 return rows, err
283}
284
285// helloConnections records what the person's runner holds: new
286// connections appear, changed ones update (headroom at most once a
287// minute), and, when the report is complete, one the runner no longer
288// holds is signed out. A teammate's connection in the same hello is
289// never recorded for this person: only the runner's own person's.
290func (t *txn) helloConnections(l Lease, held []wire.HeldConnection, complete bool) error {
291 person, runner := l.Runner.Person, l.Runner.RunnerID
292 rows, err := t.connections(person)
293 if err != nil {
294 return err
295 }
296 // The preference goes again with every hello, to the runner that
297 // said it: a runner with a fresh state learns it, one that has it
298 // ignores the same revision. A worker hears it only while it holds
299 // one of the person's connections.
300 mine := l.Role != wire.RoleWorker || len(held) > 0 || slices.ContainsFunc(rows, func(r connectionRecord) bool { return r.RunnerID == runner && r.State != wire.ConnSignedOut })
301 if value, _, revision, err := t.settingRevision(preferenceKey(person)); err != nil {
302 return err
303 } else if revision > 0 && mine {
304 if err := t.commandTo(runner, person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: value, Revision: revision}); err != nil {
305 return err
306 }
307 }
308 byLocal := map[string]int{}
309 for i, r := range rows {
310 if r.RunnerID == runner && r.LocalID != "" {
311 byLocal[r.LocalID] = i
312 }
313 }
314 seen := map[string]bool{}
315 for _, h := range held {
316 if h.Person != person || h.LocalID == "" || !slices.Contains([]string{wire.ConnHealthy, wire.ConnLimited, wire.ConnSignInAgain, wire.ConnError}, h.State) {
317 continue
318 }
319 seen[h.LocalID] = true
320 headroom := asJSON(h.Headroom)
321 i, ok := byLocal[h.LocalID]
322 if !ok {
323 // An attempt that just finished reports this connection itself.
324 if slices.ContainsFunc(rows, func(r connectionRecord) bool {
325 return r.RunnerID == runner && r.State == wire.ConnConnecting && r.Provider == h.Provider
326 }) {
327 continue
328 }
329 r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner, LocalID: h.LocalID, Provider: h.Provider, Kind: h.Kind, Label: h.Label, State: h.State, Plan: h.Plan, Headroom: headroom, ExpiresAt: h.ExpiresAt, ExpiresEstimated: h.ExpiresEstimated}
330 heldMetered(&r, h)
331 if err := t.saveConnection(&r, true); err != nil {
332 return err
333 }
334 continue
335 }
336 r := rows[i]
337 was := r
338 heldMetered(&r, h)
339 changed := r.State != h.State || r.Label != h.Label || r.Plan != h.Plan || r.Reason != "" || !sameTime(r.ExpiresAt, h.ExpiresAt) || r.ExpiresEstimated != h.ExpiresEstimated || r.Spend != was.Spend || r.Model != was.Model || r.BudgetApplied != was.BudgetApplied || r.Budget != was.Budget || r.Models != was.Models || r.ModelsApplied != was.ModelsApplied || r.ModelsState != was.ModelsState || r.ModelsListed != was.ModelsListed
340 if h.Kind == wire.KindAPIKey && l.Protocol >= wire.ProtocolModels && h.ModelsRevision < r.ModelsRevision {
341 // The runner is behind the person's set (a frame it had not
342 // applied when it went away): sent again (§16.1).
343 if err := t.commandTo(runner, person, wire.FrameModels, wire.ModelsCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, Allowed: modelsOf(r), Revision: r.ModelsRevision}); err != nil {
344 return err
345 }
346 }
347 if !changed && r.Headroom == headroom {
348 continue
349 }
350 if !changed && t.now().Sub(r.UpdatedAt) < headroomEvery {
351 continue
352 }
353 r.State, r.Label, r.Plan, r.Headroom, r.Reason, r.Prompt, r.ExpiresAt, r.ExpiresEstimated = h.State, h.Label, h.Plan, headroom, "", "", h.ExpiresAt, h.ExpiresEstimated
354 if err := t.saveConnection(&r, false); err != nil {
355 return err
356 }
357 }
358 for _, r := range rows {
359 // Only a complete report says a connection is gone.
360 if complete && r.RunnerID == runner && r.LocalID != "" && !seen[r.LocalID] && r.State != wire.ConnSignedOut && r.State != wire.ConnConnecting {
361 r.State, r.Headroom = wire.ConnSignedOut, ""
362 if err := t.saveConnection(&r, false); err != nil {
363 return err
364 }
365 }
366 }
367 return nil
368}
369
370// heldMetered copies an API-key connection's facts from the runner's
371// hello: what it reports is what it holds. The person's budget is kept
372// as they set it; the runner's revision says how far it applied.
373func heldMetered(r *connectionRecord, h wire.HeldConnection) {
374 if h.Kind != wire.KindAPIKey {
375 return
376 }
377 r.Harness, r.Upstream, r.Billing, r.Model, r.Spend = h.Harness, h.Upstream, h.Billing, h.Model, asJSON(h.Spend)
378 if h.Budget != nil {
379 if r.Budget == "" {
380 r.Budget = asJSON(h.Budget)
381 }
382 r.BudgetApplied = max(r.BudgetApplied, h.Budget.Revision)
383 }
384 // The set the runner applied and each model's state there; an older
385 // runner reports none and keeps its one model.
386 if h.Models != nil && len(h.Models) <= wire.MaxModels {
387 // The runner's word is the applied set: never maxed with an ack or
388 // an earlier hello, so a set it refused never shows applied.
389 r.ModelsApplied, r.ModelsState = h.ModelsRevision, asJSON(h.Models)
390 if r.Models == "" {
391 ids := make([]string, 0, len(h.Models))
392 for _, m := range h.Models {
393 ids = append(ids, m.ID)
394 }
395 r.Models, r.ModelsRevision = asJSON(ids), max(r.ModelsRevision, h.ModelsRevision)
396 }
397 }
398 if h.Choices != nil && validChoices(h.Choices) {
399 r.ModelsListed = asJSON(h.Choices)
400 }
401}
402
403// validChoices bounds a key's list as the runner reports it: at most
404// wire.MaxModels, each a model id within bounds, a short family and a
405// known tier word.
406func validChoices(cs []wire.ModelChoice) bool {
407 return len(cs) <= wire.MaxModels && !slices.ContainsFunc(cs, func(c wire.ModelChoice) bool {
408 return c.ID == "" || len(c.ID) > wire.MaxModelName || len(c.Family) > 64 || !slices.Contains([]string{"", "strong", "standard", "cheap"}, c.Tier)
409 })
410}
411
412// connectionReport applies the runner's word on one of its person's
413// connection attempts.
414func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error {
415 if l.Role == wire.RoleWorker && l.Protocol < wire.ProtocolMacEngineering {
416 // A worker below 37 holds no connection: what it replays is not
417 // applied.
418 return ErrRefused
419 }
420 if !wire.ConnectReasons[v.Reason] || !slices.Contains([]string{wire.ConnConnecting, wire.ConnHealthy, wire.ConnError, wire.ConnLimited, wire.ConnSignedOut}, v.State) {
421 return ErrInvalid
422 }
423 var r connectionRecord
424 err := t.db.Where("id = ? AND person = ? AND runner_id = ?", v.Connection, l.Runner.Person, l.Runner.RunnerID).First(&r).Error
425 if errors.Is(err, gorm.ErrRecordNotFound) {
426 return nil
427 }
428 if err != nil {
429 return err
430 }
431 if v.State == wire.ConnSignedOut {
432 // Signed out on the runner: its home and binding are gone.
433 if r.State == wire.ConnSignedOut {
434 return nil
435 }
436 r.State, r.Reason, r.Prompt, r.Headroom = wire.ConnSignedOut, "", "", ""
437 return t.saveConnection(&r, false)
438 }
439 // An attempt that ended stays ended: a late frame changes nothing.
440 if r.State != wire.ConnConnecting {
441 return nil
442 }
443 if v.State == wire.ConnHealthy && signingIn(r) {
444 // Claude's sign-in by the runner's setup-token made a token
445 // connection.
446 r.Kind = wire.KindToken
447 }
448 r.State, r.Reason = v.State, v.Reason
449 if v.Label != "" {
450 r.Label = v.Label
451 }
452 if v.Plan != "" {
453 r.Plan = v.Plan
454 }
455 if v.Headroom != nil {
456 r.Headroom = asJSON(v.Headroom)
457 }
458 if v.Prompt != nil {
459 if len(v.Prompt.Models) > wire.MaxModels || slices.ContainsFunc(v.Prompt.Models, func(m string) bool { return m == "" || len(m) > wire.MaxModelName }) {
460 return ErrInvalid
461 }
462 if !validChoices(v.Prompt.Choices) {
463 return ErrInvalid
464 }
465 r.Prompt = asJSON(v.Prompt)
466 if v.Prompt.Choices != nil {
467 // The key's list, kept for the row once the card is gone.
468 r.ModelsListed = asJSON(v.Prompt.Choices)
469 }
470 }
471 if v.State != wire.ConnConnecting {
472 r.Prompt = ""
473 }
474 if v.State == wire.ConnHealthy && r.Kind == wire.KindAPIKey {
475 // Made with the budget its connect frame carried, and the set its
476 // models card sent.
477 if b, ok := budgetOf(r); ok {
478 r.BudgetApplied = max(r.BudgetApplied, b.Revision)
479 }
480 r.ModelsApplied = max(r.ModelsApplied, r.ModelsRevision)
481 }
482 if v.State == wire.ConnHealthy && r.Kind == wire.KindToken && r.ExpiresAt == nil {
483 // An estimate until the runner's hello says what it knows: a
484 // setup token lasts about a year from when it was made.
485 at := t.now().Add(wire.TokenLifetime)
486 r.ExpiresAt, r.ExpiresEstimated = &at, true
487 }
488 if v.LocalID != "" && v.State != wire.ConnError {
489 // The hello may have recorded the new connection first.
490 if err := t.db.Where("person = ? AND runner_id = ? AND local_id = ? AND id <> ?", r.Person, r.RunnerID, v.LocalID, r.ID).Delete(&connectionRecord{}).Error; err != nil {
491 return err
492 }
493 r.LocalID = v.LocalID
494 // Connect again: the same account, signed out before, is this one
495 // now; its old record goes.
496 if r.Label != "" {
497 if err := t.forgetSignedOut(r.Person, r.RunnerID, r.Provider, r.Label, r.ID); err != nil {
498 return err
499 }
500 }
501 }
502 return t.saveConnection(&r, false)
503}
504
505// promptOf is a record's prompt (nil: none).
506func promptOf(r connectionRecord) *wire.ConnectPrompt {
507 if r.Prompt == "" {
508 return nil
509 }
510 var p wire.ConnectPrompt
511 if json.Unmarshal([]byte(r.Prompt), &p) != nil {
512 return nil
513 }
514 return &p
515}
516
517// signingIn says a connecting record is Claude's sign-in by the runner's
518// own setup-token (wire.PromptAuthorize), whose prompt it keeps until it
519// ends.
520func signingIn(r connectionRecord) bool {
521 p := promptOf(r)
522 return r.Provider == wire.ProviderClaude && r.Kind == wire.KindSubscription && p != nil && p.Kind == wire.PromptAuthorize
523}
524
525// forgetSignedOut removes the person's signed-out records of one account
526// (provider and label) on one runner, except keep, each with its last
527// event. The same account on another machine is another connection.
528func (t *txn) forgetSignedOut(person, runner, provider, label, keep string) error {
529 var rows []connectionRecord
530 if err := t.db.Where("person = ? AND runner_id = ? AND provider = ? AND label = ? AND state = ? AND id <> ?", person, runner, provider, label, wire.ConnSignedOut, keep).Find(&rows).Error; err != nil {
531 return err
532 }
533 for i := range rows {
534 if err := t.forget(&rows[i]); err != nil {
535 return err
536 }
537 }
538 return nil
539}
540
541// forget deletes a record the runner no longer holds; its event says
542// forgotten so every client drops it.
543func (t *txn) forget(r *connectionRecord) error {
544 if err := t.db.Delete(&connectionRecord{}, "id = ?", r.ID).Error; err != nil {
545 return err
546 }
547 r.Revision++
548 r.State, r.UpdatedAt = wire.ConnForgotten, t.now()
549 return t.event("", r.Person, wire.EventConnection, "connection", r.ID, r.Revision, "", "", 0, connectionView(*r))
550}
551
552// Forget removes one of the person's connections that is signed out, or
553// an attempt that ended: the record only, the runner holds nothing of it.
554func (s *Store) Forget(ctx context.Context, person, id string) error {
555 return s.tx(ctx, func(t *txn) error {
556 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
557 return err
558 }
559 var r connectionRecord
560 if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
561 return ErrNotFound
562 } else if err != nil {
563 return err
564 }
565 if r.State != wire.ConnSignedOut && !(r.State == wire.ConnError && r.LocalID == "") {
566 return ErrConflict
567 }
568 return t.forget(&r)
569 })
570}
571
572// preferenceKey is the person's preferred provider in chat_settings
573// ("" is Automatic).
574func preferenceKey(person string) string { return "prefer:" + person }
575
576// preferenceUntilKey holds when the person's preference ends by itself
577// (RFC 3339, "" for no end).
578func preferenceUntilKey(person string) string { return "prefer_until:" + person }
579
580// preferenceOf is the stored preference at now: one whose end has passed
581// is Automatic (connectors spec §7).
582func (t *txn) preferenceOf(person string) (wire.Preferences, error) {
583 value, _, revision, err := t.settingRevision(preferenceKey(person))
584 if err != nil {
585 return wire.Preferences{}, err
586 }
587 out := wire.Preferences{Provider: value, Revision: revision}
588 until, _, _, err := t.settingRevision(preferenceUntilKey(person))
589 if err != nil {
590 return out, err
591 }
592 if at, perr := time.Parse(time.RFC3339, until); until != "" && perr == nil {
593 if !t.now().Before(at) {
594 out.Provider = ""
595 } else {
596 out.Until = &at
597 }
598 }
599 return out, nil
600}
601
602// Preference reads the person's preference.
603func (s *Store) Preference(ctx context.Context, person string) (out wire.Preferences, err error) {
604 err = s.read(ctx, func(tx *gorm.DB) error {
605 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
606 return err
607 }
608 out, err = (&txn{s: s, db: tx}).preferenceOf(person)
609 return err
610 })
611 return out, err
612}
613
614// SetPreference records the person's preference against the revision
615// they saw (ErrConflict when it moved) and tells their runner, so its
616// choice has it offline. The same preference again changes nothing. One
617// with an end (Until) ends by itself; a runner too old to know an end is
618// refused one rather than keeping it for ever.
619func (s *Store) SetPreference(ctx context.Context, person string, in wire.Preferences) (out wire.Preferences, err error) {
620 if !wire.PreferenceProviders[in.Provider] || in.Until != nil && in.Provider == "" {
621 return out, ErrInvalid
622 }
623 err = s.tx(ctx, func(t *txn) error {
624 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
625 return err
626 }
627 out, err = t.setPreference(person, in)
628 return err
629 })
630 return out, err
631}
632
633// setPreference is SetPreference in t (advice's Prefer acts through it).
634func (t *txn) setPreference(person string, in wire.Preferences) (out wire.Preferences, err error) {
635 value, _, revision, err := t.settingRevision(preferenceKey(person))
636 if err != nil {
637 return out, err
638 }
639 if in.Revision != revision {
640 return out, ErrConflict
641 }
642 until := ""
643 if in.Until != nil {
644 at := in.Until.UTC().Truncate(time.Second)
645 if !at.After(t.now()) || at.Sub(t.now()) > wire.MaxByAhead {
646 return out, ErrInvalid
647 }
648 primary, err := t.s.authority.PrimaryRunner(t.db, person)
649 if err != nil {
650 return out, err
651 }
652 if proto, err := t.runnerProtocol(person, primary); err != nil {
653 return out, err
654 } else if proto < wire.ProtocolScheduler {
655 return out, ErrRunnerTooOld
656 }
657 in.Until, until = &at, at.Format(time.RFC3339)
658 }
659 held, _, _, err := t.settingRevision(preferenceUntilKey(person))
660 if err != nil {
661 return out, err
662 }
663 if value == in.Provider && held == until && revision > 0 {
664 out, err = t.preferenceOf(person)
665 return out, err
666 }
667 if revision, err = t.setSetting(preferenceKey(person), in.Provider, person); err != nil {
668 return out, err
669 }
670 if held != until {
671 if _, err = t.setSetting(preferenceUntilKey(person), until, person); err != nil {
672 return out, err
673 }
674 }
675 out = wire.Preferences{Provider: in.Provider, Revision: revision, Until: in.Until}
676 if err := t.event("", person, wire.EventPreference, "preference", person, revision, "", "", 0, out); err != nil {
677 return out, err
678 }
679 runners, err := t.preferenceRunners(person)
680 if err != nil {
681 return out, err
682 }
683 for _, runner := range runners {
684 if err := t.commandTo(runner, person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: in.Provider, Revision: revision, Until: in.Until}); err != nil {
685 return out, err
686 }
687 }
688 return out, nil
689}
690
691// Connections lists the person's own connections, every runner.
692func (s *Store) Connections(ctx context.Context, person string) (out []wire.Connection, err error) {
693 out = []wire.Connection{}
694 err = s.read(ctx, func(tx *gorm.DB) error {
695 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
696 return err
697 }
698 t := &txn{s: s, db: tx}
699 rows, err := t.connections(person)
700 if err != nil {
701 return err
702 }
703 out, err = t.connectionViews(person, rows)
704 return err
705 })
706 return out, err
707}
708
709// connectionViews are the person's connections as the API and pages
710// show them: a metered one on a runner below ProtocolModels says it
711// cannot change its set (§16.1).
712func (t *txn) connectionViews(person string, rows []connectionRecord) ([]wire.Connection, error) {
713 out := make([]wire.Connection, 0, len(rows))
714 protocols := map[string]int{}
715 for _, r := range rows {
716 v := connectionView(r)
717 if r.Kind == wire.KindAPIKey && r.LocalID != "" && r.State != wire.ConnSignedOut {
718 proto, ok := protocols[r.RunnerID]
719 if !ok {
720 var err error
721 if proto, err = t.runnerProtocol(person, r.RunnerID); err != nil {
722 return nil, err
723 }
724 protocols[r.RunnerID] = proto
725 }
726 v.ModelsTooOld = proto < wire.ProtocolModels
727 }
728 out = append(out, v)
729 }
730 return out, nil
731}
732
733// Connection reads one of the person's connections.
734func (s *Store) Connection(ctx context.Context, person, id string) (out wire.Connection, err error) {
735 err = s.read(ctx, func(tx *gorm.DB) error {
736 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
737 return err
738 }
739 var r connectionRecord
740 if err := tx.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
741 return ErrNotFound
742 } else if err != nil {
743 return err
744 }
745 views, err := (&txn{s: s, db: tx}).connectionViews(person, []connectionRecord{r})
746 if err != nil {
747 return err
748 }
749 out = views[0]
750 return nil
751 })
752 return out, err
753}
754
755// StartConnection starts a connection attempt on the person's runner (spec §2.1):
756// a Codex account by device code; a Claude account by the runner's own
757// `claude setup-token`, whose sign-in code the page seals to the runner
758// (wire.PromptAuthorize, SendSecret); or a Claude account from a pasted
759// setup token (kind token), sealed the same way. The sign-in finished at
760// the runner's machine (same_machine) is gone and refused. Nothing the instance
761// can read passes through it either way. A second attempt for the same
762// provider while one is connecting returns that one.
763func (s *Store) StartConnection(ctx context.Context, person string, in wire.Connect) (out wire.Connection, err error) {
764 if in.Kind == wire.KindAPIKey {
765 return s.startAPIKey(ctx, person, in)
766 }
767 token := in.Kind == wire.KindToken
768 if in.Provider != wire.ProviderClaude && in.Provider != wire.ProviderCodex || in.Kind != "" && in.Kind != wire.KindSubscription && !token || token && in.Provider != wire.ProviderClaude || in.SameMachine || in.LimitConfirmed || in.PaygOffConfirmed || in.Budget != nil {
769 return out, ErrInvalid
770 }
771 err = s.tx(ctx, func(t *txn) error {
772 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
773 return err
774 }
775 runner, err := s.runnerView(t.db, person)
776 if err != nil {
777 return err
778 }
779 if runner.ID == "" {
780 return ErrNotFound
781 }
782 onMac := in.RunnerID != "" && in.RunnerID != runner.ID
783 if onMac {
784 // Claude on one of the person's Macs (slice F): a pasted token
785 // or the Mac's own sign-in, sealed to that Mac's key.
786 m, found, err := t.connectionMachine(person, in.RunnerID)
787 if err != nil {
788 return err
789 }
790 if !found {
791 return ErrNotFound
792 }
793 if !TakesClaude(m) || in.Provider != wire.ProviderClaude {
794 return ErrInvalid
795 }
796 runner = wire.Runner{ID: m.ID, Online: m.Online, SealKey: m.SealKey}
797 }
798 rows, err := t.connections(person)
799 if err != nil {
800 return err
801 }
802 for _, r := range rows {
803 if r.State == wire.ConnConnecting && r.Provider == in.Provider && r.RunnerID == runner.ID {
804 out = connectionView(r)
805 return nil
806 }
807 }
808 if !runner.Online {
809 return ErrRunnerOffline
810 }
811 r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner.ID, Provider: in.Provider, Kind: wire.KindSubscription, State: wire.ConnConnecting}
812 if token {
813 // The token card: run the command anywhere, approve, paste.
814 r.Kind, r.Prompt = wire.KindToken, asJSON(wire.ConnectPrompt{Kind: wire.PromptToken, Code: "claude setup-token"})
815 } else if in.Provider == wire.ProviderClaude {
816 // Claude with no terminal: the runner starts setup-token and
817 // reports its link; until then the card says it is starting.
818 r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptAuthorize})
819 }
820 if err := t.saveConnection(&r, true); err != nil {
821 return err
822 }
823 if onMac {
824 // The Mac holds a model credential from now (D1) until it says
825 // everything of one is gone.
826 if err := t.holdCredential(r.RunnerID); err != nil {
827 return err
828 }
829 }
830 if err := t.audit(person, "connection.start", r.ID+"@"+r.RunnerID); err != nil {
831 return err
832 }
833 out = connectionView(r)
834 return t.commandTo(r.RunnerID, person, wire.FrameConnect, wire.ConnectCommand{Connection: r.ID, Person: person, Provider: r.Provider, Kind: r.Kind, SameMachine: in.SameMachine})
835 })
836 return out, err
837}
838
839// CancelConnection ends the person's connection attempt.
840func (s *Store) CancelConnection(ctx context.Context, person, id string) (out wire.Connection, err error) {
841 err = s.tx(ctx, func(t *txn) error {
842 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
843 return err
844 }
845 var r connectionRecord
846 if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
847 return ErrNotFound
848 } else if err != nil {
849 return err
850 }
851 if r.State != wire.ConnConnecting {
852 out = connectionView(r)
853 return nil
854 }
855 r.State, r.Reason, r.Prompt = wire.ConnError, "cancelled", ""
856 if err := t.saveConnection(&r, false); err != nil {
857 return err
858 }
859 if err := t.dropSecret(r.ID); err != nil {
860 return err
861 }
862 out = connectionView(r)
863 runner, err := t.connectionRunner(r)
864 if err != nil {
865 return err
866 }
867 if err := t.audit(person, "connection.cancel", r.ID+"@"+runner); err != nil {
868 return err
869 }
870 return t.commandTo(runner, person, wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: r.ID, Person: person})
871 })
872 return out, err
873}
874
875// SignOut signs one of the person's connections out (DELETE
876// /api/v1/connections/{id}): the runner runs the harness's own logout,
877// deletes the home and reports signed_out. An attempt still connecting
878// is cancelled instead.
879// CheckConnection is the person's Check again on a connection the runner
880// holds: its real check runs there (for a token, one small request).
881func (s *Store) CheckConnection(ctx context.Context, person, id string) error {
882 return s.tx(ctx, func(t *txn) error {
883 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
884 return err
885 }
886 var r connectionRecord
887 if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
888 return ErrNotFound
889 } else if err != nil {
890 return err
891 }
892 if r.LocalID == "" || r.State == wire.ConnSignedOut || r.State == wire.ConnConnecting {
893 return ErrConflict
894 }
895 return t.commandTo(r.RunnerID, person, wire.FrameCheck, wire.CheckCommand{Connection: r.ID, Person: person, LocalID: r.LocalID})
896 })
897}
898
899func (s *Store) SignOut(ctx context.Context, person, id string) (out wire.Connection, err error) {
900 err = s.tx(ctx, func(t *txn) error {
901 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
902 return err
903 }
904 var r connectionRecord
905 if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
906 return ErrNotFound
907 } else if err != nil {
908 return err
909 }
910 out = connectionView(r)
911 if r.State == wire.ConnSignedOut || r.LocalID == "" {
912 return nil
913 }
914 // To the runner that holds it, naming it: local ids repeat across
915 // runners.
916 runner, err := t.connectionRunner(r)
917 if err != nil {
918 return err
919 }
920 if err := t.audit(person, "connection.sign_out", r.ID+"@"+runner); err != nil {
921 return err
922 }
923 return t.commandTo(runner, person, wire.FrameDisconnect, wire.DisconnectCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, RunnerID: runner})
924 })
925 if err == nil && out.State == wire.ConnConnecting {
926 return s.CancelConnection(ctx, person, id)
927 }
928 return out, err
929}
930
931// SendSecret queues the sealed secret for one of the person's token
932// attempts (spec §2.4) as a durable secret frame to the attempt's
933// runner. The instance cannot open the box; it checks the clear binding
934// beside it names this attempt (its runner, Claude's endpoint, attempt
935// 1, a short expiry) and that the box is a size a sealed token can be.
936// One box per attempt: the attempt's token prompt goes with it, so the
937// card waits for the runner. A sign-in code (wire.EndpointClaudeCode)
938// goes the same way to a sign-in attempt, one box per prompt: its
939// attempt is the one the card shows, and the card's link goes with it
940// until the runner asks again. The box is in no event, response or log
941// line, and leaves the mailbox once the runner acks it.
942func (s *Store) SendSecret(ctx context.Context, person, id string, in wire.Sealed) (out wire.Connection, err error) {
943 if !sealedShape(in, s.now()) {
944 return out, ErrInvalid
945 }
946 err = s.tx(ctx, func(t *txn) error {
947 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
948 return err
949 }
950 var r connectionRecord
951 if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
952 return ErrNotFound
953 } else if err != nil {
954 return err
955 }
956 if in.RunnerID != r.RunnerID || in.ConnectionID != r.ID || in.Provider != r.Provider {
957 return ErrInvalid
958 }
959 if in.Endpoint == wire.EndpointClaudeCode {
960 if r.Provider != wire.ProviderClaude || r.Kind != wire.KindSubscription {
961 return ErrInvalid
962 }
963 p := promptOf(r)
964 if r.State != wire.ConnConnecting || p == nil || p.Kind != wire.PromptAuthorize || p.URL == "" || p.Attempt != in.Attempt {
965 return ErrConflict
966 }
967 // The card waits for the runner: no link until it asks again.
968 r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptAuthorize, Attempt: in.Attempt})
969 } else if r.Kind == wire.KindAPIKey {
970 // An API key, bound to its provider's origin (connectors
971 // spec §2.2); the card waits for the runner's model list.
972 if kp, ok := wire.APIKeyProviders[r.Provider]; !ok || in.Endpoint != kp.Endpoint || in.Attempt != 1 {
973 return ErrInvalid
974 }
975 p := promptOf(r)
976 if r.State != wire.ConnConnecting || p == nil || p.Kind != wire.PromptAPIKey {
977 return ErrConflict
978 }
979 r.Prompt = ""
980 } else {
981 if r.Kind != wire.KindToken || in.Endpoint != wire.EndpointAnthropic {
982 return ErrInvalid
983 }
984 if r.State != wire.ConnConnecting || r.Prompt == "" {
985 return ErrConflict
986 }
987 r.Prompt = ""
988 }
989 if err := t.saveConnection(&r, false); err != nil {
990 return err
991 }
992 out = connectionView(r)
993 return t.commandTo(r.RunnerID, person, wire.FrameSecret, wire.SecretCommand{Connection: r.ID, Person: person, Sealed: in})
994 })
995 return out, err
996}
997
998// sealedShape checks what can be checked of a box without opening it.
999func sealedShape(in wire.Sealed, now time.Time) bool {
1000 token := in.Provider == wire.ProviderClaude && in.Endpoint == wire.EndpointAnthropic && in.Attempt == 1
1001 code := in.Provider == wire.ProviderClaude && in.Endpoint == wire.EndpointClaudeCode && in.Attempt >= 1 && in.Attempt <= wire.MaxCodeAttempts
1002 kp, apiKey := wire.APIKeyProviders[in.Provider]
1003 apiKey = apiKey && in.Endpoint == kp.Endpoint && in.Attempt == 1
1004 if !token && !code && !apiKey || len(in.Box) > wire.MaxSealedBytes {
1005 return false
1006 }
1007 // The runner allows a minute of clock skew past the TTL; so does this.
1008 if !in.ExpiresAt.After(now) || in.ExpiresAt.Sub(now) > wire.SealedTTL+time.Minute {
1009 return false
1010 }
1011 raw, err := base64.StdEncoding.DecodeString(in.Box)
1012 // An ephemeral public key and a MAC at least.
1013 return err == nil && len(raw) > 48
1014}
1015
1016// dropSecret takes an ended attempt's box out of the mailbox before its
1017// runner took it.
1018func (t *txn) dropSecret(connection string) error {
1019 like := `{"connection":"` + strings.ReplaceAll(connection, `"`, "") + `",%`
1020 return t.db.Model(&commandRecord{}).Where("kind = ? AND body LIKE ?", wire.FrameSecret, like).Updates(map[string]any{"body": "{}", "acked_at": t.now()}).Error
1021}
1022
1023// sameTime reports whether two optional times are the same instant.
1024func sameTime(a, b *time.Time) bool {
1025 if a == nil || b == nil {
1026 return a == b
1027 }
1028 return a.Equal(*b)
1029}
1030
1031// expireAttempts ends attempts that made no progress (a runner that went
1032// away mid-attempt reports nothing).
1033func (t *txn) expireAttempts() error {
1034 var rows []connectionRecord
1035 if err := t.db.Where("state = ? AND updated_at < ?", wire.ConnConnecting, t.now().Add(-connectionAttemptLimit)).Find(&rows).Error; err != nil {
1036 return err
1037 }
1038 for i := range rows {
1039 rows[i].State, rows[i].Reason, rows[i].Prompt = wire.ConnError, "timed_out", ""
1040 if err := t.saveConnection(&rows[i], false); err != nil {
1041 return err
1042 }
1043 if err := t.dropSecret(rows[i].ID); err != nil {
1044 return err
1045 }
1046 }
1047 return nil
1048}
1049
1050// usageOutcomes are the endings a usage row may name.
1051var usageOutcomes = map[string]bool{wire.OutcomeReplied: true, wire.OutcomeFailed: true, wire.OutcomeCancelled: true, wire.OutcomeSuperseded: true}
1052
1053// recordUsage keeps one row per attempt and model, keyed so a resent
1054// frame changes nothing. turn is a coordinator turn, step a step or a
1055// question; round the step's fix round.
1056func (t *txn) recordUsage(l Lease, person, role, task, step, turn string, round int, rows []wire.Usage) error {
1057 protocol := l.Protocol
1058 // Below 37 a row keeps its legacy form (no runner), and a worker has
1059 // no connection usage to record.
1060 var runner *string
1061 if protocol >= wire.ProtocolMacEngineering {
1062 runner = &l.Runner.RunnerID
1063 } else if l.Role == wire.RoleWorker {
1064 return nil
1065 }
1066 settle := map[int64]bool{}
1067 for _, u := range rows {
1068 if !usageOutcomes[u.Outcome] || u.Attempt < 1 || len(u.Model) > 200 || len(u.Connection) > 200 || u.Turns != nil && *u.Turns < 0 || u.CostMicros != nil && *u.CostMicros < 0 || u.CostReportedMicros != nil && *u.CostReportedMicros < 0 || len(u.Currency) > 8 || len(u.PriceVersion) > 64 || len(u.Family) > 64 || len(u.Tier) > 16 || len(u.TierVersion) > 64 {
1069 return ErrInvalid
1070 }
1071 r := usageRecord{Person: person, RunnerID: runner, Connection: u.Connection, Provider: u.Provider, Model: u.Model, Role: role, TaskID: task, StepID: step, TurnID: turn, Attempt: u.Attempt, Outcome: u.Outcome, Complete: u.Complete, InputTokens: u.InputTokens, CachedInputTokens: u.CachedInputTokens, CacheWriteTokens: u.CacheWriteTokens, OutputTokens: u.OutputTokens, ReasoningOutputTokens: u.ReasoningOutputTokens, Round: round, Turns: u.Turns, Overcount: protocol < wire.ProtocolSpend && u.Provider == "claude" && (role == "coordinator" || role == "ask"), CostMicros: u.CostMicros, Currency: u.Currency, PriceVersion: u.PriceVersion, CostReportedMicros: u.CostReportedMicros, Family: u.Family, Tier: u.Tier, TierVersion: u.TierVersion, ModelMismatch: u.ModelMismatch, RecordedAt: t.now()}
1072 if err := t.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&r).Error; err != nil {
1073 return err
1074 }
1075 settle[u.Attempt] = step != ""
1076 }
1077 // A needs-you triage action's step: its row records what it spent,
1078 // recomputed from every usage row so far.
1079 for attempt, ok := range settle {
1080 if !ok {
1081 continue
1082 }
1083 if err := t.triageSettle(person, step, attempt); err != nil {
1084 return err
1085 }
1086 }
1087 return nil
1088}
1089
1090// stepRound is the fix round of the step a question asked.
1091func (t *txn) stepRound(id string) (int, error) {
1092 var s stepRecord
1093 if err := t.db.Select("round").Where("id = ?", id).First(&s).Error; err != nil {
1094 return 0, err
1095 }
1096 return s.Round, nil
1097}
1098
1099// usageReport records the rows of attempts that produced no reply, for
1100// one of the person's own turns, steps or questions.
1101func (t *txn) usageReport(l Lease, v *wire.UsageReport) error {
1102 // A worker below 37 has none of its connections' usage recorded
1103 // (recordUsage).
1104 person := l.Runner.Person
1105 switch {
1106 case v.TurnID != "" && v.StepID == "" && v.QuestionID == "":
1107 if _, err := t.ownTurn(l, v.TurnID); err != nil {
1108 return err
1109 }
1110 return t.recordUsage(l, person, "coordinator", "", "", v.TurnID, 0, v.Rows)
1111 case v.StepID != "" && v.TurnID == "" && v.QuestionID == "":
1112 var s stepRecord
1113 if err := t.db.Where("id = ? AND person = ?", v.StepID, person).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) {
1114 return ErrNotFound
1115 } else if err != nil {
1116 return err
1117 }
1118 return t.recordUsage(l, person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Rows)
1119 case v.QuestionID != "" && v.TurnID == "" && v.StepID == "":
1120 q, err := t.ownQuestion(l, v.QuestionID)
1121 if err != nil {
1122 return err
1123 }
1124 round, err := t.stepRound(q.StepID)
1125 if err != nil {
1126 return err
1127 }
1128 return t.recordUsage(l, person, "ask", q.TaskID, q.ID, "", round, v.Rows)
1129 case v.ProbeID != "" && v.CheckID == "" && v.TurnID == "" && v.StepID == "" && v.QuestionID == "":
1130 // A metered connection's probe: one billable token on its model,
1131 // charged like any other attempt (connectors spec §2.2).
1132 if len(v.ProbeID) > 200 {
1133 return ErrInvalid
1134 }
1135 return t.recordUsage(l, person, wire.UsageProbe, "", v.ProbeID, "", 0, v.Rows)
1136 case v.CheckID != "" && v.ProbeID == "" && v.TurnID == "" && v.StepID == "" && v.QuestionID == "":
1137 // A token connection's health check: a real request on the
1138 // person's own connection, keyed by the check so each counts.
1139 if len(v.CheckID) > 200 {
1140 return ErrInvalid
1141 }
1142 return t.recordUsage(l, person, "check", "", v.CheckID, "", 0, v.Rows)
1143 }
1144 return ErrInvalid
1145}
1146
1147// NoConnectionLine is what the person's connections say about why
1148// nothing can answer: each connection's provider with its state and, for
1149// a limited one, the reset the provider reported. The page renders it.
1150type NoConnectionLine struct {
1151 Provider string
1152 State string
1153 ResetsAt *time.Time
1154}
1155
1156// NoConnection reads the person's connections for the no_connection card.
1157func (s *Store) NoConnection(ctx context.Context, person string) (out []NoConnectionLine, err error) {
1158 conns, err := s.Connections(ctx, person)
1159 for _, c := range conns {
1160 if c.State == wire.ConnConnecting || c.State == wire.ConnError && c.LocalID == "" {
1161 continue
1162 }
1163 line := NoConnectionLine{Provider: c.Provider, State: c.State}
1164 if c.Headroom != nil && c.State == wire.ConnLimited {
1165 line.ResetsAt = c.Headroom.ResetsAt
1166 }
1167 out = append(out, line)
1168 }
1169 return out, err
1170}
1171
1172// Spend is what usage rows add up to: every token read or written
1173// (input, cached or not, and output) and, of them, the cached input.
1174// Partial: a row lacked a figure the sum needs, or the harness's final
1175// usage message for it was not seen, so the sum is a lower bound.
1176type Spend struct {
1177 Tokens, Cached int64
1178 Partial bool
1179}
1180
1181func (s *Spend) add(o Spend) {
1182 s.Tokens, s.Cached, s.Partial = s.Tokens+o.Tokens, s.Cached+o.Cached, s.Partial || o.Partial
1183}
1184
1185// TaskSpend is a task's recorded usage: in all, per step, and for the
1186// questions asked about it. Rows is how many usage rows it counts;
1187// Left out says rows were left out because they overcount.
1188type TaskSpend struct {
1189 Total Spend
1190 Steps map[string]Spend
1191 Questions Spend
1192 Rows int
1193 LeftOut bool
1194}
1195
1196// TaskSpend reads a task's usage rows for anyone on the team who can
1197// read the task. Claude reports cached and cache-written input apart
1198// from input; Codex counts cached input inside it.
1199func (s *Store) TaskSpend(ctx context.Context, person, id string) (out TaskSpend, err error) {
1200 out.Steps = map[string]Spend{}
1201 err = s.read(ctx, func(tx *gorm.DB) error {
1202 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
1203 return err
1204 }
1205 t := &txn{s: s, db: tx}
1206 if _, err := t.loadTask(id); err != nil {
1207 return err
1208 }
1209 var rows []usageRecord
1210 if err := tx.Where("task_id = ?", id).Find(&rows).Error; err != nil {
1211 return err
1212 }
1213 for _, r := range rows {
1214 if r.Overcount {
1215 out.LeftOut = true
1216 continue
1217 }
1218 out.Rows++
1219 one := rowSpend(r)
1220 out.Total.add(one)
1221 if r.Role == "ask" {
1222 out.Questions.add(one)
1223 } else {
1224 step := out.Steps[r.StepID]
1225 step.add(one)
1226 out.Steps[r.StepID] = step
1227 }
1228 }
1229 return nil
1230 })
1231 return out, err
1232}
1233
1234// rowSpend is one usage row's part of a sum. Claude counts cache reads
1235// and writes apart from input, so each is a figure of the sum; for Codex
1236// the cached figure is part of input, but the cached subtotal needs it.
1237func rowSpend(r usageRecord) Spend {
1238 one := Spend{Partial: !r.Complete || r.InputTokens == nil || r.OutputTokens == nil || r.CachedInputTokens == nil || r.Provider == "claude" && r.CacheWriteTokens == nil}
1239 in, cached, written := figure(r.InputTokens), figure(r.CachedInputTokens), figure(r.CacheWriteTokens)
1240 if r.Provider == "claude" {
1241 in += cached + written
1242 }
1243 one.Tokens, one.Cached = in+figure(r.OutputTokens), cached
1244 return one
1245}
1246
1247func figure(p *int64) int64 {
1248 if p == nil {
1249 return 0
1250 }
1251 return *p
1252}
1253
1254// UsageToday sums the person's recorded tokens (input and output) per
1255// connection (by UsageKey) since midnight UTC, without rows that
1256// overcount.
1257func (s *Store) UsageToday(ctx context.Context, person string) (map[string]int64, error) {
1258 out := map[string]int64{}
1259 err := s.read(ctx, func(tx *gorm.DB) error {
1260 var rows []struct {
1261 Runner string
1262 Connection string
1263 N int64
1264 }
1265 primary, err := s.authority.PrimaryRunner(tx, person)
1266 if err != nil {
1267 return err
1268 }
1269 day := s.now().UTC().Truncate(24 * time.Hour)
1270 if err := tx.Raw("SELECT coalesce(runner_id, '') AS runner, connection, sum(coalesce(input_tokens,0) + coalesce(output_tokens,0)) AS n FROM chat_usage WHERE person = ? AND recorded_at >= ? AND NOT coalesce(overcount, 0) GROUP BY coalesce(runner_id, ''), connection", person, day).Scan(&rows).Error; err != nil {
1271 return err
1272 }
1273 for _, r := range rows {
1274 out[UsageKey(primary, r.Runner, r.Connection)] += r.N
1275 }
1276 return nil
1277 })
1278 return out, err
1279}
1280
1281// MaxStatedEmail is the longest account email a person may type.
1282const MaxStatedEmail = 254
1283
1284// StatedEmailShape reports whether s looks like an email address: one
1285// @ with something either side, a dot inside the domain, at most
1286// MaxStatedEmail bytes, and no spaces, control or format characters.
1287// It proves nothing about the account.
1288func StatedEmailShape(s string) bool {
1289 if s == "" || len(s) > MaxStatedEmail || !utf8.ValidString(s) {
1290 return false
1291 }
1292 for _, r := range s {
1293 if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) || unicode.IsSpace(r) || strings.ContainsRune(`<>()[]\,;:"`, r) {
1294 return false
1295 }
1296 }
1297 local, domain, ok := strings.Cut(s, "@")
1298 host := strings.Trim(domain, ".")
1299 return ok && local != "" && host == domain && strings.Contains(host, ".") && !strings.Contains(domain, "@") && !strings.Contains(domain, "..")
1300}
1301
1302// SetStatedEmail keeps the account email the person says one of their
1303// token connections signs in as ("" clears it). It is their words, kept
1304// apart from what the provider reports: shown on their row and nowhere
1305// else, never sent to the runner, never matched or routed on.
1306func (s *Store) SetStatedEmail(ctx context.Context, person, id, email string) error {
1307 email = strings.TrimSpace(email)
1308 if email != "" && !StatedEmailShape(email) {
1309 return ErrInvalid
1310 }
1311 return s.tx(ctx, func(t *txn) error {
1312 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
1313 return err
1314 }
1315 var r connectionRecord
1316 if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
1317 return ErrNotFound
1318 } else if err != nil {
1319 return err
1320 }
1321 // Claude's sign-in by a link asks for it with the code (Paul,
1322 // 2026-11-23): kept on the attempt, it is the token connection's
1323 // once the runner makes it.
1324 asked := r.State == wire.ConnConnecting && signingIn(r)
1325 if !asked && (r.Kind != wire.KindToken || r.LocalID == "" || r.State == wire.ConnSignedOut || r.State == wire.ConnConnecting) {
1326 return ErrConflict
1327 }
1328 if r.StatedEmail == email {
1329 return nil
1330 }
1331 if err := t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Update("stated_email", email).Error; err != nil {
1332 return err
1333 }
1334 if asked {
1335 // Nothing on the card shows it: no event until the row.
1336 return nil
1337 }
1338 r.StatedEmail = email
1339 // The row's event, so the person's other pages read it again.
1340 return t.saveConnection(&r, false)
1341 })
1342}
1343
1344// RowFacts are what the Connections page knows beside the runner's
1345// report: the email the person stated for each connection (by its id),
1346// and the connections (by UsageKey) a turn was answered on a while ago,
1347// whose provider had its chance to report usage by now.
1348type RowFacts struct {
1349 Stated map[string]string
1350 Served map[string]bool
1351}
1352
1353// ConnectionRowFacts reads the person's RowFacts; served counts only
1354// answered turns, steps and questions recorded more than grace ago,
1355// never a token check.
1356func (s *Store) ConnectionRowFacts(ctx context.Context, person string, grace time.Duration) (RowFacts, error) {
1357 servedBefore := s.now().Add(-grace)
1358 out := RowFacts{Stated: map[string]string{}, Served: map[string]bool{}}
1359 err := s.read(ctx, func(tx *gorm.DB) error {
1360 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
1361 return err
1362 }
1363 var stated []connectionRecord
1364 if err := tx.Select("id", "stated_email").Where("person = ? AND coalesce(stated_email, '') <> ''", person).Find(&stated).Error; err != nil {
1365 return err
1366 }
1367 for _, r := range stated {
1368 out.Stated[r.ID] = r.StatedEmail
1369 }
1370 var served []struct{ Runner, Connection string }
1371 primary, err := s.authority.PrimaryRunner(tx, person)
1372 if err != nil {
1373 return err
1374 }
1375 if err := tx.Raw("SELECT DISTINCT coalesce(runner_id, '') AS runner, connection FROM chat_usage WHERE person = ? AND role NOT IN ('check', 'probe') AND outcome = ? AND recorded_at < ?", person, wire.OutcomeReplied, servedBefore).Scan(&served).Error; err != nil {
1376 return err
1377 }
1378 for _, c := range served {
1379 out.Served[UsageKey(primary, c.Runner, c.Connection)] = true
1380 }
1381 return nil
1382 })
1383 return out, err
1384}
1385