| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "slices" |
| 8 | "strconv" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | "gorm.io/gorm" |
| 12 | ) |
| 13 | |
| 14 | // Metered connections on the instance (connectors spec 2026-11-12, S1): |
| 15 | // an API-key connection is started with its confirmations and budget, |
| 16 | // its key is sealed in the page to the runner (SendSecret), the person |
| 17 | // picks its model from the list the runner read, and its budget and |
| 18 | // Resume go to the runner as durable frames. The runner holds the |
| 19 | // ledger; the instance shows what it reports. |
| 20 | |
| 21 | // ErrConfirmation: an API-key connection without the confirmations its |
| 22 | // billing needs (§2.1). |
| 23 | var ErrConfirmation = errors.New("chat: the connection needs its confirmations") |
| 24 | |
| 25 | // ErrRunnerTooOld: the person's runner speaks a protocol before metered |
| 26 | // connections; it is refused one rather than downgraded (§10). |
| 27 | var ErrRunnerTooOld = errors.New("chat: the runner is too old for this connection") |
| 28 | |
| 29 | // runnerProtocol is the protocol the runner last spoke (1 when unknown). |
| 30 | func (t *txn) runnerProtocol(person, runner string) (int, error) { |
| 31 | rs, err := t.runners(person) |
| 32 | if err != nil { |
| 33 | return 0, err |
| 34 | } |
| 35 | for _, r := range rs { |
| 36 | if r.ID == runner { |
| 37 | return r.Protocol, nil |
| 38 | } |
| 39 | } |
| 40 | return wire.Protocol1, nil |
| 41 | } |
| 42 | |
| 43 | // startAPIKey starts an API-key connection attempt on the person's |
| 44 | // primary runner: the provider from the table, the limit confirmed when |
| 45 | // it is metered, pay-as-you-go off only for an overflow subscription, |
| 46 | // and a budget in bounds. The confirmations are recorded with the |
| 47 | // person, the time and the provider. |
| 48 | func (s *Store) startAPIKey(ctx context.Context, person string, in wire.Connect) (out wire.Connection, err error) { |
| 49 | kp, ok := wire.APIKeyProviders[in.Provider] |
| 50 | if !ok || in.SameMachine { |
| 51 | return out, ErrInvalid |
| 52 | } |
| 53 | if err := kp.CheckConfirmations(in.LimitConfirmed, in.PaygOffConfirmed); err != nil { |
| 54 | return out, ErrConfirmation |
| 55 | } |
| 56 | if in.Budget == nil || !wire.ValidBudget(wire.Budget{Day: in.Budget.Day, Month: in.Budget.Month}) { |
| 57 | return out, ErrInvalid |
| 58 | } |
| 59 | budget := wire.Budget{Day: in.Budget.Day, Month: in.Budget.Month, Currency: kp.Currency, Revision: 1} |
| 60 | billing := kp.Billing(in.PaygOffConfirmed) |
| 61 | err = s.tx(ctx, func(t *txn) error { |
| 62 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 63 | return err |
| 64 | } |
| 65 | runner, err := s.runnerView(t.db, person) |
| 66 | if err != nil { |
| 67 | return err |
| 68 | } |
| 69 | if runner.ID == "" { |
| 70 | return ErrNotFound |
| 71 | } |
| 72 | if in.RunnerID != "" && in.RunnerID != runner.ID { |
| 73 | // An API key stays on the main runner (Mac runners spec §8.5). |
| 74 | if _, found, err := t.connectionMachine(person, in.RunnerID); err != nil { |
| 75 | return err |
| 76 | } else if found { |
| 77 | return ErrInvalid |
| 78 | } |
| 79 | return ErrNotFound |
| 80 | } |
| 81 | rows, err := t.connections(person) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | for _, r := range rows { |
| 86 | if r.State == wire.ConnConnecting && r.Provider == in.Provider && r.RunnerID == runner.ID { |
| 87 | out = connectionView(r) |
| 88 | return nil |
| 89 | } |
| 90 | } |
| 91 | if !runner.Online { |
| 92 | return ErrRunnerOffline |
| 93 | } |
| 94 | if proto, err := t.runnerProtocol(person, runner.ID); err != nil { |
| 95 | return err |
| 96 | } else if proto < wire.ProtocolMetered || in.Provider == wire.ProviderOpenCodeGo && proto < wire.ProtocolOpenCode { |
| 97 | // An older runner is refused the connection, never sent it: |
| 98 | // OpenCode Go is new at protocol 17 (slice S5). |
| 99 | return ErrRunnerTooOld |
| 100 | } |
| 101 | now := t.now() |
| 102 | r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner.ID, Provider: in.Provider, Kind: wire.KindAPIKey, State: wire.ConnConnecting, Harness: kp.Harness, Upstream: kp.Upstream, Billing: billing, Budget: asJSON(budget), Prompt: asJSON(wire.ConnectPrompt{Kind: wire.PromptAPIKey})} |
| 103 | if in.LimitConfirmed { |
| 104 | r.LimitConfirmedAt = &now |
| 105 | } |
| 106 | if in.PaygOffConfirmed { |
| 107 | r.PaygOffConfirmedAt = &now |
| 108 | } |
| 109 | if err := t.saveConnection(&r, true); err != nil { |
| 110 | return err |
| 111 | } |
| 112 | // The confirmations are kept on the record (saveConnection writes |
| 113 | // only what a later change may change), and audited. |
| 114 | for kind, confirmed := range map[string]bool{"connection.limit_confirmed": in.LimitConfirmed, "connection.payg_off_confirmed": in.PaygOffConfirmed} { |
| 115 | if confirmed { |
| 116 | if err := t.audit(person, kind, r.ID+"@"+r.Provider); err != nil { |
| 117 | return err |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | if err := t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Updates(map[string]any{"limit_confirmed_at": r.LimitConfirmedAt, "payg_off_confirmed_at": r.PaygOffConfirmedAt}).Error; err != nil { |
| 122 | return err |
| 123 | } |
| 124 | out = connectionView(r) |
| 125 | return t.commandTo(runner.ID, person, wire.FrameConnect, wire.ConnectCommand{Connection: r.ID, Person: person, Provider: r.Provider, Kind: wire.KindAPIKey, Billing: billing, Budget: &budget}) |
| 126 | }) |
| 127 | return out, err |
| 128 | } |
| 129 | |
| 130 | // audit appends a credential-free audit event in t: the verified actor, |
| 131 | // what was done and the record (a connection id and a revision). |
| 132 | func (t *txn) audit(person, kind, record string) error { |
| 133 | if t.s.authority.Audit == nil { |
| 134 | return nil |
| 135 | } |
| 136 | return t.s.authority.Audit(t.db, person, kind, record) |
| 137 | } |
| 138 | |
| 139 | // ownConnection reads one of the person's connections in t. |
| 140 | func (t *txn) ownConnection(person, id string) (connectionRecord, error) { |
| 141 | var r connectionRecord |
| 142 | err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error |
| 143 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 144 | return r, ErrNotFound |
| 145 | } |
| 146 | return r, err |
| 147 | } |
| 148 | |
| 149 | // ChooseModel is the person's pick of a connecting API-key connection's |
| 150 | // one model, from the list its runner read (a second model is a second |
| 151 | // connection). The card waits for the runner's probe after it. |
| 152 | func (s *Store) ChooseModel(ctx context.Context, person, id string, in wire.ChooseModel) (out wire.Connection, err error) { |
| 153 | err = s.tx(ctx, func(t *txn) error { |
| 154 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 155 | return err |
| 156 | } |
| 157 | r, err := t.ownConnection(person, id) |
| 158 | if err != nil { |
| 159 | return err |
| 160 | } |
| 161 | p := promptOf(r) |
| 162 | if r.Kind != wire.KindAPIKey { |
| 163 | return ErrInvalid |
| 164 | } |
| 165 | if r.State != wire.ConnConnecting || p == nil || p.Kind != wire.PromptModel || len(p.Models) == 0 { |
| 166 | return ErrConflict |
| 167 | } |
| 168 | if !slices.Contains(p.Models, in.Model) { |
| 169 | return ErrInvalid |
| 170 | } |
| 171 | // An older runner's one model: its set of one (§16.5). |
| 172 | r.Model, r.Prompt = in.Model, asJSON(wire.ConnectPrompt{Kind: wire.PromptModel}) |
| 173 | r.Models, r.ModelsRevision = asJSON([]string{in.Model}), 1 |
| 174 | if err := t.saveConnection(&r, false); err != nil { |
| 175 | return err |
| 176 | } |
| 177 | out = connectionView(r) |
| 178 | return t.commandTo(r.RunnerID, person, wire.FrameModel, wire.ModelCommand{Connection: r.ID, Person: person, Model: in.Model}) |
| 179 | }) |
| 180 | return out, err |
| 181 | } |
| 182 | |
| 183 | // ErrModelsNotAllowed: a set with no model, or with a model the key did |
| 184 | // not list as one that can be allowed (§16.1). |
| 185 | var ErrModelsNotAllowed = errors.New("chat: those models cannot be allowed") |
| 186 | |
| 187 | // SetModels is the person's allowed set for one of their own metered |
| 188 | // connections (§16.1): the models card's answer while it connects |
| 189 | // (revision 0), or a change of a made connection's set against the |
| 190 | // revision they saw (ErrConflict when it moved). Owner-only: the |
| 191 | // connection must be the person's own, the actor is the session's, and |
| 192 | // the roster is checked in the write transaction; audited. At least one |
| 193 | // model, each one the key listed that can be allowed. A runner below |
| 194 | // ProtocolModels is refused any change (ErrRunnerTooOld): its |
| 195 | // connections keep their one model. It goes to the runner as a durable |
| 196 | // models frame and is pending until the runner applies it. |
| 197 | func (s *Store) SetModels(ctx context.Context, person, id string, in wire.SetModels) (out wire.Connection, err error) { |
| 198 | err = s.tx(ctx, func(t *txn) error { |
| 199 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 200 | return err |
| 201 | } |
| 202 | out, err = t.setModels(person, id, in) |
| 203 | return err |
| 204 | }) |
| 205 | return out, err |
| 206 | } |
| 207 | |
| 208 | func (t *txn) setModels(person, id string, in wire.SetModels) (wire.Connection, error) { |
| 209 | r, err := t.ownConnection(person, id) |
| 210 | if err != nil { |
| 211 | return wire.Connection{}, err |
| 212 | } |
| 213 | if r.Kind != wire.KindAPIKey { |
| 214 | return wire.Connection{}, ErrInvalid |
| 215 | } |
| 216 | if !wire.ValidAllowed(in.Allowed) { |
| 217 | return wire.Connection{}, ErrModelsNotAllowed |
| 218 | } |
| 219 | var cmd wire.ModelsCommand |
| 220 | switch { |
| 221 | case r.State == wire.ConnConnecting: |
| 222 | p := promptOf(r) |
| 223 | if p == nil || p.Kind != wire.PromptModels || len(p.Choices) == 0 || in.Revision != 0 { |
| 224 | return wire.Connection{}, ErrConflict |
| 225 | } |
| 226 | if !allowable(p.Choices, in.Allowed) { |
| 227 | return wire.Connection{}, ErrModelsNotAllowed |
| 228 | } |
| 229 | // The card waits for the runner's proof after it. |
| 230 | r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptModels}) |
| 231 | cmd = wire.ModelsCommand{Connection: r.ID, Person: person, Allowed: in.Allowed, Revision: 1} |
| 232 | default: |
| 233 | if r.LocalID == "" || r.State == wire.ConnSignedOut { |
| 234 | return wire.Connection{}, ErrConflict |
| 235 | } |
| 236 | if proto, err := t.runnerProtocol(person, r.RunnerID); err != nil { |
| 237 | return wire.Connection{}, err |
| 238 | } else if proto < wire.ProtocolModels { |
| 239 | return wire.Connection{}, ErrRunnerTooOld |
| 240 | } |
| 241 | if in.Revision != r.ModelsRevision { |
| 242 | return wire.Connection{}, ErrConflict |
| 243 | } |
| 244 | var listed []wire.ModelChoice |
| 245 | for _, m := range modelsView(r) { |
| 246 | listed = append(listed, wire.ModelChoice{ID: m.ID, Eligible: m.Eligible}) |
| 247 | } |
| 248 | if !allowable(listed, in.Allowed) { |
| 249 | return wire.Connection{}, ErrModelsNotAllowed |
| 250 | } |
| 251 | cmd = wire.ModelsCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, Allowed: in.Allowed, Revision: r.ModelsRevision + 1} |
| 252 | } |
| 253 | r.Models, r.ModelsRevision = asJSON(cmd.Allowed), cmd.Revision |
| 254 | if err := t.saveConnection(&r, false); err != nil { |
| 255 | return wire.Connection{}, err |
| 256 | } |
| 257 | if err := t.audit(person, "connection.models", r.ID+"@"+strconv.FormatInt(cmd.Revision, 10)); err != nil { |
| 258 | return wire.Connection{}, err |
| 259 | } |
| 260 | return connectionView(r), t.commandTo(r.RunnerID, person, wire.FrameModels, cmd) |
| 261 | } |
| 262 | |
| 263 | // allowable reports whether every model of a set is one the key listed |
| 264 | // that can be allowed. |
| 265 | func allowable(choices []wire.ModelChoice, allowed []string) bool { |
| 266 | for _, m := range allowed { |
| 267 | if !slices.ContainsFunc(choices, func(c wire.ModelChoice) bool { return c.ID == m && c.Eligible }) { |
| 268 | return false |
| 269 | } |
| 270 | } |
| 271 | return true |
| 272 | } |
| 273 | |
| 274 | // meteredConnection is one of the person's API-key connections the |
| 275 | // runner holds (made, not signed out). |
| 276 | func (t *txn) meteredConnection(person, id string) (connectionRecord, error) { |
| 277 | r, err := t.ownConnection(person, id) |
| 278 | if err != nil { |
| 279 | return r, err |
| 280 | } |
| 281 | if r.Kind != wire.KindAPIKey { |
| 282 | return r, ErrInvalid |
| 283 | } |
| 284 | if r.LocalID == "" || r.State == wire.ConnSignedOut || r.State == wire.ConnConnecting { |
| 285 | return r, ErrConflict |
| 286 | } |
| 287 | return r, nil |
| 288 | } |
| 289 | |
| 290 | // SetBudget changes a metered connection's budget against the revision |
| 291 | // the person saw (ErrConflict when it moved). It takes effect when the |
| 292 | // runner applies the durable budget frame; until its ack the connection |
| 293 | // says the budget is pending. A running step is not stopped. |
| 294 | func (s *Store) SetBudget(ctx context.Context, person, id string, in wire.SetBudget) (out wire.Connection, err error) { |
| 295 | err = s.tx(ctx, func(t *txn) error { |
| 296 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 297 | return err |
| 298 | } |
| 299 | out, err = t.setBudget(person, id, in) |
| 300 | return err |
| 301 | }) |
| 302 | return out, err |
| 303 | } |
| 304 | |
| 305 | // setBudget is SetBudget in t (advice's Raise acts through it too). |
| 306 | func (t *txn) setBudget(person, id string, in wire.SetBudget) (wire.Connection, error) { |
| 307 | r, err := t.meteredConnection(person, id) |
| 308 | if err != nil { |
| 309 | return wire.Connection{}, err |
| 310 | } |
| 311 | b, _ := budgetOf(r) |
| 312 | if in.Revision != b.Revision { |
| 313 | return wire.Connection{}, ErrConflict |
| 314 | } |
| 315 | next := wire.Budget{Day: in.Day, Month: in.Month, Currency: b.Currency, Revision: b.Revision + 1} |
| 316 | if !wire.ValidBudget(next) { |
| 317 | return wire.Connection{}, ErrInvalid |
| 318 | } |
| 319 | r.Budget = asJSON(next) |
| 320 | if err := t.saveConnection(&r, false); err != nil { |
| 321 | return wire.Connection{}, err |
| 322 | } |
| 323 | if err := t.audit(person, "connection.budget", r.ID+"@"+strconv.FormatInt(next.Revision, 10)); err != nil { |
| 324 | return wire.Connection{}, err |
| 325 | } |
| 326 | return connectionView(r), t.commandTo(r.RunnerID, person, wire.FrameBudget, wire.BudgetCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, Budget: next}) |
| 327 | } |
| 328 | |
| 329 | // ResumeSpend is the person's Resume of a connection whose spend is |
| 330 | // unknown, after looking at the provider's dashboard. It is bound to the |
| 331 | // pause they saw: the runner consumes it once, only while that pause is |
| 332 | // current, so a stale Resume leaves a newer pause. |
| 333 | func (s *Store) ResumeSpend(ctx context.Context, person, id string, in wire.ResumeSpend) error { |
| 334 | return s.tx(ctx, func(t *txn) error { |
| 335 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 336 | return err |
| 337 | } |
| 338 | r, err := t.meteredConnection(person, id) |
| 339 | if err != nil { |
| 340 | return err |
| 341 | } |
| 342 | var spend wire.Spend |
| 343 | if r.Spend == "" || json.Unmarshal([]byte(r.Spend), &spend) != nil || !spend.Unknown || spend.PauseRevision != in.PauseRevision { |
| 344 | return ErrConflict |
| 345 | } |
| 346 | if err := t.audit(person, "connection.resume", r.ID+"@"+strconv.FormatInt(in.PauseRevision, 10)); err != nil { |
| 347 | return err |
| 348 | } |
| 349 | return t.commandTo(r.RunnerID, person, wire.FrameResumeSpend, wire.ResumeSpendCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, PauseRevision: in.PauseRevision}) |
| 350 | }) |
| 351 | } |
| 352 | |
| 353 | // budgetAcked records that the runner applied a budget frame: the page |
| 354 | // stops saying it is pending. |
| 355 | func (t *txn) budgetAcked(body string) error { |
| 356 | var cmd wire.BudgetCommand |
| 357 | if err := json.Unmarshal([]byte(body), &cmd); err != nil { |
| 358 | return err |
| 359 | } |
| 360 | var r connectionRecord |
| 361 | if err := t.db.Where("id = ? AND person = ?", cmd.Connection, cmd.Person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 362 | return nil |
| 363 | } else if err != nil { |
| 364 | return err |
| 365 | } |
| 366 | if cmd.Budget.Revision <= r.BudgetApplied { |
| 367 | return nil |
| 368 | } |
| 369 | r.BudgetApplied = cmd.Budget.Revision |
| 370 | return t.saveConnection(&r, false) |
| 371 | } |
| 372 | |