oficina / equipo Public

instance: metered connections, budget and Resume

POST /api/v1/connections with kind api_key starts a TensorX connection
on the person's runner: refused without the limit confirmation, with a
pay-as-you-go confirmation a per-token provider cannot have, without a
budget in bounds, or on a runner before protocol 12. The confirmations
are kept with the time; the key travels sealed to the runner, bound to
TensorX's origin, as a token does. POST /connections/{id}/model picks
the model from the runner's list; PUT /connections/{id}/budget is
pending until the runner acks its frame; POST /connections/{id}/resume
is bound to the pause the person saw. Hello brings the harness, model,
budget and spend; a probe's usage is recorded with role probe and its
cost. A question held by the guard keeps its hold as its reason.
Migration 0068 adds the columns.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev c2adf8e7b7f5811c70038239773c04ccddecbedc parent 0670615
9 files changed, +695 −14
  • internal/equipo/chat/connections.go +107 −11
  • internal/equipo/chat/http.go +55 −0
  • internal/equipo/chat/metered.go +239 −0
  • internal/equipo/chat/questions.go +12 −1
  • internal/equipo/chat/runner.go +3 −0
  • internal/equipo/migrations/0068_thin_metered_connections.sql +13 −0
  • internal/equipo/migrations/schema.sql +2 −2
  • internal/thintest/client.go +15 −0
  • internal/thintest/metered_contract_test.go +249 −0
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go
index dbd5ea04..a18e151e 100644
--- a/internal/equipo/chat/connections.go
+++ b/internal/equipo/chat/connections.go
@@ -56,6 +56,21 @@ type connectionRecord struct {
// beside the row as theirs, never matched, deduplicated or routed on,
// and never sent to the runner.
StatedEmail string
+ // An API-key connection (connectors spec S1): its harness, origin,
+ // billing and model; when the person confirmed the provider-side
+ // limit and, for an overflow subscription, pay-as-you-go off; the
+ // budget the person set (JSON wire.Budget) and the highest revision
+ // the runner applied; its spend as the runner last reported it (JSON
+ // wire.Spend).
+ Harness string
+ Upstream string
+ Billing string
+ Model string
+ LimitConfirmedAt *time.Time
+ PaygOffConfirmedAt *time.Time
+ Budget string
+ BudgetApplied int64
+ Spend string
}
func (connectionRecord) TableName() string { return "chat_connections" }
@@ -87,6 +102,13 @@ type usageRecord struct {
// (modelUsage) as the turn's own. It is at most what was used, often
// more; sums leave it out and say so.
Overcount bool
+ // A metered connection's charge: the cost the runner priced (null
+ // when it could not), its currency and price table version, and the
+ // cost the harness reported itself.
+ CostMicros *int64
+ Currency string
+ PriceVersion string
+ CostReportedMicros *int64
// Figures the harness did not report stay null, never zero.
InputTokens *int64
CachedInputTokens *int64
@@ -112,9 +134,32 @@ func connectionView(r connectionRecord) wire.Connection {
v.Prompt = nil
}
}
+ if r.Kind == wire.KindAPIKey {
+ v.Harness, v.Upstream, v.Billing, v.Model, v.LimitConfirmedAt, v.PaygOffConfirmedAt = r.Harness, r.Upstream, r.Billing, r.Model, r.LimitConfirmedAt, r.PaygOffConfirmedAt
+ if b, ok := budgetOf(r); ok {
+ // The budget a connection was made with rides its connect
+ // frame; a change after is pending until the runner applies it.
+ v.Budget, v.BudgetPending = &b, b.Revision > r.BudgetApplied && r.State != wire.ConnConnecting
+ }
+ if r.Spend != "" {
+ v.Spend = &wire.Spend{}
+ if json.Unmarshal([]byte(r.Spend), v.Spend) != nil {
+ v.Spend = nil
+ }
+ }
+ }
return v
}
+// budgetOf is the budget the person set on a metered connection.
+func budgetOf(r connectionRecord) (wire.Budget, bool) {
+ var b wire.Budget
+ if r.Budget == "" || json.Unmarshal([]byte(r.Budget), &b) != nil {
+ return b, false
+ }
+ return b, true
+}
+
func asJSON(v any) string {
if v == nil {
return ""
@@ -135,7 +180,7 @@ func (t *txn) saveConnection(r *connectionRecord, fresh bool) error {
r.CreatedAt = r.UpdatedAt
err = t.db.Create(r).Error
} else {
- 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").Updates(r).Error
+ 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").Updates(r).Error
}
if err != nil {
return err
@@ -191,13 +236,16 @@ func (t *txn) helloConnections(l Lease, held []wire.HeldConnection) error {
continue
}
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}
+ heldMetered(&r, h)
if err := t.saveConnection(&r, true); err != nil {
return err
}
continue
}
r := rows[i]
- changed := r.State != h.State || r.Label != h.Label || r.Plan != h.Plan || r.Reason != "" || !sameTime(r.ExpiresAt, h.ExpiresAt) || r.ExpiresEstimated != h.ExpiresEstimated
+ was := r
+ heldMetered(&r, h)
+ 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
if !changed && r.Headroom == headroom {
continue
}
@@ -220,6 +268,22 @@ func (t *txn) helloConnections(l Lease, held []wire.HeldConnection) error {
return nil
}
+// heldMetered copies an API-key connection's facts from the runner's
+// hello: what it reports is what it holds. The person's budget is kept
+// as they set it; the runner's revision says how far it applied.
+func heldMetered(r *connectionRecord, h wire.HeldConnection) {
+ if h.Kind != wire.KindAPIKey {
+ return
+ }
+ r.Harness, r.Upstream, r.Billing, r.Model, r.Spend = h.Harness, h.Upstream, h.Billing, h.Model, asJSON(h.Spend)
+ if h.Budget != nil {
+ if r.Budget == "" {
+ r.Budget = asJSON(h.Budget)
+ }
+ r.BudgetApplied = max(r.BudgetApplied, h.Budget.Revision)
+ }
+}
+
// connectionReport applies the runner's word on one of its person's
// connection attempts.
func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error {
@@ -262,11 +326,20 @@ func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error {
r.Headroom = asJSON(v.Headroom)
}
if v.Prompt != nil {
+ if len(v.Prompt.Models) > wire.MaxModels || slices.ContainsFunc(v.Prompt.Models, func(m string) bool { return m == "" || len(m) > wire.MaxModelName }) {
+ return ErrInvalid
+ }
r.Prompt = asJSON(v.Prompt)
}
if v.State != wire.ConnConnecting {
r.Prompt = ""
}
+ if v.State == wire.ConnHealthy && r.Kind == wire.KindAPIKey {
+ // Made with the budget its connect frame carried.
+ if b, ok := budgetOf(r); ok {
+ r.BudgetApplied = max(r.BudgetApplied, b.Revision)
+ }
+ }
if v.State == wire.ConnHealthy && r.Kind == wire.KindToken && r.ExpiresAt == nil {
// An estimate until the runner's hello says what it knows: a
// setup token lasts about a year from when it was made.
@@ -450,8 +523,11 @@ func (s *Store) Connection(ctx context.Context, person, id string) (out wire.Con
// can read passes through it either way. A second attempt for the same
// provider while one is connecting returns that one.
func (s *Store) StartConnection(ctx context.Context, person string, in wire.Connect) (out wire.Connection, err error) {
+ if in.Kind == wire.KindAPIKey {
+ return s.startAPIKey(ctx, person, in)
+ }
token := in.Kind == wire.KindToken
- if in.Provider != wire.ProviderClaude && in.Provider != wire.ProviderCodex || in.Kind != "" && in.Kind != wire.KindSubscription && !token || token && in.Provider != wire.ProviderClaude || in.SameMachine {
+ 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 {
return out, ErrInvalid
}
err = s.tx(ctx, func(t *txn) error {
@@ -610,8 +686,19 @@ func (s *Store) SendSecret(ctx context.Context, person, id string, in wire.Seale
}
// The card waits for the runner: no link until it asks again.
r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptAuthorize, Attempt: in.Attempt})
+ } else if r.Kind == wire.KindAPIKey {
+ // An API key, bound to its provider's origin (connectors
+ // spec §2.2); the card waits for the runner's model list.
+ if kp, ok := wire.APIKeyProviders[r.Provider]; !ok || in.Endpoint != kp.Endpoint || in.Attempt != 1 {
+ return ErrInvalid
+ }
+ p := promptOf(r)
+ if r.State != wire.ConnConnecting || p == nil || p.Kind != wire.PromptAPIKey {
+ return ErrConflict
+ }
+ r.Prompt = ""
} else {
- if r.Kind != wire.KindToken {
+ if r.Kind != wire.KindToken || in.Endpoint != wire.EndpointAnthropic {
return ErrInvalid
}
if r.State != wire.ConnConnecting || r.Prompt == "" {
@@ -630,9 +717,11 @@ func (s *Store) SendSecret(ctx context.Context, person, id string, in wire.Seale
// sealedShape checks what can be checked of a box without opening it.
func sealedShape(in wire.Sealed, now time.Time) bool {
- token := in.Endpoint == wire.EndpointAnthropic && in.Attempt == 1
- code := in.Endpoint == wire.EndpointClaudeCode && in.Attempt >= 1 && in.Attempt <= wire.MaxCodeAttempts
- if in.Provider != wire.ProviderClaude || !token && !code || len(in.Box) > wire.MaxSealedBytes {
+ token := in.Provider == wire.ProviderClaude && in.Endpoint == wire.EndpointAnthropic && in.Attempt == 1
+ code := in.Provider == wire.ProviderClaude && in.Endpoint == wire.EndpointClaudeCode && in.Attempt >= 1 && in.Attempt <= wire.MaxCodeAttempts
+ kp, apiKey := wire.APIKeyProviders[in.Provider]
+ apiKey = apiKey && in.Endpoint == kp.Endpoint && in.Attempt == 1
+ if !token && !code && !apiKey || len(in.Box) > wire.MaxSealedBytes {
return false
}
// The runner allows a minute of clock skew past the TTL; so does this.
@@ -687,10 +776,10 @@ var usageOutcomes = map[string]bool{wire.OutcomeReplied: true, wire.OutcomeFaile
func (t *txn) recordUsage(protocol int, person, role, task, step, turn string, round int, rows []wire.Usage) error {
settle := map[int64]bool{}
for _, u := range rows {
- if !usageOutcomes[u.Outcome] || u.Attempt < 1 || len(u.Model) > 200 || len(u.Connection) > 200 || u.Turns != nil && *u.Turns < 0 {
+ 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 {
return ErrInvalid
}
- r := usageRecord{Person: person, 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"), RecordedAt: t.now()}
+ r := usageRecord{Person: person, 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, RecordedAt: t.now()}
if err := t.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&r).Error; err != nil {
return err
}
@@ -746,7 +835,14 @@ func (t *txn) usageReport(l Lease, v *wire.UsageReport) error {
return err
}
return t.recordUsage(l.Protocol, person, "ask", q.TaskID, q.ID, "", round, v.Rows)
- case v.CheckID != "" && v.TurnID == "" && v.StepID == "" && v.QuestionID == "":
+ case v.ProbeID != "" && v.CheckID == "" && v.TurnID == "" && v.StepID == "" && v.QuestionID == "":
+ // A metered connection's probe: one billable token on its model,
+ // charged like any other attempt (connectors spec §2.2).
+ if len(v.ProbeID) > 200 {
+ return ErrInvalid
+ }
+ return t.recordUsage(l.Protocol, person, wire.UsageProbe, "", v.ProbeID, "", 0, v.Rows)
+ case v.CheckID != "" && v.ProbeID == "" && v.TurnID == "" && v.StepID == "" && v.QuestionID == "":
// A token connection's health check: a real request on the
// person's own connection, keyed by the check so each counts.
if len(v.CheckID) > 200 {
@@ -967,7 +1063,7 @@ func (s *Store) ConnectionRowFacts(ctx context.Context, person string, grace tim
out.Stated[r.ID] = r.StatedEmail
}
var served []string
- if err := tx.Raw("SELECT DISTINCT connection FROM chat_usage WHERE person = ? AND role <> 'check' AND outcome = ? AND recorded_at < ?", person, wire.OutcomeReplied, servedBefore).Scan(&served).Error; err != nil {
+ if err := tx.Raw("SELECT DISTINCT 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 {
return err
}
for _, c := range served {
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index 5e4e02bb..19a2af50 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -102,6 +102,9 @@ func (h *HTTP) Mount(r chi.Router) {
r.Delete("/connections/{id}", h.thinOr("DELETE /connections/{id}", thinConnection, h.bearer(h.signOut)))
r.Post("/connections/{id}/forget", h.bearer(h.forget))
r.Post("/connections/{id}/check", h.bearer(h.checkConnection))
+ r.Post("/connections/{id}/model", h.bearer(h.chooseModel))
+ r.Put("/connections/{id}/budget", h.bearer(h.setBudget))
+ r.Post("/connections/{id}/resume", h.bearer(h.resumeSpend))
r.Get("/thinking", h.bearer(h.thinking))
r.Put("/thinking", h.bearer(h.setThinking))
r.Get("/connections/preference", h.bearer(h.preferences))
@@ -245,6 +248,54 @@ func (h *HTTP) secret(w http.ResponseWriter, r *http.Request, p personapi.Person
writeJSON(w, http.StatusAccepted, out)
}
+// chooseModel is POST /api/v1/connections/{id}/model {model}: the
+// connecting card's pick, from the list the runner read.
+func (h *HTTP) chooseModel(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in wire.ChooseModel
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ out, err := h.Store.ChooseModel(r.Context(), p.Address, chi.URLParam(r, "id"), in)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusAccepted, out)
+}
+
+// setBudget is PUT /api/v1/connections/{id}/budget {day, month,
+// revision}: 202, applied when the runner confirms (budget_pending until
+// then); 409 when the revision moved.
+func (h *HTTP) setBudget(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in wire.SetBudget
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ out, err := h.Store.SetBudget(r.Context(), p.Address, chi.URLParam(r, "id"), in)
+ if err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ writeJSON(w, http.StatusAccepted, out)
+}
+
+// resumeSpend is POST /api/v1/connections/{id}/resume {pause_revision}:
+// 202; 409 when that pause is not the connection's now.
+func (h *HTTP) resumeSpend(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
+ var in wire.ResumeSpend
+ if err := readJSON(r, &in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ if err := h.Store.ResumeSpend(r.Context(), p.Address, chi.URLParam(r, "id"), in); err != nil {
+ h.fail(w, r, err)
+ return
+ }
+ w.WriteHeader(http.StatusAccepted)
+}
+
func (h *HTTP) cancelConnection(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
out, err := h.Store.CancelConnection(r.Context(), p.Address, chi.URLParam(r, "id"))
if err != nil {
@@ -311,6 +362,10 @@ func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, err error) {
personapi.WriteError(w, r, 409, "not_askable", nil)
case errors.Is(err, ErrRunnerOffline):
personapi.WriteError(w, r, 409, "runner_offline", nil)
+ case errors.Is(err, ErrConfirmation):
+ personapi.WriteError(w, r, 422, "confirmation_required", nil)
+ case errors.Is(err, ErrRunnerTooOld):
+ personapi.WriteError(w, r, 409, "runner_too_old", nil)
case errors.Is(err, ErrActionConflict):
personapi.WriteError(w, r, 409, "not_undoable", nil)
case errors.Is(err, ErrRevision):
diff --git a/internal/equipo/chat/metered.go b/internal/equipo/chat/metered.go
new file mode 100644
index 00000000..e5b5eef4
--- /dev/null
+++ b/internal/equipo/chat/metered.go
@@ -0,0 +1,239 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// Metered connections on the instance (connectors spec 2026-11-12, S1):
+// an API-key connection is started with its confirmations and budget,
+// its key is sealed in the page to the runner (SendSecret), the person
+// picks its model from the list the runner read, and its budget and
+// Resume go to the runner as durable frames. The runner holds the
+// ledger; the instance shows what it reports.
+
+// ErrConfirmation: an API-key connection without the confirmations its
+// billing needs (§2.1).
+var ErrConfirmation = errors.New("chat: the connection needs its confirmations")
+
+// ErrRunnerTooOld: the person's runner speaks a protocol before metered
+// connections; it is refused one rather than downgraded (§10).
+var ErrRunnerTooOld = errors.New("chat: the runner is too old for this connection")
+
+// runnerProtocol is the protocol the runner last spoke (1 when unknown).
+func (t *txn) runnerProtocol(person, runner string) (int, error) {
+ rs, err := t.runners(person)
+ if err != nil {
+ return 0, err
+ }
+ for _, r := range rs {
+ if r.ID == runner {
+ return r.Protocol, nil
+ }
+ }
+ return wire.Protocol1, nil
+}
+
+// startAPIKey starts an API-key connection attempt on the person's
+// primary runner: the provider from the table, the limit confirmed when
+// it is metered, pay-as-you-go off only for an overflow subscription,
+// and a budget in bounds. The confirmations are recorded with the
+// person, the time and the provider.
+func (s *Store) startAPIKey(ctx context.Context, person string, in wire.Connect) (out wire.Connection, err error) {
+ kp, ok := wire.APIKeyProviders[in.Provider]
+ if !ok || in.SameMachine {
+ return out, ErrInvalid
+ }
+ if err := kp.CheckConfirmations(in.LimitConfirmed, in.PaygOffConfirmed); err != nil {
+ return out, ErrConfirmation
+ }
+ if in.Budget == nil || !wire.ValidBudget(wire.Budget{Day: in.Budget.Day, Month: in.Budget.Month}) {
+ return out, ErrInvalid
+ }
+ budget := wire.Budget{Day: in.Budget.Day, Month: in.Budget.Month, Currency: kp.Currency, Revision: 1}
+ billing := kp.Billing(in.PaygOffConfirmed)
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ runner, err := s.runnerView(t.db, person)
+ if err != nil {
+ return err
+ }
+ if runner.ID == "" || in.RunnerID != "" && in.RunnerID != runner.ID {
+ return ErrNotFound
+ }
+ rows, err := t.connections(person)
+ if err != nil {
+ return err
+ }
+ for _, r := range rows {
+ if r.State == wire.ConnConnecting && r.Provider == in.Provider && r.RunnerID == runner.ID {
+ out = connectionView(r)
+ return nil
+ }
+ }
+ if !runner.Online {
+ return ErrRunnerOffline
+ }
+ if proto, err := t.runnerProtocol(person, runner.ID); err != nil {
+ return err
+ } else if proto < wire.ProtocolMetered {
+ return ErrRunnerTooOld
+ }
+ now := t.now()
+ 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})}
+ if in.LimitConfirmed {
+ r.LimitConfirmedAt = &now
+ }
+ if in.PaygOffConfirmed {
+ r.PaygOffConfirmedAt = &now
+ }
+ if err := t.saveConnection(&r, true); err != nil {
+ return err
+ }
+ // The confirmations are kept on the record (saveConnection writes
+ // only what a later change may change).
+ 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 {
+ return err
+ }
+ out = connectionView(r)
+ 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})
+ })
+ return out, err
+}
+
+// ownConnection reads one of the person's connections in t.
+func (t *txn) ownConnection(person, id string) (connectionRecord, error) {
+ var r connectionRecord
+ err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return r, ErrNotFound
+ }
+ return r, err
+}
+
+// ChooseModel is the person's pick of a connecting API-key connection's
+// one model, from the list its runner read (a second model is a second
+// connection). The card waits for the runner's probe after it.
+func (s *Store) ChooseModel(ctx context.Context, person, id string, in wire.ChooseModel) (out wire.Connection, err error) {
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ r, err := t.ownConnection(person, id)
+ if err != nil {
+ return err
+ }
+ p := promptOf(r)
+ if r.Kind != wire.KindAPIKey {
+ return ErrInvalid
+ }
+ if r.State != wire.ConnConnecting || p == nil || p.Kind != wire.PromptModel || len(p.Models) == 0 {
+ return ErrConflict
+ }
+ if !slices.Contains(p.Models, in.Model) {
+ return ErrInvalid
+ }
+ r.Model, r.Prompt = in.Model, asJSON(wire.ConnectPrompt{Kind: wire.PromptModel})
+ if err := t.saveConnection(&r, false); err != nil {
+ return err
+ }
+ out = connectionView(r)
+ return t.commandTo(r.RunnerID, person, wire.FrameModel, wire.ModelCommand{Connection: r.ID, Person: person, Model: in.Model})
+ })
+ return out, err
+}
+
+// meteredConnection is one of the person's API-key connections the
+// runner holds (made, not signed out).
+func (t *txn) meteredConnection(person, id string) (connectionRecord, error) {
+ r, err := t.ownConnection(person, id)
+ if err != nil {
+ return r, err
+ }
+ if r.Kind != wire.KindAPIKey {
+ return r, ErrInvalid
+ }
+ if r.LocalID == "" || r.State == wire.ConnSignedOut || r.State == wire.ConnConnecting {
+ return r, ErrConflict
+ }
+ return r, nil
+}
+
+// SetBudget changes a metered connection's budget against the revision
+// the person saw (ErrConflict when it moved). It takes effect when the
+// runner applies the durable budget frame; until its ack the connection
+// says the budget is pending. A running step is not stopped.
+func (s *Store) SetBudget(ctx context.Context, person, id string, in wire.SetBudget) (out wire.Connection, err error) {
+ err = s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ r, err := t.meteredConnection(person, id)
+ if err != nil {
+ return err
+ }
+ b, _ := budgetOf(r)
+ if in.Revision != b.Revision {
+ return ErrConflict
+ }
+ next := wire.Budget{Day: in.Day, Month: in.Month, Currency: b.Currency, Revision: b.Revision + 1}
+ if !wire.ValidBudget(next) {
+ return ErrInvalid
+ }
+ r.Budget = asJSON(next)
+ if err := t.saveConnection(&r, false); err != nil {
+ return err
+ }
+ out = connectionView(r)
+ return t.commandTo(r.RunnerID, person, wire.FrameBudget, wire.BudgetCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, Budget: next})
+ })
+ return out, err
+}
+
+// ResumeSpend is the person's Resume of a connection whose spend is
+// unknown, after looking at the provider's dashboard. It is bound to the
+// pause they saw: the runner consumes it once, only while that pause is
+// current, so a stale Resume leaves a newer pause.
+func (s *Store) ResumeSpend(ctx context.Context, person, id string, in wire.ResumeSpend) error {
+ return s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ r, err := t.meteredConnection(person, id)
+ if err != nil {
+ return err
+ }
+ var spend wire.Spend
+ if r.Spend == "" || json.Unmarshal([]byte(r.Spend), &spend) != nil || !spend.Unknown || spend.PauseRevision != in.PauseRevision {
+ return ErrConflict
+ }
+ return t.commandTo(r.RunnerID, person, wire.FrameResumeSpend, wire.ResumeSpendCommand{Connection: r.ID, Person: person, LocalID: r.LocalID, PauseRevision: in.PauseRevision})
+ })
+}
+
+// budgetAcked records that the runner applied a budget frame: the page
+// stops saying it is pending.
+func (t *txn) budgetAcked(body string) error {
+ var cmd wire.BudgetCommand
+ if err := json.Unmarshal([]byte(body), &cmd); err != nil {
+ return err
+ }
+ var r connectionRecord
+ if err := t.db.Where("id = ? AND person = ?", cmd.Connection, cmd.Person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ } else if err != nil {
+ return err
+ }
+ if cmd.Budget.Revision <= r.BudgetApplied {
+ return nil
+ }
+ r.BudgetApplied = cmd.Budget.Revision
+ return t.saveConnection(&r, false)
+}
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go
index 69c6d5e8..db3d7e30 100644
--- a/internal/equipo/chat/questions.go
+++ b/internal/equipo/chat/questions.go
@@ -418,7 +418,18 @@ func (t *txn) answer(l Lease, v *wire.AnswerReport) error {
if q.State == wire.QuestionRunning {
return nil
}
- q.State = wire.QuestionRunning
+ q.State, q.Reason = wire.QuestionRunning, ""
+ return t.saveQuestion(&q)
+ case wire.QuestionQueued:
+ // Held by its metered connection's guard (connectors spec §7):
+ // it waits on that connection, never moved; the reason says why.
+ if v.Reason != wire.HoldBusy && v.Reason != wire.HoldBudget && v.Reason != wire.HoldSpendUnknown {
+ return ErrInvalid
+ }
+ if q.State != wire.QuestionQueued || q.Reason == v.Reason {
+ return nil
+ }
+ q.Reason = v.Reason
return t.saveQuestion(&q)
case wire.QuestionAnswered:
answer := strings.TrimSpace(v.Text)
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index e80f1150..7cbdf9c2 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -363,6 +363,9 @@ func (t *txn) ack(l Lease, id string) error {
if c.Kind == wire.FrameBlob {
return t.blobAcked(c.Body)
}
+ if c.Kind == wire.FrameBudget {
+ return t.budgetAcked(c.Body)
+ }
if c.Kind == wire.FrameSecret {
// The runner holds the secret now: the box leaves the mailbox
// (only WAL and backup residue can remain, spec §2.4).
diff --git a/internal/equipo/migrations/0068_thin_metered_connections.sql b/internal/equipo/migrations/0068_thin_metered_connections.sql
new file mode 100644
index 00000000..bcd7740b
--- /dev/null
+++ b/internal/equipo/migrations/0068_thin_metered_connections.sql
@@ -0,0 +1,13 @@
+ALTER TABLE chat_connections ADD COLUMN harness text;
+ALTER TABLE chat_connections ADD COLUMN upstream text;
+ALTER TABLE chat_connections ADD COLUMN billing text;
+ALTER TABLE chat_connections ADD COLUMN model text;
+ALTER TABLE chat_connections ADD COLUMN limit_confirmed_at datetime;
+ALTER TABLE chat_connections ADD COLUMN payg_off_confirmed_at datetime;
+ALTER TABLE chat_connections ADD COLUMN budget text;
+ALTER TABLE chat_connections ADD COLUMN budget_applied integer;
+ALTER TABLE chat_connections ADD COLUMN spend text;
+ALTER TABLE chat_usage ADD COLUMN cost_micros integer;
+ALTER TABLE chat_usage ADD COLUMN currency text;
+ALTER TABLE chat_usage ADD COLUMN price_version text;
+ALTER TABLE chat_usage ADD COLUMN cost_reported_micros integer;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 936b8b9b..e5f728cd 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -607,9 +607,9 @@ CREATE TABLE chat_task_distinct (a text, b text, created_at datetime, PRIMARY KE
CREATE TABLE chat_questions (id text PRIMARY KEY, task_id text, asker text, idempotency_key text, step_id text, specialist text, chosen text, text text, state text, reason text, attempt integer, dispatched numeric, answer text, timing text, revision integer, created_at datetime, updated_at datetime);
CREATE INDEX chat_question_task ON chat_questions(task_id);
CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key);
-CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime, expires_at datetime, expires_estimated numeric, stated_email text);
+CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime, expires_at datetime, expires_estimated numeric, stated_email text, harness text, upstream text, billing text, model text, limit_confirmed_at datetime, payg_off_confirmed_at datetime, budget text, budget_applied integer, spend text);
CREATE INDEX chat_connection_person ON chat_connections(person);
-CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, outcome text, complete numeric, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime, round integer, turns integer, overcount numeric);
+CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, outcome text, complete numeric, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime, round integer, turns integer, overcount numeric, cost_micros integer, currency text, price_version text, cost_reported_micros integer);
CREATE INDEX chat_usage_person ON chat_usage(person, recorded_at);
CREATE UNIQUE INDEX chat_usage_key ON chat_usage(turn_id, step_id, attempt, connection, model);
CREATE INDEX chat_tool_call_turn ON chat_tool_calls(turn_id, op);
diff --git a/internal/thintest/client.go b/internal/thintest/client.go
index f2098c2d..e73f67c4 100644
--- a/internal/thintest/client.go
+++ b/internal/thintest/client.go
@@ -305,6 +305,21 @@ func (c *Client) Secret(ctx context.Context, id string, in wire.Sealed) (out wir
return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/secret", in, &out)
}
+// ChooseModel picks a connecting API-key connection's model.
+func (c *Client) ChooseModel(ctx context.Context, id, model string) (out wire.Connection, err error) {
+ return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/model", wire.ChooseModel{Model: model}, &out)
+}
+
+// SetBudget changes a metered connection's budget.
+func (c *Client) SetBudget(ctx context.Context, id string, in wire.SetBudget) (out wire.Connection, err error) {
+ return out, c.do(ctx, "PUT", "/api/v1/connections/"+id+"/budget", in, &out)
+}
+
+// ResumeSpend resumes a connection paused with its spend unknown.
+func (c *Client) ResumeSpend(ctx context.Context, id string, pause int64) error {
+ return c.do(ctx, "POST", "/api/v1/connections/"+id+"/resume", wire.ResumeSpend{PauseRevision: pause}, nil)
+}
+
// Stream is one open SSE connection.
type Stream struct {
Events <-chan wire.Event
diff --git a/internal/thintest/metered_contract_test.go b/internal/thintest/metered_contract_test.go
new file mode 100644
index 00000000..a4903d75
--- /dev/null
+++ b/internal/thintest/metered_contract_test.go
@@ -0,0 +1,249 @@
+package thintest
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/sealbox"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// canaryKey is an obviously fake TensorX key: sealed in the test, never
+// seen by the instance.
+const canaryKey = "tx-CANARY-not-a-real-key-CANARY"
+
+// TestContractMeteredConnection (connectors spec S1, §§2.1 to 2.3, §10):
+// an API-key connection is refused without its confirmations or its
+// budget and on a runner before protocol 12; with them it goes to the
+// runner as connect (kind api_key, billing, budget); its key is sealed
+// to the runner and bound to TensorX's origin; the person picks the
+// model from the runner's list; the probe's usage is recorded with role
+// probe and its cost; hello brings the budget and spend; a budget change
+// is pending until the runner acks its frame; Resume is bound to the
+// pause it saw. The canary key appears nowhere the instance can read.
+func TestContractMeteredConnection(t *testing.T) {
+ budget := &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth}
+ good := wire.Connect{Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: budget}
+ // An older runner is refused a metered connection, not downgraded.
+ {
+ old := newRig(t)
+ runner := dialAt(t, old, wire.ProtocolPreviewHost)
+ hello := primaryAt(held(), wire.ProtocolPreviewHost)
+ hello.Generation, hello.SealKey = runner.Welcome.Generation, sealKeys(t).PublicString()
+ if err := runner.Send(old.ctx, "h1", wire.FrameHello, hello); err != nil {
+ t.Fatal(err)
+ }
+ old.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
+ if _, err := old.client.Connect(old.ctx, good); Status(err) != 409 {
+ t.Fatalf("a protocol 11 runner: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(old.ctx, 300*time.Millisecond)
+ if f, _, _ := runner.Expect(ctx, wire.FrameConnect); f.Type == wire.FrameConnect {
+ t.Fatal("a protocol 11 runner was sent a connect")
+ }
+ cancel()
+ }
+ r := newRig(t)
+ keys := sealKeys(t)
+ runner := dialAt(t, r, wire.ProtocolMetered)
+ hello := primaryAt(held(), wire.ProtocolMetered)
+ hello.Generation, hello.SealKey = runner.Welcome.Generation, keys.PublicString()
+ if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
+ var runnerID string
+ waitFor(t, "the runner listed", func() bool {
+ list, err := r.client.Runners(r.ctx)
+ if err != nil || len(list.Items) != 1 {
+ return false
+ }
+ runnerID = list.Items[0].ID
+ return true
+ })
+ for name, bad := range map[string]wire.Connect{
+ "no limit confirmation": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Budget: budget},
+ "pay-as-you-go off on a per-token provider": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, PaygOffConfirmed: true, Budget: budget},
+ "no budget": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true},
+ "a day over a month": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: &wire.Budget{Day: 5, Month: 4}},
+ "an unknown provider": {Provider: "elsewhere", Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: budget},
+ "a confirmation on a subscription": {Provider: "codex", Kind: wire.KindSubscription, LimitConfirmed: true},
+ } {
+ if _, err := r.client.Connect(r.ctx, bad); Status(err) != 422 {
+ t.Fatalf("%s: %v", name, err)
+ }
+ }
+ attempt, err := r.client.Connect(r.ctx, good)
+ if err != nil || attempt.State != wire.ConnConnecting || attempt.Kind != wire.KindAPIKey || attempt.Prompt == nil || attempt.Prompt.Kind != wire.PromptAPIKey || attempt.Billing != wire.BillingMetered || attempt.Harness != wire.HarnessPi || attempt.Upstream != "https://api.tensorx.ai" || attempt.LimitConfirmedAt == nil || attempt.PaygOffConfirmedAt != nil {
+ t.Fatalf("attempt %+v %v", attempt, err)
+ }
+ f, body, err := runner.Expect(r.ctx, wire.FrameConnect)
+ if err != nil {
+ t.Fatal(err)
+ }
+ shape(t, "frames/connect-api-key.json", runner.Received[len(runner.Received)-1])
+ if cmd := body.(*wire.ConnectCommand); cmd.Connection != attempt.ID || cmd.Kind != wire.KindAPIKey || cmd.Provider != wire.ProviderTensorX || cmd.Billing != wire.BillingMetered || cmd.Budget == nil || cmd.Budget.Day != wire.DefaultBudgetDay || cmd.Budget.Currency != "USD" || cmd.Budget.Revision != 1 {
+ t.Fatalf("connect %+v", cmd)
+ }
+ runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID})
+
+ // The key, sealed to the runner and bound to TensorX's origin.
+ endpoint := wire.APIKeyProviders[wire.ProviderTensorX].Endpoint
+ expires := time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second)
+ sealed, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: canaryKey, RunnerID: runnerID, ConnectionID: attempt.ID, Provider: wire.ProviderTensorX, Endpoint: endpoint, Attempt: 1, ExpiresAt: expires})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for name, change := range map[string]func(*wire.Sealed){
+ "Claude's endpoint": func(s *wire.Sealed) { s.Endpoint = wire.EndpointAnthropic },
+ "Claude": func(s *wire.Sealed) { s.Provider = wire.ProviderClaude },
+ "attempt 2": func(s *wire.Sealed) { s.Attempt = 2 },
+ } {
+ bad := sealed
+ change(&bad)
+ if _, err := r.client.Secret(r.ctx, attempt.ID, bad); Status(err) != 422 {
+ t.Fatalf("%s: %v", name, err)
+ }
+ }
+ if posted, err := r.client.Secret(r.ctx, attempt.ID, sealed); err != nil || posted.Prompt != nil {
+ t.Fatalf("secret %+v %v", posted, err)
+ }
+ f, body, err = runner.Expect(r.ctx, wire.FrameSecret)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if opened, err := keys.Open(body.(*wire.SecretCommand).Sealed, time.Now()); err != nil || opened.Secret != canaryKey || opened.Endpoint != endpoint {
+ t.Fatalf("the runner could not open the box: %v", err)
+ }
+ runner.Send(r.ctx, "a-secret", wire.FrameAck, wire.Ack{ID: f.ID})
+
+ // The runner's model list; the person picks one of them.
+ if _, err := r.client.ChooseModel(r.ctx, attempt.ID, "z-ai/glm-5.3"); Status(err) != 409 {
+ t.Fatalf("a model before the list: %v", err)
+ }
+ runner.Send(r.ctx, "r-models", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: wire.ProviderTensorX, State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptModel, Models: []string{"moonshotai/kimi-k3.1-pro", "z-ai/glm-5.3"}}})
+ r.wait("the model card", func(c *Conversation) bool {
+ p := c.Connections[attempt.ID].Prompt
+ return p != nil && p.Kind == wire.PromptModel && len(p.Models) == 2
+ })
+ got, _ := r.client.Connection(r.ctx, attempt.ID)
+ shape(t, "api/connection-choose-model.json", got)
+ if _, err := r.client.ChooseModel(r.ctx, attempt.ID, "vendor/unlisted"); Status(err) != 422 {
+ t.Fatalf("an unlisted model: %v", err)
+ }
+ if picked, err := r.client.ChooseModel(r.ctx, attempt.ID, "z-ai/glm-5.3"); err != nil || picked.Model != "z-ai/glm-5.3" || len(picked.Prompt.Models) != 0 {
+ t.Fatalf("picked %+v %v", picked, err)
+ }
+ f, body, err = runner.Expect(r.ctx, wire.FrameModel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ shape(t, "frames/model.json", runner.Received[len(runner.Received)-1])
+ if cmd := body.(*wire.ModelCommand); cmd.Connection != attempt.ID || cmd.Model != "z-ai/glm-5.3" || cmd.Person != Owner {
+ t.Fatalf("model %+v", cmd)
+ }
+ runner.Send(r.ctx, "a-model", wire.FrameAck, wire.Ack{ID: f.ID})
+
+ // The probe: healthy, its usage charged with role probe.
+ cost, in, out := int64(21), int64(9), int64(1)
+ probe := wire.UsageReport{ProbeID: "pr_" + attempt.ID, Rows: []wire.Usage{{Provider: wire.ProviderTensorX, Connection: "tensorx-1", Model: "z-ai/glm-5.3", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &in, OutputTokens: &out, CostMicros: &cost, Currency: "USD", PriceVersion: "tensorx-2026-11-12"}}}
+ for i := 0; i < 2; i++ {
+ // Resent: recorded once.
+ if err := runner.Send(r.ctx, "r-probe", wire.FrameUsage, probe); err != nil {
+ t.Fatal(err)
+ }
+ }
+ runner.Send(r.ctx, "r-healthy", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: wire.ProviderTensorX, LocalID: "tensorx-1", State: wire.ConnHealthy})
+ metered := wire.HeldConnection{LocalID: "tensorx-1", Person: Owner, Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth, Currency: "USD", Revision: 1}, Spend: &wire.Spend{Day: 21, Month: 21, Currency: "USD"}}
+ hello.Connections = []wire.HeldConnection{metered}
+ runner.Send(r.ctx, "h3", wire.FrameHello, hello)
+ r.wait("healthy with its spend", func(c *Conversation) bool {
+ v := c.Connections[attempt.ID]
+ return v.State == wire.ConnHealthy && v.Spend != nil && v.Spend.Day == 21 && v.Model == "z-ai/glm-5.3"
+ })
+ var rows int
+ var role string
+ var charged int64
+ if err := r.inst.DB.Writer().QueryRow("SELECT count(*), max(role), max(cost_micros) FROM chat_usage WHERE step_id = ?", "pr_"+attempt.ID).Scan(&rows, &role, &charged); err != nil || rows != 1 || role != wire.UsageProbe || charged != 21 {
+ t.Fatalf("probe usage: %d %s %d %v", rows, role, charged, err)
+ }
+
+ // A budget change: pending until the runner acks the frame.
+ if _, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 2_000_000, Month: 10_000_000, Revision: 0}); Status(err) != 409 {
+ t.Fatalf("a stale budget revision: %v", err)
+ }
+ if _, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 20_000_000, Month: 10_000_000, Revision: 1}); Status(err) != 422 {
+ t.Fatalf("a day over its month: %v", err)
+ }
+ changed, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 2_000_000, Month: 10_000_000, Revision: 1})
+ if err != nil || !changed.BudgetPending || changed.Budget.Revision != 2 || changed.Budget.Day != 2_000_000 {
+ t.Fatalf("budget %+v %v", changed, err)
+ }
+ shape(t, "api/connection-metered.json", changed)
+ f, body, err = runner.Expect(r.ctx, wire.FrameBudget)
+ if err != nil {
+ t.Fatal(err)
+ }
+ shape(t, "frames/budget.json", runner.Received[len(runner.Received)-1])
+ if cmd := body.(*wire.BudgetCommand); cmd.LocalID != "tensorx-1" || cmd.Budget.Revision != 2 || cmd.Budget.Currency != "USD" {
+ t.Fatalf("budget frame %+v", cmd)
+ }
+ runner.Send(r.ctx, "a-budget", wire.FrameAck, wire.Ack{ID: f.ID})
+ r.wait("the budget applied", func(c *Conversation) bool {
+ v := c.Connections[attempt.ID]
+ return !v.BudgetPending && v.Budget != nil && v.Budget.Revision == 2
+ })
+
+ // Resume is bound to the pause the person saw.
+ if err := r.client.ResumeSpend(r.ctx, attempt.ID, 3); Status(err) != 409 {
+ t.Fatalf("a resume with nothing paused: %v", err)
+ }
+ metered.Spend = &wire.Spend{Day: 21, Month: 21, Currency: "USD", Unknown: true, PauseRevision: 3}
+ metered.Budget = &wire.Budget{Day: 2_000_000, Month: 10_000_000, Currency: "USD", Revision: 2}
+ hello.Connections = []wire.HeldConnection{metered}
+ runner.Send(r.ctx, "h4", wire.FrameHello, hello)
+ r.wait("spend unknown", func(c *Conversation) bool {
+ v := c.Connections[attempt.ID]
+ return v.Spend != nil && v.Spend.Unknown
+ })
+ if err := r.client.ResumeSpend(r.ctx, attempt.ID, 2); Status(err) != 409 {
+ t.Fatalf("a stale resume: %v", err)
+ }
+ if err := r.client.ResumeSpend(r.ctx, attempt.ID, 3); err != nil {
+ t.Fatal(err)
+ }
+ _, body, err = runner.Expect(r.ctx, wire.FrameResumeSpend)
+ if err != nil {
+ t.Fatal(err)
+ }
+ shape(t, "frames/resume_spend.json", runner.Received[len(runner.Received)-1])
+ if cmd := body.(*wire.ResumeSpendCommand); cmd.PauseRevision != 3 || cmd.LocalID != "tensorx-1" {
+ t.Fatalf("resume frame %+v", cmd)
+ }
+
+ // The key is nowhere on the instance.
+ var found int
+ for _, q := range []string{"SELECT count(*) FROM runner_commands WHERE body LIKE ?", "SELECT count(*) FROM chat_connections WHERE coalesce(prompt,'') || coalesce(budget,'') || coalesce(spend,'') LIKE ?", "SELECT count(*) FROM chat_events WHERE body LIKE ?"} {
+ var n int
+ if err := r.inst.DB.Writer().QueryRow(q, "%"+canaryKey+"%").Scan(&n); err != nil && !strings.Contains(err.Error(), "no such") {
+ t.Fatal(err)
+ }
+ found += n
+ }
+ if found != 0 {
+ t.Fatalf("the key is on the instance (%d)", found)
+ }
+}
+
+// dialAt connects a fake runner whose first hello speaks protocol.
+func dialAt(t *testing.T, r *rig, protocol int) *FakeRunner {
+ t.Helper()
+ f, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, primaryAt(held(), protocol))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(f.Close)
+ return f
+}