package thin import ( "context" "crypto/rand" "database/sql" "encoding/json" "errors" "path/filepath" "slices" "time" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" ) // API-key connections (connectors spec 2026-11-12, §2.2, slice S1). The // person pastes a provider key (TensorX); the page seals it to this // runner as a Claude token is sealed, and it is delivered the same way // (Secret, keep) into the connection's own home, 0600. The runner, never // a namespace, reads the provider's model list with it; the person picks // the one model from those Equipo can price; a one-token completion on // that model, admitted through the metered guard and charged like any // other attempt (a usage row with role probe), makes the connection // healthy. The connection lives in thin.db (metered.Conn), not in the // bindings file: no Claude or Codex launch can ever be given it. // errHeld: the metered guard held the probe. var errHeld = errors.New("the connection's guard held the probe") // apiClient is the provider's API at its origin from the table (a test // points origin at a fake server on 127.0.0.1). func (c *Connector) apiClient(prov string) (connect.APIClient, bool) { kp, ok := wire.APIKeyProviders[prov] if !ok { return connect.APIClient{}, false } origin := kp.Upstream if c.origin != nil { origin = c.origin(prov) } return connect.APIClient{HTTP: c.http, Origin: origin, Path: kp.APIPath, ModelsPath: kp.ModelsPath}, true } // meter is the runner's metered guard (nil: no metered connection can be // added). func (c *Connector) meter() *metered.Meter { if c.Conns == nil { return nil } return c.Conns.Meter } // meteredHome reports whether a validated metered connection keeps its // key in home: such a home is deleted only by its sign-out. func (c *Connector) meteredHome(home string) bool { var n int _ = c.State.db.QueryRow("SELECT count(*) FROM metered_connections WHERE home=? AND validated=1", home).Scan(&n) return n > 0 } // attemptExtra is what an API-key attempt recorded beside its row: its // billing and budget from the connect frame and the model picked. func (c *Connector) attemptExtra(ctx context.Context, id string) (billing string, budget wire.Budget, model string, err error) { var raw string err = c.State.db.QueryRowContext(ctx, "SELECT billing, budget, model FROM connect_attempts WHERE id=?", id).Scan(&billing, &raw, &model) if err == nil && raw != "" { err = json.Unmarshal([]byte(raw), &budget) } return billing, budget, model, err } // attemptAllowed is the allowed set the person sent for a connecting // attempt and its revision: the models frame's (ProtocolModels), else // S1's one model from an older instance's model frame, as a set of one // at revision 1. func (c *Connector) attemptAllowed(ctx context.Context, id string) ([]string, int64, error) { var raw, model string if err := c.State.db.QueryRowContext(ctx, "SELECT allowed, model FROM connect_attempts WHERE id=?", id).Scan(&raw, &model); err != nil { return nil, 0, err } if raw != "" { var set wire.ModelsCommand if err := json.Unmarshal([]byte(raw), &set); err != nil { return nil, 0, err } return set.Allowed, set.Revision, nil } if model != "" { return []string{model}, 1, nil } return nil, 0, nil } // runAPIKey is an API-key attempt: the card asking for the key, the wait // for its sealed box, the model list, the card asking for the model, the // probe, then the healthy report. A restart picks it up where it was. func (c *Connector) runAPIKey(ctx context.Context, cmd wire.ConnectCommand, base wire.ConnectionReport) { failed := func(home, reason string) { c.failAPIKey(cmd, home, reason) } kp, known := wire.APIKeyProviders[cmd.Provider] m := c.meter() billing, budget, _, err := c.attemptExtra(ctx, cmd.Connection) if !known || m == nil || err != nil || billing != wire.BillingMetered && billing != wire.BillingSubscription || !wire.ValidBudget(budget) { failed("", "provider_refused") return } table, priced := metered.TableFor(metered.Current[cmd.Provider]) wake := c.waitFor(cmd.Connection) defer c.stopWaiting(cmd.Connection) home, err := c.tokenHome(ctx, cmd.Connection) if err != nil { c.log("connect home", err) failed(home, "provider_refused") return } local := filepath.Base(home) a, _, err := c.attempt(ctx, cmd.Connection) if err == nil && a.secret == "" { r := base r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptAPIKey} c.report(r) } for err == nil && a.secret == "" && a.state == "running" { select { case <-ctx.Done(): failed(home, reasonOf(ctx.Err())) return case <-wake: } a, _, err = c.attempt(ctx, cmd.Connection) } if err != nil || a.state != "running" { if err != nil { failed(home, "provider_refused") } return } if conn, ok, _ := metered.Get(ctx, c.State.db, local); ok && conn.Validated { // Made before a stop: it stands. c.finishAPIKey(cmd, local, conn) return } key, err := provider.ReadToken(home) if err != nil { failed(home, "provider_refused") return } defer clear(key) api, _ := c.apiClient(cmd.Provider) listed, err := api.Models(ctx, key) if err != nil { c.log("connect api key", err) failed(home, refusal(ctx, err)) return } // Every model the key lists, each saying whether it can be allowed // (priced and tiered); the card ticks those by default (§16.1). var models []string choices := []wire.ModelChoice{} for _, m := range listed { t, _, ok := metered.Eligible(cmd.Provider, table.Version, m) if !priced { ok = false } choices = append(choices, wire.ModelChoice{ID: m, Eligible: ok, Family: t.Family, Tier: t.Tier}) if ok { models = append(models, m) } } if len(models) == 0 { failed(home, "no_priced_model") return } // A card carries at most wire.MaxModels: the ones that can be allowed // first. choices = metered.CapChoices(choices) models = models[:0] for _, c := range choices { if c.Eligible { models = append(models, c.ID) } } shown := false var allowed []string var revision int64 for { if allowed, revision, err = c.attemptAllowed(ctx, cmd.Connection); err != nil { failed(home, "provider_refused") return } if len(allowed) > 0 && !slices.ContainsFunc(allowed, func(m string) bool { return !slices.Contains(models, m) }) { break } if !shown { // An older instance is said the one-model pick (Encode). r := base r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptModels, Choices: choices} c.report(r) shown = true } select { case <-ctx.Done(): failed(home, reasonOf(ctx.Err())) return case <-wake: } } if a, _, err = c.attempt(ctx, cmd.Connection); err != nil || a.cancelled || a.state != "running" { failed(home, reasonOf(firstErr(ctx.Err(), context.Canceled))) return } // The key is proven once, on the cheapest allowed model; every other // allowed model starts unprobed (§16.1). model := metered.Cheapest(cmd.Provider, table.Version, allowed) conn := metered.Conn{Connection: cmd.Connection, LocalID: local, Person: cmd.Person, Provider: cmd.Provider, Harness: kp.Harness, Upstream: kp.Upstream, Billing: billing, Model: model, Home: home, Currency: table.Currency, PriceVersion: table.Version, Budget: wire.Budget{Day: budget.Day, Month: budget.Month, Currency: table.Currency, Revision: budget.Revision}, ModelsRevision: revision} err = c.State.tx(ctx, func(t *sql.Tx) error { if _, ok, err := metered.Get(ctx, t, local); err != nil { return err } else if !ok { if err := metered.Add(ctx, t, conn, time.Now()); err != nil { return err } } else if err := metered.SetModel(ctx, t, local, model); err != nil { return err } if err := metered.SetListed(ctx, t, local, listed); err != nil { return err } return metered.InitModels(ctx, t, local, allowed, revision) }) if err != nil { failed(home, "provider_refused") return } if _, err = c.probe(ctx, conn, model, "pr_"+cmd.Connection, nil); err != nil { c.log("connect probe", err) failed(home, refusal(ctx, err)) return } conn, _, _ = metered.Get(ctx, c.State.db, local) c.finishAPIKey(cmd, local, conn) } // refusal is the reason an attempt ends with after err. func refusal(ctx context.Context, err error) string { switch { case ctx.Err() != nil: return reasonOf(ctx.Err()) case errors.Is(err, connect.ErrKeyRefused): return "key_refused" } return "provider_refused" } // finishAPIKey reports the attempt healthy; one cancelled meanwhile is // signed out instead. func (c *Connector) finishAPIKey(cmd wire.ConnectCommand, local string, conn metered.Conn) { r := wire.ConnectionReport{Connection: cmd.Connection, Person: cmd.Person, Provider: cmd.Provider, State: wire.ConnHealthy, LocalID: local} c.finish(cmd.Connection, r) c.Conns.changed() var cancelled int _ = c.State.db.QueryRow("SELECT cancelled FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&cancelled) if cancelled == 1 { k := cleanup{connection: cmd.Connection, person: cmd.Person, local: local, home: conn.Home, provider: conn.Provider} err := c.State.tx(context.Background(), func(t *sql.Tx) error { return owe(t, k) }) c.log("disconnect record", err) c.settle(k) } } // failAPIKey ends an attempt not yet healthy: its unvalidated metered // record and its home (the key with it) go, then the error report. func (c *Connector) failAPIKey(cmd wire.ConnectCommand, home, reason string) { c.delivery.Lock() defer c.delivery.Unlock() c.endAPIKey(cmd.Connection, cmd.Person, cmd.Provider, home, reason) } // endAPIKey removes an API-key attempt's unvalidated record and home and // reports its end. func (c *Connector) endAPIKey(id, person, prov, home, reason string) { if home != "" { local := filepath.Base(home) err := c.State.tx(context.Background(), func(t *sql.Tx) error { _, err := t.Exec("DELETE FROM metered_connections WHERE local_id=? AND home=? AND validated=0", local, home) return err }) c.log("connect api key", err) c.removeHome(home) } c.finish(id, wire.ConnectionReport{Connection: id, Person: person, Provider: prov, State: wire.ConnError, Reason: reason}) } // probe proves a model with one billable token (§2.2, §16.4), admitted // through the metered guard with the slot claimed (and admit, a step's // scheduler admission, in that same transaction), its usage charged and // reported as a probe's (role probe) under id, the slot released with // the charge or spend_unknown. Its verdict commits with the charge: // answered by that model, the model is healthy and the key proven; a // refused key refuses the connection (no model is marked); the model // not found, or another model answering, makes the model unhealthy; no // usable usage leaves the spend unknown. It runs at connect, on Check // again, and on a model's first use in a step. func (c *Connector) probe(ctx context.Context, conn metered.Conn, model, id string, admit func(*sql.Tx) error) (metered.Admission, error) { m := c.meter() api, ok := c.apiClient(conn.Provider) if m == nil || !ok { return metered.Admission{}, connect.ErrProviderAnswer } // Each execution of a probe id is its own attempt (a durable // sequence): charged and settled as itself, while a resent usage frame // of it stays one charge (security round #2). attempt, err := c.State.nextProbe(ctx, id) if err != nil { return metered.Admission{}, err } var perr error h := metered.Holder{Step: id, Attempt: attempt, Role: metered.RoleProbe, Model: model} adm, _, err := m.RunAdmitted(ctx, conn.LocalID, h, admit, func(ctx context.Context, l metered.Launch) metered.Result { key, err := provider.ReadToken(conn.Home) if err != nil { perr = err return metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}} } defer clear(key) u, err := api.Probe(ctx, key, model) perr = err // Another model answering proves nothing about the selected one; // its usage is that model's, priced as it (security round, // finding 6). if errors.Is(err, connect.ErrKeyRefused) || errors.Is(err, connect.ErrModelNotFound) { // Refused before any work: nothing was billed. return metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}} } // The request ran in this process, which is its whole boundary. return metered.Result{Usage: []wire.Usage{u.Row(conn.Provider, conn.LocalID, model, attempt, err == nil)}, Ending: metered.Ending{Proven: true}} }, func(t *sql.Tx, priced []wire.Usage) error { // The verdict commits with the probe's charge. now := time.Now() switch { case perr == nil: if err := metered.Checked(ctx, t, conn.LocalID, true); err != nil { return err } if err := metered.MarkModel(ctx, t, conn.LocalID, model, wire.ModelHealthy, "", now); err != nil { return err } case errors.Is(perr, connect.ErrKeyRefused): if err := metered.Checked(ctx, t, conn.LocalID, false); err != nil { return err } case errors.Is(perr, connect.ErrModelNotFound): if err := metered.MarkModel(ctx, t, conn.LocalID, model, wire.ModelUnhealthy, wire.ModelNotFound, now); err != nil { return err } case errors.Is(perr, connect.ErrModelMismatch): if err := metered.MarkModel(ctx, t, conn.LocalID, model, wire.ModelUnhealthy, wire.ModelOtherAnswered, now); err != nil { return err } } if len(priced) == 0 { return nil } return c.State.enqueue(t, wire.FrameUsage, "", wire.UsageReport{ProbeID: id, Rows: priced}) }) if err != nil { return adm, err } if !adm.Admitted { return adm, errHeld } return adm, perr } // probeModel is a step's first-use probe (Conns.Prober, §16.4). func (c *Connector) probeModel(ctx context.Context, conn metered.Conn, model, id string, admit func(*sql.Tx) error) (metered.Admission, error) { adm, err := c.probe(ctx, conn, model, id, admit) if errors.Is(err, errHeld) { err = nil } if c.Notify != nil { c.Notify() } return adm, err } // Model takes the person's pick of a connecting attempt's model, once // per frame, and wakes the attempt. func (c *Connector) Model(ctx context.Context, frameID string, cmd wire.ModelCommand) error { err := c.State.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh || len(cmd.Model) > wire.MaxModelName { return err } _, err = t.Exec("UPDATE connect_attempts SET model=? WHERE id=? AND person=? AND kind=? AND state='running'", cmd.Model, cmd.Connection, cmd.Person, wire.KindAPIKey) return err }) if err == nil { c.wake(cmd.Connection) } return err } // Models applies the person's allowed set (§16.1), once per frame. A // connecting attempt (no runner name yet) takes it as its card's answer // and wakes. A metered connection applies it in one transaction, only // for the connection, person and runner name the frame names and only // above the revision held; the link acks it after, which is when the // instance shows it applied. A frame that does not bind is acked // unapplied: hello carries the revision held, so the instance sees it. func (c *Connector) Models(ctx context.Context, frameID string, cmd wire.ModelsCommand) error { m := c.meter() applied, woke := false, false err := c.State.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh || !wire.ValidAllowed(cmd.Allowed) { return err } if cmd.LocalID == "" { raw, err := json.Marshal(wire.ModelsCommand{Allowed: cmd.Allowed, Revision: cmd.Revision}) if err != nil { return err } res, err := t.Exec("UPDATE connect_attempts SET allowed=? WHERE id=? AND person=? AND kind=? AND state='running'", string(raw), cmd.Connection, cmd.Person, wire.KindAPIKey) if err != nil { return err } n, _ := res.RowsAffected() woke = n == 1 return nil } if m == nil { return nil } if ok, err := bound(ctx, t, cmd.LocalID, cmd.Connection, cmd.Person); err != nil || !ok { return err } applied, err = metered.SetModels(ctx, t, cmd.LocalID, cmd.Connection, cmd.Allowed, cmd.Revision) if errors.Is(err, metered.ErrNotAllowable) { // A model it cannot price or tier: acked, not applied. return nil } return err }) if err == nil && woke { c.wake(cmd.Connection) } if err == nil && applied { m.Notify() if c.Notify != nil { c.Notify() } } return err } // Budget applies a budget frame for one of the person's metered // connections. In one transaction: a frame already consumed changes // nothing; the command must name the connection's own instance id, // person and runner name, and a budget in bounds; then it is applied // (security round, finding 4). The link acks it after, which is when the // instance shows it applied. A frame that does not bind is acked // unapplied. func (c *Connector) Budget(ctx context.Context, frameID string, cmd wire.BudgetCommand) error { m := c.meter() if m == nil { return nil } applied := false err := c.State.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh || !wire.ValidBudget(cmd.Budget) { return err } if ok, err := bound(ctx, t, cmd.LocalID, cmd.Connection, cmd.Person); err != nil || !ok { return err } applied, err = metered.ApplyBudget(ctx, t, cmd.LocalID, cmd.Connection, cmd.Budget) return err }) if err == nil && applied { m.Notify() } return err } // bound reports whether a frame's binding is the metered connection's // own: its runner name, the instance's id for it and its person. func bound(ctx context.Context, t *sql.Tx, local, connection, person string) (bool, error) { conn, ok, err := metered.Get(ctx, t, local) if err != nil || !ok { return false, err } return conn.Connection != "" && conn.Connection == connection && conn.Person == person, nil } // ResumeSpend consumes the person's Resume for the pause it names, under // the same binding and freshness rules as Budget. func (c *Connector) ResumeSpend(ctx context.Context, frameID string, cmd wire.ResumeSpendCommand) error { m := c.meter() if m == nil { return nil } cleared := false err := c.State.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh { return err } if ok, err := bound(ctx, t, cmd.LocalID, cmd.Connection, cmd.Person); err != nil || !ok { return err } cleared, err = metered.Resume(ctx, t, cmd.LocalID, cmd.Connection, cmd.PauseRevision) return err }) if err == nil && cleared { m.Notify() } return err } // checkMetered is Check again on a metered connection (§16.4): the key // proven again on the cheapest allowed model, then every unhealthy // allowed model probed, each billable and through the guard under the // normal budget bar. A refused key makes it sign_in_again and stops. func (c *Connector) checkMetered(conn metered.Conn) { c.background(func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() // The key's list read again: the page's choices (a connection // from before S5b gets its list here). if api, ok := c.apiClient(conn.Provider); ok { if key, err := provider.ReadToken(conn.Home); err == nil { listed, err := api.Models(ctx, key) clear(key) if err == nil { c.log("connection models", c.State.tx(ctx, func(t *sql.Tx) error { return metered.SetListed(ctx, t, conn.LocalID, listed) })) } } } models, err := metered.Models(ctx, c.State.db, conn.LocalID) c.log("connection probe", err) ids := make([]string, 0, len(models)) for _, m := range models { ids = append(ids, m.ID) } first := metered.Cheapest(conn.Provider, conn.PriceVersion, ids) if first == "" { first = conn.Model } _, err = c.probe(ctx, conn, first, "pr_"+conn.LocalID+"_"+rand.Text()[:10], nil) c.log("connection probe", err) for _, m := range models { if err != nil && !errors.Is(err, connect.ErrModelNotFound) && !errors.Is(err, connect.ErrModelMismatch) || ctx.Err() != nil { break } if m.ID == first || m.State != wire.ModelUnhealthy { continue } _, err = c.probe(ctx, conn, m.ID, "pr_"+conn.LocalID+"_"+rand.Text()[:10], nil) c.log("connection probe", err) } c.Conns.changed() if c.Notify != nil { c.Notify() } }) } // removeMetered is a metered connection's part of its sign-out // (security round, finding 3): it retires first, so nothing more is // admitted; an attempt still holding its slot (a Check again's probe) is // awaited, and its charge or spend_unknown commits before the record // goes; then the record goes before its home (a stop between them leaves // the home in the cleanup record, deleted on the next start). An attempt // that does not end in time leaves the sign-out owed, retired. func (c *Connector) removeMetered(k cleanup) bool { ctx := context.Background() if err := c.State.tx(ctx, func(t *sql.Tx) error { return metered.Retire(ctx, t, k.local) }); err != nil { c.log("disconnect metered", err) return false } deadline := time.Now().Add(removeWait) for { err := c.State.tx(ctx, func(t *sql.Tx) error { return metered.Remove(ctx, t, k.local) }) if err == nil { break } if !errors.Is(err, metered.ErrSlotHeld) || time.Now().After(deadline) { c.log("disconnect metered", err) return false } // An attempt that ended unproven is proven here, if it can be. if m := c.meter(); m != nil { _ = m.Recover(ctx) } time.Sleep(100 * time.Millisecond) } c.Conns.changed() return true } // removeWait bounds how long a sign-out waits for a running attempt: a // probe's own limit and a little more. const removeWait = 3 * time.Minute