oficina / equipo Public

runner: API-key connections, the probe and the metered guard

A TensorX key pasted in the app arrives sealed to the runner's key and
bound to TensorX's origin, and is delivered as a Claude token is, into
its own home (0600). The runner, outside any namespace, reads the model
list with it, offers the priced models, and proves the picked one with
a one-token completion admitted through the metered guard and charged
as a usage row with role probe. The connection lives in thin.db (not
the bindings file) and is in hello with its budget and spend; budget
and resume_spend frames apply with their frame record; Check again
probes again; sign-out deletes the record and the home.

Questions on a metered connection pass the guard with their start in
one transaction; refused, they wait queued with the hold as the reason
and go on their own when the facts change. The Meter's slots are
reconciled at start-up, before anything is admitted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 0670615eaf90e894998151d61d09f0f845add917 parent f0f1890
21 files changed, +1,624 −49
  • internal/runner/connect/apikey.go +183 −0
  • internal/runner/connect/apikey_test.go +70 −0
  • internal/runner/metered/ledger.go +3 −3
  • internal/runner/metered/meter.go +41 −3
  • internal/runner/thin/apikey.go +384 −0
  • internal/runner/thin/apikey_test.go +309 −0
  • internal/runner/thin/ask.go +23 −19
  • internal/runner/thin/askmetered.go +170 −0
  • internal/runner/thin/askmetered_test.go +223 −0
  • internal/runner/thin/connector.go +49 −6
  • internal/runner/thin/conns.go +42 −0
  • internal/runner/thin/link.go +22 −0
  • internal/runner/thin/run.go +12 −1
  • internal/runner/thin/signin.go +1 −1
  • internal/runner/thin/state.go +8 −3
  • internal/runner/thin/step.go +20 −2
  • internal/runner/thin/token.go +38 −10
  • internal/wire/connections.go +4 −0
  • internal/wire/metered.go +14 −1
  • internal/wire/questions.go +5 −0
  • internal/wire/runners.go +3 −0
diff --git a/internal/runner/connect/apikey.go b/internal/runner/connect/apikey.go
new file mode 100644
index 00000000..88773cc4
--- /dev/null
+++ b/internal/runner/connect/apikey.go
@@ -0,0 +1,183 @@
+package connect
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "slices"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// API-key providers (connectors spec §2.2): the runner, outside every
+// namespace, reads the provider's model list with the key and proves the
+// selected model with a one-token completion. Nothing here logs or
+// returns the key, a header, or the provider's text.
+
+// ErrKeyRefused: the provider refused the key (401 or 403). For TensorX
+// that is also an empty balance (§4.1).
+var ErrKeyRefused = errors.New("the provider refused the key")
+
+// ErrProviderAnswer: the provider's answer was not one this reads.
+var ErrProviderAnswer = errors.New("the provider's answer could not be read")
+
+// errProviderUnreachable: the request did not reach an answer.
+var errProviderUnreachable = errors.New("the provider could not be reached")
+
+// maxAnswer bounds a provider answer read here.
+const maxAnswer = 1 << 20
+
+// APIClient talks to one API-key provider's OpenAI-compatible API.
+// Origin is the provider's origin (wire.APIKeyProvider.Upstream; a test
+// points it at a fake server on 127.0.0.1).
+type APIClient struct {
+ HTTP *http.Client
+ Origin string
+ Path string
+}
+
+func (c APIClient) client() *http.Client {
+ if c.HTTP != nil {
+ return c.HTTP
+ }
+ return &http.Client{Timeout: time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+}
+
+func (c APIClient) do(ctx context.Context, method, path string, key []byte, body any) ([]byte, error) {
+ var in io.Reader
+ if body != nil {
+ raw, err := json.Marshal(body)
+ if err != nil {
+ return nil, err
+ }
+ in = bytes.NewReader(raw)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, strings.TrimSuffix(c.Origin, "/")+c.Path+path, in)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Authorization", "Bearer "+string(key))
+ req.Header.Set("Accept", "application/json")
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ resp, err := c.client().Do(req)
+ if err != nil {
+ // Never the request (its headers hold the key): the category only.
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ return nil, errProviderUnreachable
+ }
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, maxAnswer+1))
+ if err != nil {
+ return nil, err
+ }
+ switch {
+ case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
+ return nil, ErrKeyRefused
+ case resp.StatusCode/100 != 2 || len(raw) > maxAnswer:
+ return nil, fmt.Errorf("%w: status %d", ErrProviderAnswer, resp.StatusCode)
+ }
+ return raw, nil
+}
+
+// Models lists the models the key may use, sorted, once each.
+func (c APIClient) Models(ctx context.Context, key []byte) ([]string, error) {
+ raw, err := c.do(ctx, http.MethodGet, "/models", key, nil)
+ if err != nil {
+ return nil, err
+ }
+ var list struct {
+ Data []struct {
+ ID string `json:"id"`
+ } `json:"data"`
+ }
+ if err := json.Unmarshal(raw, &list); err != nil {
+ return nil, ErrProviderAnswer
+ }
+ var out []string
+ for _, m := range list.Data {
+ if m.ID != "" && len(m.ID) <= wire.MaxModelName {
+ out = append(out, m.ID)
+ }
+ }
+ slices.Sort(out)
+ return slices.Compact(out), nil
+}
+
+// ProbeUsage is a one-token completion's usage as the provider reported
+// it, normalised: input is the uncached part (an OpenAI-compatible
+// prompt_tokens counts cached tokens inside it); reasoning is part of
+// output. Reported is false when the answer carried no usage.
+type ProbeUsage struct {
+ Input, Cached, Output int64
+ Reasoning *int64
+ Reported bool
+}
+
+// probePrompt is the probe's whole request: one word back, one token.
+const probePrompt = "Reply with the word ok."
+
+// Probe proves model with a one-token completion (max_tokens 1). It is
+// billable: the caller charges its usage like any other attempt's.
+func (c APIClient) Probe(ctx context.Context, key []byte, model string) (ProbeUsage, error) {
+ body := map[string]any{"model": model, "max_tokens": 1, "stream": false, "messages": []map[string]string{{"role": "user", "content": probePrompt}}}
+ raw, err := c.do(ctx, http.MethodPost, "/chat/completions", key, body)
+ if err != nil {
+ return ProbeUsage{}, err
+ }
+ var answer struct {
+ Model string `json:"model"`
+ Usage *struct {
+ Prompt *int64 `json:"prompt_tokens"`
+ Completion *int64 `json:"completion_tokens"`
+ Prompt2 *struct {
+ Cached *int64 `json:"cached_tokens"`
+ } `json:"prompt_tokens_details"`
+ Completion2 *struct {
+ Reasoning *int64 `json:"reasoning_tokens"`
+ } `json:"completion_tokens_details"`
+ } `json:"usage"`
+ }
+ if err := json.Unmarshal(raw, &answer); err != nil {
+ return ProbeUsage{}, ErrProviderAnswer
+ }
+ u := answer.Usage
+ if u == nil || u.Prompt == nil || u.Completion == nil {
+ return ProbeUsage{}, nil
+ }
+ out := ProbeUsage{Input: *u.Prompt, Output: *u.Completion, Reported: true}
+ if u.Prompt2 != nil && u.Prompt2.Cached != nil {
+ out.Cached = *u.Prompt2.Cached
+ out.Input -= out.Cached
+ }
+ if u.Completion2 != nil {
+ out.Reasoning = u.Completion2.Reasoning
+ }
+ if out.Input < 0 || out.Cached < 0 || out.Output < 0 {
+ return ProbeUsage{}, nil
+ }
+ return out, nil
+}
+
+// Row is the probe's usage row on connection local: complete only when
+// the provider reported the usage.
+func (u ProbeUsage) Row(provider, local, model string, attempt int64, ok bool) wire.Usage {
+ row := wire.Usage{Provider: provider, Connection: local, Model: model, Attempt: attempt, Outcome: wire.OutcomeReplied, Complete: u.Reported}
+ if !ok {
+ row.Outcome = wire.OutcomeFailed
+ }
+ if u.Reported {
+ in, cached, out, none := u.Input, u.Cached, u.Output, int64(0)
+ row.InputTokens, row.CachedInputTokens, row.CacheWriteTokens, row.OutputTokens, row.ReasoningOutputTokens = &in, &cached, &none, &out, u.Reasoning
+ }
+ return row
+}
diff --git a/internal/runner/connect/apikey_test.go b/internal/runner/connect/apikey_test.go
new file mode 100644
index 00000000..c30c793b
--- /dev/null
+++ b/internal/runner/connect/apikey_test.go
@@ -0,0 +1,70 @@
+package connect
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// fakeProvider is an OpenAI-compatible provider on 127.0.0.1: it lists
+// models and answers a one-token completion for one key.
+func fakeProvider(t *testing.T, key string) *httptest.Server {
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer "+key {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ switch r.Method + " " + r.URL.Path {
+ case "GET /v1/models":
+ w.Write([]byte(`{"object":"list","data":[{"id":"z-ai/glm-5.3"},{"id":"vendor/other"},{"id":"z-ai/glm-5.3"}]}`))
+ case "POST /v1/chat/completions":
+ var in struct {
+ Model string `json:"model"`
+ MaxTokens int `json:"max_tokens"`
+ }
+ if json.NewDecoder(r.Body).Decode(&in) != nil || in.MaxTokens != 1 {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ w.Write([]byte(`{"model":"` + in.Model + `","choices":[{"message":{"content":"ok"}}],"usage":{"prompt_tokens":12,"completion_tokens":1,"prompt_tokens_details":{"cached_tokens":2}}}`))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ t.Cleanup(s.Close)
+ if !strings.HasPrefix(s.URL, "http://127.0.0.1:") {
+ t.Fatalf("fake provider not on loopback: %s", s.URL)
+ }
+ return s
+}
+
+func TestAPIClientModelsAndProbe(t *testing.T) {
+ s := fakeProvider(t, "tx-key-1")
+ c := APIClient{Origin: s.URL, Path: "/v1"}
+ models, err := c.Models(context.Background(), []byte("tx-key-1"))
+ if err != nil || strings.Join(models, ",") != "vendor/other,z-ai/glm-5.3" {
+ t.Fatalf("models %v %v", models, err)
+ }
+ u, err := c.Probe(context.Background(), []byte("tx-key-1"), "z-ai/glm-5.3")
+ if err != nil || !u.Reported || u.Input != 10 || u.Cached != 2 || u.Output != 1 {
+ t.Fatalf("probe %+v %v", u, err)
+ }
+ row := u.Row("tensorx", "tensorx-1", "z-ai/glm-5.3", 1, true)
+ if !row.Complete || *row.InputTokens != 10 || *row.CachedInputTokens != 2 || *row.OutputTokens != 1 || row.Outcome != "replied" {
+ t.Fatalf("row %+v", row)
+ }
+ _, err = c.Models(context.Background(), []byte("wrong"))
+ if !errors.Is(err, ErrKeyRefused) || strings.Contains(err.Error(), "wrong") {
+ t.Fatalf("refused: %v", err)
+ }
+ if _, err = c.Probe(context.Background(), []byte("wrong"), "z-ai/glm-5.3"); !errors.Is(err, ErrKeyRefused) {
+ t.Fatalf("probe refused: %v", err)
+ }
+ if row := (ProbeUsage{}).Row("tensorx", "tensorx-1", "z-ai/glm-5.3", 1, true); row.Complete || row.InputTokens != nil {
+ t.Fatalf("no usage reported: %+v", row)
+ }
+}
diff --git a/internal/runner/metered/ledger.go b/internal/runner/metered/ledger.go
index 420ef515..065e6498 100644
--- a/internal/runner/metered/ledger.go
+++ b/internal/runner/metered/ledger.go
@@ -24,9 +24,9 @@ CREATE INDEX IF NOT EXISTS budget_charge_period ON budget_charge(connection, day
// Holds: why an attempt on a metered connection is not admitted.
const (
- HoldBusy = "busy"
- HoldBudget = "budget"
- HoldSpendUnknown = "spend_unknown"
+ HoldBusy = wire.HoldBusy
+ HoldBudget = wire.HoldBudget
+ HoldSpendUnknown = wire.HoldSpendUnknown
)
// Roles an attempt holds the slot for.
diff --git a/internal/runner/metered/meter.go b/internal/runner/metered/meter.go
index 9eebf2c6..3d352297 100644
--- a/internal/runner/metered/meter.go
+++ b/internal/runner/metered/meter.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
+ "sync"
"time"
"amadan.net/oficina/equipo/internal/wire"
@@ -28,6 +29,30 @@ type Meter struct {
// Fault, in tests, stops the process at a boundary ("exited": after
// the harness ended, before its charge), as if it stopped there.
Fault func(stage string) error
+
+ // running are the slots this process admitted whose attempt has not
+ // ended: Recover never touches them.
+ mu sync.Mutex
+ running map[string]bool
+}
+
+func (m *Meter) setRunning(local string, h Holder, on bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.running == nil {
+ m.running = map[string]bool{}
+ }
+ if on {
+ m.running[local+"\x00"+h.Key()] = true
+ } else {
+ delete(m.running, local+"\x00"+h.Key())
+ }
+}
+
+func (m *Meter) isRunning(local, holder string) bool {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.running[local+"\x00"+holder]
}
// ErrStopped is a test fault's stop.
@@ -87,6 +112,7 @@ func (m *Meter) Admit(ctx context.Context, local string, h Holder, admit func(*s
return admit(t)
})
if err == nil && a.Admitted {
+ m.setRunning(local, h, true)
m.changed()
}
return a, err
@@ -118,9 +144,17 @@ func (m *Meter) Run(ctx context.Context, local string, h Holder, run func(contex
return a, res, err
}
+// Namespace records the namespace of h's attempt in its slot (before the
+// harness starts it).
+func (m *Meter) Namespace(ctx context.Context, local string, h Holder, ns string) error {
+ return m.tx(ctx, func(t *sql.Tx) error { return SetNamespace(ctx, t, local, h, ns) })
+}
+
// Finish charges an attempt's usage and, once its exit is proven,
-// releases its slot, in one transaction.
+// releases its slot, in one transaction. The attempt has ended either
+// way: an unproven one is Recover's to prove.
func (m *Meter) Finish(ctx context.Context, local string, h Holder, res Result, report func(*sql.Tx, []wire.Usage) error) error {
+ defer m.setRunning(local, h, false)
err := m.tx(ctx, func(t *sql.Tx) error {
priced, err := Charge(ctx, t, local, h, res.Usage, m.now())
if err != nil {
@@ -142,8 +176,9 @@ func (m *Meter) Finish(ctx context.Context, local string, h Holder, res Result,
return err
}
-// Recover reconciles every claimed slot, at start-up before anything is
-// admitted and again whenever an exit could not be proven (§2.3): the
+// Recover reconciles every claimed slot whose attempt is not running in
+// this process, at start-up before anything is admitted and again
+// whenever an exit could not be proven (§2.3): the
// attempt's namespace is proven gone; a usage row it committed is
// already charged (Charge commits with the report); otherwise the
// connection's spend becomes unknown; then the slot is released, in one
@@ -156,6 +191,9 @@ func (m *Meter) Recover(ctx context.Context) error {
}
var first error
for _, c := range held {
+ if m.isRunning(c.Local, c.Holder) {
+ continue
+ }
if c.Namespace != "" {
if m.Gone == nil {
first = firstErr(first, ErrNotProven)
diff --git a/internal/runner/thin/apikey.go b/internal/runner/thin/apikey.go
new file mode 100644
index 00000000..191c0e6a
--- /dev/null
+++ b/internal/runner/thin/apikey.go
@@ -0,0 +1,384 @@
+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}, 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
+}
+
+// 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
+ }
+ var models []string
+ for _, m := range listed {
+ if priced && table.Priced(m) {
+ models = append(models, m)
+ }
+ }
+ if len(models) == 0 {
+ failed(home, "no_priced_model")
+ return
+ }
+ shown := false
+ var model string
+ for {
+ if _, _, model, err = c.attemptExtra(ctx, cmd.Connection); err != nil {
+ failed(home, "provider_refused")
+ return
+ }
+ if slices.Contains(models, model) {
+ break
+ }
+ if !shown {
+ r := base
+ r.State, r.Prompt = wire.ConnConnecting, &wire.ConnectPrompt{Kind: wire.PromptModel, Models: models}
+ 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
+ }
+ conn := metered.Conn{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}}
+ err = c.State.tx(ctx, func(t *sql.Tx) error {
+ if _, ok, err := metered.Get(ctx, t, local); err != nil || ok {
+ if ok {
+ return metered.SetModel(ctx, t, local, model)
+ }
+ return err
+ }
+ return metered.Add(ctx, t, conn, time.Now())
+ })
+ if err != nil {
+ failed(home, "provider_refused")
+ return
+ }
+ if err = c.probe(ctx, conn, "pr_"+cmd.Connection); 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 is the selected-model proof (§2.2): one billable token, admitted
+// through the metered guard with the slot claimed, its usage charged and
+// reported as a probe's (role probe), the slot released with the charge
+// or spend_unknown. It runs at connect and on Check again only.
+func (c *Connector) probe(ctx context.Context, conn metered.Conn, id string) error {
+ m := c.meter()
+ api, ok := c.apiClient(conn.Provider)
+ if m == nil || !ok {
+ return connect.ErrProviderAnswer
+ }
+ var perr error
+ h := metered.Holder{Step: id, Attempt: 1, Role: metered.RoleProbe}
+ adm, _, err := m.Run(ctx, conn.LocalID, h, 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, conn.Model)
+ perr = err
+ if errors.Is(err, connect.ErrKeyRefused) {
+ // Refused at sign-in: 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, conn.Model, 1, err == nil)}, Ending: metered.Ending{Proven: true}}
+ }, func(t *sql.Tx, priced []wire.Usage) error {
+ // The verdict commits with the probe's charge.
+ if refused := errors.Is(perr, connect.ErrKeyRefused); refused || perr == nil {
+ if err := metered.Checked(ctx, t, conn.LocalID, !refused); 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 err
+ }
+ if !adm.Admitted {
+ return errHeld
+ }
+ return perr
+}
+
+// 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
+}
+
+// Budget applies a budget frame for one of the person's metered
+// connections, with the frame's record in the same transaction; the
+// link acks it after, which is when the instance shows it applied. A
+// frame for no such connection, or out of bounds, is acked unapplied.
+func (c *Connector) Budget(ctx context.Context, frameID string, cmd wire.BudgetCommand) error {
+ m := c.meter()
+ if m == nil {
+ return nil
+ }
+ if conn, ok, err := metered.Get(ctx, c.State.db, cmd.LocalID); err != nil {
+ return err
+ } else if !ok || conn.Person != cmd.Person || !wire.ValidBudget(cmd.Budget) {
+ return nil
+ }
+ _, err := m.ApplyBudget(ctx, cmd.LocalID, cmd.Budget, func(t *sql.Tx) error {
+ _, err := seen(t, frameID)
+ return err
+ })
+ if err == nil {
+ c.Conns.changed()
+ }
+ return err
+}
+
+// ResumeSpend consumes the person's Resume for the pause it names.
+func (c *Connector) ResumeSpend(ctx context.Context, frameID string, cmd wire.ResumeSpendCommand) error {
+ m := c.meter()
+ if m == nil {
+ return nil
+ }
+ if conn, ok, err := metered.Get(ctx, c.State.db, cmd.LocalID); err != nil {
+ return err
+ } else if !ok || conn.Person != cmd.Person {
+ return nil
+ }
+ fresh := true
+ _, err := m.Resume(ctx, cmd.LocalID, cmd.PauseRevision, func(t *sql.Tx) error {
+ var err error
+ fresh, err = seen(t, frameID)
+ return err
+ })
+ if err == nil && fresh {
+ c.Conns.changed()
+ }
+ return err
+}
+
+// checkMetered is Check again on a metered connection: the probe again
+// (billable, through the guard). A refused key makes it sign_in_again.
+func (c *Connector) checkMetered(conn metered.Conn) {
+ c.background(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ err := c.probe(ctx, conn, "pr_"+conn.LocalID+"_"+rand.Text()[:10])
+ 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: its
+// record goes before its home; a stop between them leaves the home in
+// the cleanup record, which deletes it on the next start.
+func (c *Connector) removeMetered(k cleanup) bool {
+ err := c.State.tx(context.Background(), func(t *sql.Tx) error { return metered.Remove(context.Background(), t, k.local) })
+ if err != nil {
+ c.log("disconnect metered", err)
+ return false
+ }
+ c.Conns.changed()
+ return true
+}
diff --git a/internal/runner/thin/apikey_test.go b/internal/runner/thin/apikey_test.go
new file mode 100644
index 00000000..f62fc455
--- /dev/null
+++ b/internal/runner/thin/apikey_test.go
@@ -0,0 +1,309 @@
+package thin
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/metered"
+ "amadan.net/oficina/equipo/internal/sealbox"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// fakeTensorX is an OpenAI-compatible provider on 127.0.0.1 standing in
+// for TensorX: one key it accepts, a model list, and one-token
+// completions it counts. No real provider is called.
+type fakeTensorX struct {
+ *httptest.Server
+ mu sync.Mutex
+ key string
+ probes []string
+ usage string
+}
+
+func newFakeTensorX(t *testing.T, key string) *fakeTensorX {
+ f := &fakeTensorX{key: key, usage: `{"prompt_tokens":9,"completion_tokens":1}`}
+ f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ key, usage := f.key, f.usage
+ f.mu.Unlock()
+ if r.Header.Get("Authorization") != "Bearer "+key {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ switch r.Method + " " + r.URL.Path {
+ case "GET /v1/models":
+ w.Write([]byte(`{"data":[{"id":"z-ai/glm-5.3"},{"id":"vendor/unpriced"}]}`))
+ case "POST /v1/chat/completions":
+ var in struct {
+ Model string `json:"model"`
+ MaxTokens int `json:"max_tokens"`
+ }
+ if json.NewDecoder(r.Body).Decode(&in) != nil || in.MaxTokens != 1 {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ f.mu.Lock()
+ f.probes = append(f.probes, in.Model)
+ f.mu.Unlock()
+ w.Write([]byte(`{"choices":[{"message":{"content":"ok"}}],"usage":` + usage + `}`))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ t.Cleanup(f.Close)
+ if !strings.HasPrefix(f.URL, "http://127.0.0.1:") {
+ t.Fatalf("fake provider not on loopback: %s", f.URL)
+ }
+ return f
+}
+
+func (f *fakeTensorX) set(key, usage string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if key != "" {
+ f.key = key
+ }
+ if usage != "" {
+ f.usage = usage
+ }
+}
+
+func (f *fakeTensorX) probeCount() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return len(f.probes)
+}
+
+// meteredConnector is a connector with the metered guard, its API-key
+// providers pointed at fake.
+func (r *tokenRig) meteredConnector(fake *fakeTensorX) *Connector {
+ if r.conns.Meter == nil {
+ r.conns.Meter = &metered.Meter{DB: r.state.db}
+ }
+ c := r.connector()
+ c.http, c.origin = fake.Client(), func(string) string { return fake.URL }
+ return c
+}
+
+func (r *tokenRig) startAPIKey(c *Connector, id string) string {
+ r.t.Helper()
+ cmd := wire.ConnectCommand{Connection: id, Person: connPerson, Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth, Currency: "USD", Revision: 1}}
+ if err := c.Accept(r.ctx, "f-connect-"+id, cmd); err != nil {
+ r.t.Fatal(err)
+ }
+ r.card(id, wire.PromptAPIKey)
+ var home string
+ _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home)
+ if home == "" || filepath.Dir(home) != r.root || !strings.HasPrefix(filepath.Base(home), "tensorx-") {
+ r.t.Fatalf("attempt home %q", home)
+ }
+ return home
+}
+
+func (r *tokenRig) card(id, kind string) wire.ConnectPrompt {
+ r.t.Helper()
+ var p wire.ConnectPrompt
+ r.waitFor(func() bool {
+ for _, v := range r.reports(id) {
+ if v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == kind {
+ p = *v.Prompt
+ return true
+ }
+ }
+ return false
+ }, "the "+kind+" card")
+ return p
+}
+
+// sealedKey is a box for an API-key attempt, as the page seals it.
+func (r *tokenRig) sealedKey(id, key string, change func(*wire.SealedPayload)) wire.SecretCommand {
+ r.t.Helper()
+ p := wire.SealedPayload{Secret: key, RunnerID: tokenRunner, ConnectionID: id, Provider: wire.ProviderTensorX, Endpoint: wire.APIKeyProviders[wire.ProviderTensorX].Endpoint, Attempt: 1, ExpiresAt: time.Now().Add(5 * time.Minute).UTC()}
+ if change != nil {
+ change(&p)
+ }
+ s, err := sealbox.Seal(r.keys.PublicString(), p)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ return wire.SecretCommand{Connection: id, Person: connPerson, Sealed: s}
+}
+
+func (r *tokenRig) held(local string) (wire.HeldConnection, bool) {
+ for _, h := range r.conns.Held() {
+ if h.LocalID == local {
+ return h, true
+ }
+ }
+ return wire.HeldConnection{}, false
+}
+
+func (r *tokenRig) usageFrames() []wire.UsageReport {
+ frames, _, err := r.state.Unacked(context.Background(), 0)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ var out []wire.UsageReport
+ for _, f := range frames {
+ var v wire.UsageReport
+ if f.Type == wire.FrameUsage && json.Unmarshal(f.Data, &v) == nil {
+ out = append(out, v)
+ }
+ }
+ return out
+}
+
+// TestAPIKeyConnectionRoundTrip is S1's sealed API-key paste on the
+// runner: the box bound to TensorX's origin is delivered into the home
+// (0600); the runner reads the model list and offers the priced ones;
+// the picked model's one-token probe against the fake provider passes
+// the metered guard and is charged as a usage row with role probe; the
+// connection is then healthy in hello with its budget and spend; Check
+// again probes again and a refused key reads sign_in_again; a budget
+// frame applies above the revision held; sign-out deletes the home and
+// the record. The key is in no frame and no log line.
+func TestAPIKeyConnectionRoundTrip(t *testing.T) {
+ const key = "tx-fake-key-fake-key"
+ r := newTokenRig(t)
+ fake := newFakeTensorX(t, key)
+ c := r.meteredConnector(fake)
+ home := r.startAPIKey(c, "cn_tx")
+ local := filepath.Base(home)
+ if !r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil)) {
+ t.Fatalf("secret refused: %v", r.errs)
+ }
+ p := r.card("cn_tx", wire.PromptModel)
+ if strings.Join(p.Models, ",") != "z-ai/glm-5.3" {
+ t.Fatalf("offered %v", p.Models)
+ }
+ if fake.probeCount() != 0 {
+ t.Fatal("probed before a model was picked")
+ }
+ // A model not offered changes nothing; the offered one runs the probe.
+ if err := c.Model(r.ctx, "f-model-0", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "vendor/unpriced"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := c.Model(r.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"}); err != nil {
+ t.Fatal(err)
+ }
+ end := r.ended("cn_tx")
+ if end.State != wire.ConnHealthy || end.LocalID != local || end.Provider != wire.ProviderTensorX {
+ t.Fatalf("end %+v", end)
+ }
+ if fake.probeCount() != 1 {
+ t.Fatalf("probes %d", fake.probeCount())
+ }
+ raw, err := os.ReadFile(filepath.Join(home, ".oauth-token"))
+ info, _ := os.Stat(filepath.Join(home, ".oauth-token"))
+ if err != nil || string(raw) != key || info.Mode().Perm() != 0600 {
+ t.Fatalf("key file: %v", err)
+ }
+ usage := r.usageFrames()
+ if len(usage) != 1 || usage[0].ProbeID != "pr_cn_tx" || len(usage[0].Rows) != 1 {
+ t.Fatalf("probe usage %+v", usage)
+ }
+ row := usage[0].Rows[0]
+ // 9 input at 1.75 and 1 output at 4.50 per million: 16 + 5 micros.
+ if row.CostMicros == nil || *row.CostMicros != 21 || row.PriceVersion != "tensorx-2026-11-12" || row.Connection != local || !row.Complete {
+ t.Fatalf("probe row %+v", row)
+ }
+ h, ok := r.held(local)
+ if !ok || h.Kind != wire.KindAPIKey || h.State != wire.ConnHealthy || h.Harness != wire.HarnessPi || h.Upstream != "https://api.tensorx.ai" || h.Billing != wire.BillingMetered || h.Model != "z-ai/glm-5.3" || h.Budget == nil || h.Budget.Day != wire.DefaultBudgetDay || h.Spend == nil || h.Spend.Day != 21 || h.Spend.Unknown || h.Spend.Running {
+ t.Fatalf("held %+v %v", h, ok)
+ }
+ // Check again: another billable probe, charged.
+ if err := c.Check(r.ctx, "f-check-1", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil {
+ t.Fatal(err)
+ }
+ r.waitFor(func() bool { h, _ := r.held(local); return h.Spend != nil && h.Spend.Day == 42 }, "the second probe's charge")
+ // The provider refuses the key now: sign_in_again, nothing charged.
+ fake.set("rotated", "")
+ if err := c.Check(r.ctx, "f-check-2", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil {
+ t.Fatal(err)
+ }
+ r.waitFor(func() bool { h, _ := r.held(local); return h.State == wire.ConnSignInAgain }, "sign_in_again")
+ if h, _ := r.held(local); h.Spend.Day != 42 || h.Spend.Unknown {
+ t.Fatalf("a refused probe charged: %+v", h.Spend)
+ }
+ // Budget frames: applied above the revision held, else not.
+ if err := c.Budget(r.ctx, "f-budget-1", wire.BudgetCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 2_000_000, Month: 20_000_000, Revision: 2}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := c.Budget(r.ctx, "f-budget-0", wire.BudgetCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 1, Month: 1, Revision: 1}}); err != nil {
+ t.Fatal(err)
+ }
+ if h, _ := r.held(local); h.Budget.Day != 2_000_000 || h.Budget.Month != 20_000_000 || h.Budget.Revision != 2 {
+ t.Fatalf("budget %+v", h.Budget)
+ }
+ // Nothing in the outbox or the log is the key.
+ frames, _, _ := r.state.Unacked(context.Background(), 0)
+ for _, f := range frames {
+ if strings.Contains(string(f.Data), key) {
+ t.Fatalf("%s frame carries the key", f.Type)
+ }
+ }
+ if strings.Contains(r.logs.String(), key) {
+ t.Fatal("the log carries the key")
+ }
+ // Sign out: the record, the home and the key go.
+ if err := c.Disconnect(r.ctx, "f-disconnect", wire.DisconnectCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil {
+ t.Fatal(err)
+ }
+ r.waitFor(func() bool {
+ for _, v := range r.reports("cn_tx") {
+ if v.State == wire.ConnSignedOut {
+ return true
+ }
+ }
+ return false
+ }, "signed out")
+ if _, err := os.Lstat(home); !os.IsNotExist(err) {
+ t.Fatalf("home left: %v", err)
+ }
+ if _, ok := r.held(local); ok {
+ t.Fatal("still held")
+ }
+}
+
+// TestAPIKeyBoxBoundToTheProvider: a box for an API-key attempt bound to
+// Claude's endpoint, or naming Claude, is refused and ends the attempt;
+// a key the provider refuses ends it key_refused, home and all.
+func TestAPIKeyBoxBoundToTheProvider(t *testing.T) {
+ const key = "tx-fake-key-fake-key"
+ r := newTokenRig(t)
+ fake := newFakeTensorX(t, key)
+ c := r.meteredConnector(fake)
+ for i, change := range []func(*wire.SealedPayload){
+ func(p *wire.SealedPayload) { p.Endpoint = wire.EndpointAnthropic },
+ func(p *wire.SealedPayload) { p.Provider = wire.ProviderClaude },
+ } {
+ id := "cn_bad" + string(rune('a'+i))
+ home := r.startAPIKey(c, id)
+ r.deliver(c, "f-secret-"+id, r.sealedKey(id, key, change))
+ if end := r.ended(id); end.State != wire.ConnError || end.Reason != "provider_refused" {
+ t.Fatalf("%s: %+v", id, end)
+ }
+ if _, err := os.Lstat(home); !os.IsNotExist(err) {
+ t.Fatalf("%s: home left", id)
+ }
+ }
+ home := r.startAPIKey(c, "cn_wrong")
+ r.deliver(c, "f-secret-wrong", r.sealedKey("cn_wrong", "tx-not-the-key", nil))
+ if end := r.ended("cn_wrong"); end.State != wire.ConnError || end.Reason != "key_refused" {
+ t.Fatalf("wrong key: %+v", end)
+ }
+ if _, err := os.Lstat(home); !os.IsNotExist(err) {
+ t.Fatal("refused key's home left")
+ }
+ if fake.probeCount() != 0 || len(r.conns.Held()) != 0 {
+ t.Fatal("a refused attempt probed or stayed")
+ }
+}
diff --git a/internal/runner/thin/ask.go b/internal/runner/thin/ask.go
index d8526886..803b6770 100644
--- a/internal/runner/thin/ask.go
+++ b/internal/runner/thin/ask.go
@@ -212,7 +212,7 @@ func (s *State) nextAsk(ctx context.Context) (askRow, bool, error) {
var a askRow
var body string
var cancel int
- err := s.db.QueryRowContext(ctx, "SELECT body, cancel, created_at FROM asks WHERE state=? AND started=0 ORDER BY created_at, question_id LIMIT 1", runRunning).Scan(&body, &cancel, &a.Created)
+ err := s.db.QueryRowContext(ctx, "SELECT body, cancel, created_at FROM asks WHERE state=? AND started=0 AND (not_before='' OR not_before<=? OR cancel=1) ORDER BY created_at, question_id LIMIT 1", runRunning, stamp(time.Now())).Scan(&body, &cancel, &a.Created)
if errors.Is(err, sql.ErrNoRows) {
return a, false, nil
}
@@ -247,26 +247,30 @@ func (s *State) startAsk(ctx context.Context, a askRow) error {
// a probe that verifies the exit sends it later. Either way the attempt
// leaves the queue.
func (s *State) FinishAsk(ctx context.Context, a askRow, rep wire.AnswerReport, terminated bool) error {
- return s.tx(ctx, func(t *sql.Tx) error {
- if s.fault != nil {
- if err := s.fault("finish_ask"); err != nil {
- return err
- }
- }
- if !terminated {
- raw, _ := json.Marshal(rep)
- _, err := t.Exec("UPDATE asks SET state=?, final=? WHERE question_id=? AND attempt=? AND state=?", runPending, string(raw), a.QuestionID, a.Attempt, runRunning)
- return err
- }
- res, err := t.Exec("UPDATE asks SET state=? WHERE question_id=? AND attempt=? AND state=?", runReported, a.QuestionID, a.Attempt, runRunning)
- if err != nil {
+ return s.tx(ctx, func(t *sql.Tx) error { return s.finishAskTx(t, a, rep, terminated) })
+}
+
+// finishAskTx is FinishAsk in the caller's transaction (a metered
+// question's charge commits with it).
+func (s *State) finishAskTx(t *sql.Tx, a askRow, rep wire.AnswerReport, terminated bool) error {
+ if s.fault != nil {
+ if err := s.fault("finish_ask"); err != nil {
return err
}
- if n, _ := res.RowsAffected(); n != 1 {
- return nil
- }
- return s.enqueue(t, wire.FrameAnswer, "", rep)
- })
+ }
+ if !terminated {
+ raw, _ := json.Marshal(rep)
+ _, err := t.Exec("UPDATE asks SET state=?, final=? WHERE question_id=? AND attempt=? AND state=?", runPending, string(raw), a.QuestionID, a.Attempt, runRunning)
+ return err
+ }
+ res, err := t.Exec("UPDATE asks SET state=? WHERE question_id=? AND attempt=? AND state=?", runReported, a.QuestionID, a.Attempt, runRunning)
+ if err != nil {
+ return err
+ }
+ if n, _ := res.RowsAffected(); n != 1 {
+ return nil
+ }
+ return s.enqueue(t, wire.FrameAnswer, "", rep)
}
// heldAsk is an attempt whose answer waits for its namespace's proof.
diff --git a/internal/runner/thin/askmetered.go b/internal/runner/thin/askmetered.go
new file mode 100644
index 00000000..06adc122
--- /dev/null
+++ b/internal/runner/thin/askmetered.go
@@ -0,0 +1,170 @@
+package thin
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/metered"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The metered guard for questions (connectors spec §7, "Ask"). A
+// question stays on its step's own session and connection; when that
+// connection is metered it passes the same guard as a step, in the same
+// admission transaction as its start: the slot free, the spend known,
+// the day's and the month's budget not reached. Consent is the question
+// itself. A question the guard refuses is held, never moved: it reports
+// queued with the hold as its reason and goes on its own when the facts
+// change (MeteredChanged) or, for the budget, at the next day.
+
+// heldUntilChange is a held question's not_before while it waits for a
+// fact to change (the slot, a Resume), not for a time.
+const heldUntilChange = "999999999999999"
+
+// MeteredAskFunc answers a question on a metered connection (S2's Pi
+// adapter): the report, with the harness's usage rows, and how the
+// attempt ended. l.Namespace records its namespace before it starts.
+type MeteredAskFunc func(ctx context.Context, a askRow, l metered.Launch, progress func(wire.AnswerReport)) (wire.AnswerReport, metered.Ending)
+
+// meteredAsk is the metered connection a question's kept session is on.
+func (e *StepEngine) meteredAsk(ctx context.Context, a askRow) (string, bool) {
+ if e.Meter == nil {
+ return "", false
+ }
+ kept, found, err := e.State.keptSessionFor(ctx, a.StepID)
+ if err != nil || !found {
+ return "", false
+ }
+ c, ok, err := metered.Get(ctx, e.State.db, kept.Account)
+ if err != nil || !ok {
+ return "", false
+ }
+ return c.LocalID, true
+}
+
+// askMetered runs a question on metered connection local through the
+// guard. With no harness for it here, it fails without claiming the
+// slot.
+func (e *StepEngine) askMetered(ctx, actx context.Context, a askRow, local string, report func(wire.AnswerReport)) {
+ finish := func(rep wire.AnswerReport) {
+ if err := e.State.startAsk(ctx, a); err != nil {
+ e.log("ask start", err)
+ return
+ }
+ e.log("answer report", e.State.FinishAsk(context.WithoutCancel(ctx), a, rep, true))
+ e.Notify()
+ }
+ base := wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt}
+ if e.MeteredAsk == nil {
+ rep := base
+ rep.State, rep.Reason = wire.QuestionFailed, "account_unavailable"
+ finish(rep)
+ return
+ }
+ h := metered.Holder{Step: a.QuestionID, Attempt: a.Attempt, Role: metered.RoleAsk}
+ adm, err := e.Meter.Admit(ctx, local, h, func(t *sql.Tx) error { return startAskTx(t, a) })
+ if err != nil {
+ e.log("ask admission", err)
+ _, herr := e.State.holdAsk(ctx, a, "", time.Now().Add(heldRetry))
+ e.log("ask hold", herr)
+ time.AfterFunc(heldRetry, e.Wake)
+ return
+ }
+ if !adm.Admitted {
+ changed, err := e.State.holdAsk(ctx, a, adm.Hold, adm.WakeAt)
+ if err != nil {
+ e.log("ask hold", err)
+ return
+ }
+ if changed {
+ // Said once per hold, not at every look.
+ held := base
+ held.State, held.Reason = wire.QuestionQueued, adm.Hold
+ report(held)
+ }
+ return
+ }
+ l := metered.Launch{Holder: h, Namespace: func(ns string) error {
+ if err := e.State.setAskNamespace(ctx, a, ns); err != nil {
+ return err
+ }
+ return e.Meter.Namespace(ctx, local, h, ns)
+ }}
+ if c, ok, err := metered.Get(ctx, e.State.db, local); err == nil && ok {
+ l.Conn = c
+ }
+ rep, ending := e.MeteredAsk(actx, a, l, func(p wire.AnswerReport) {
+ p.State = wire.QuestionRunning
+ report(p)
+ })
+ if actx.Err() != nil && rep.State != wire.QuestionAnswered {
+ rep.State, rep.Reason = wire.QuestionCancelled, "cancelled"
+ }
+ if !wire.QuestionTerminal(rep.State) {
+ rep.State, rep.Reason = wire.QuestionFailed, "provider_failed"
+ }
+ rep.TaskID, rep.QuestionID, rep.Attempt = a.TaskID, a.QuestionID, a.Attempt
+ // The charge, the answer and (once proven) the slot's release commit
+ // together; a failed write is tried again, never the harness.
+ for i := 0; ; i++ {
+ err := e.Meter.Finish(context.WithoutCancel(ctx), local, h, metered.Result{Usage: rep.Usage, Ending: ending}, func(t *sql.Tx, priced []wire.Usage) error {
+ out := rep
+ out.Usage = priced
+ return e.State.finishAskTx(t, a, out, ending.Proven)
+ })
+ if err == nil {
+ break
+ }
+ e.log("answer report", err)
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(min(time.Duration(i+1)*100*time.Millisecond, 5*time.Second)):
+ }
+ }
+ e.Notify()
+}
+
+// startAskTx marks a question started in the guard's transaction.
+func startAskTx(t *sql.Tx, a askRow) error {
+ res, err := t.Exec("UPDATE asks SET started=1, hold='', not_before='' WHERE question_id=? AND attempt=? AND state=? AND started=0", a.QuestionID, a.Attempt, runRunning)
+ if err != nil {
+ return err
+ }
+ if n, _ := res.RowsAffected(); n != 1 {
+ return errors.New("question attempt not runnable")
+ }
+ return nil
+}
+
+// holdAsk holds a question for its guard: until a fact changes, or (for
+// the budget) until the next day or month. It reports whether the hold
+// is not the one the question already had.
+func (s *State) holdAsk(ctx context.Context, a askRow, hold string, until time.Time) (bool, error) {
+ at := heldUntilChange
+ if !until.IsZero() {
+ at = stamp(until)
+ }
+ changed := false
+ err := s.tx(ctx, func(t *sql.Tx) error {
+ var was string
+ if err := t.QueryRow("SELECT hold FROM asks WHERE question_id=? AND attempt=?", a.QuestionID, a.Attempt).Scan(&was); err != nil {
+ return err
+ }
+ changed = was != hold
+ _, err := t.Exec("UPDATE asks SET hold=?, not_before=? WHERE question_id=? AND attempt=? AND state=? AND started=0", hold, at, a.QuestionID, a.Attempt, runRunning)
+ return err
+ })
+ return changed, err
+}
+
+// MeteredChanged looks at held questions again: a slot was released, a
+// budget applied, a pause resumed, or a connection's standing changed.
+func (e *StepEngine) MeteredChanged() {
+ if _, err := e.State.db.Exec("UPDATE asks SET not_before='' WHERE hold<>'' AND state=? AND started=0", runRunning); err != nil {
+ e.log("ask holds", err)
+ }
+ e.Wake()
+}
diff --git a/internal/runner/thin/askmetered_test.go b/internal/runner/thin/askmetered_test.go
new file mode 100644
index 00000000..17e90f01
--- /dev/null
+++ b/internal/runner/thin/askmetered_test.go
@@ -0,0 +1,223 @@
+package thin
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/metered"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// askRig is a step engine whose questions' kept session is on a metered
+// connection, and a fake harness answering them (S2's Pi stands here).
+type askRig struct {
+ t *testing.T
+ ctx context.Context
+ s *State
+ m *metered.Meter
+ e *StepEngine
+ calls atomic.Int64
+}
+
+const meteredLocal = "tensorx-1"
+
+func newAskRig(t *testing.T, harness bool) *askRig {
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ s, err := OpenState(ctx, t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { s.Close() })
+ r := &askRig{t: t, ctx: ctx, s: s, m: &metered.Meter{DB: s.db}}
+ err = s.tx(ctx, func(tx *sql.Tx) error {
+ if err := metered.Add(ctx, tx, metered.Conn{LocalID: meteredLocal, Person: connPerson, Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: "/nowhere", Currency: "USD", PriceVersion: metered.Current[wire.ProviderTensorX], Budget: wire.Budget{Day: 1_000_000, Month: 10_000_000, Revision: 1}}, time.Now()); err != nil {
+ return err
+ }
+ return metered.Checked(ctx, tx, meteredLocal, true)
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.e = &StepEngine{State: s, Meter: r.m, Notify: func() {}, Exec: func(context.Context, stepRow, func(wire.StepReport)) wire.StepReport {
+ t.Error("a step ran")
+ return wire.StepReport{}
+ }, Ask: func(context.Context, askRow, func(wire.AnswerReport)) askResult {
+ t.Error("a metered question went to the Claude path")
+ return askResult{}
+ }}
+ if harness {
+ r.e.MeteredAsk = func(ctx context.Context, a askRow, l metered.Launch, progress func(wire.AnswerReport)) (wire.AnswerReport, metered.Ending) {
+ r.calls.Add(1)
+ if err := l.Namespace("ns-" + a.QuestionID); err != nil {
+ t.Error(err)
+ }
+ if l.Conn.LocalID != meteredLocal || l.Holder.Role != metered.RoleAsk {
+ t.Errorf("launch %+v", l)
+ }
+ in, out := int64(1000), int64(100)
+ return wire.AnswerReport{State: wire.QuestionAnswered, Text: "It reads the config.", Usage: []wire.Usage{{Provider: wire.ProviderTensorX, Connection: meteredLocal, Model: "z-ai/glm-5.3", Attempt: a.Attempt, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &in, OutputTokens: &out}}}, metered.Ending{Proven: true}
+ }
+ }
+ // The step the question asks about kept its session on the metered
+ // connection.
+ if err := s.keepSession(ctx, stepRow{DispatchCommand: dispatchFor("tk1", "s1", 1)}, wire.SpecialistEngineering, meteredLocal, "00000000-0000-4000-8000-000000000001", "/nowhere", "", 1); err != nil {
+ t.Fatal(err)
+ }
+ return r
+}
+
+func (r *askRig) ask(q string) {
+ r.t.Helper()
+ if err := r.s.AcceptAsk(r.ctx, "f-"+q, wire.AskCommand{Person: connPerson, TaskID: "tk1", StepID: "s1", QuestionID: q, Attempt: 1, Specialist: wire.SpecialistEngineering, Text: "What does it read?"}); err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+func (r *askRig) answers(q string) []wire.AnswerReport {
+ frames, _, err := r.s.Unacked(context.Background(), 0)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ var out []wire.AnswerReport
+ for _, f := range frames {
+ var v wire.AnswerReport
+ if f.Type == wire.FrameAnswer && json.Unmarshal(f.Data, &v) == nil && v.QuestionID == q {
+ out = append(out, v)
+ }
+ }
+ return out
+}
+
+func (r *askRig) waitAnswer(q, state string) wire.AnswerReport {
+ r.t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ for _, a := range r.answers(q) {
+ if a.State == state {
+ return a
+ }
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ r.t.Fatalf("%s: no %s report: %+v", q, state, r.answers(q))
+ return wire.AnswerReport{}
+}
+
+func (r *askRig) spend() wire.Spend {
+ c, _, _ := metered.Get(r.ctx, r.s.db, meteredLocal)
+ s, err := metered.SpendOf(r.ctx, r.s.db, c, time.Now())
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ return s
+}
+
+// TestMeteredGuardHoldsQuestions is §7's metered guard for questions:
+// a question on a metered connection is admitted through the same guard
+// as a step, with its start; held, it reports queued with the hold and
+// is never run or moved; it goes on its own once the facts change (the
+// slot released, the budget raised, the pause resumed), and its answer
+// is charged.
+func TestMeteredGuardHoldsQuestions(t *testing.T) {
+ r := newAskRig(t, true)
+ // A probe holds the slot: the question waits busy.
+ probe := metered.Holder{Step: "pr_1", Attempt: 1, Role: metered.RoleProbe}
+ if a, err := r.m.Admit(r.ctx, meteredLocal, probe, nil); err != nil || !a.Admitted {
+ t.Fatal(a, err)
+ }
+ if err := r.e.Start(r.ctx); err != nil {
+ t.Fatal(err)
+ }
+ r.ask("q1")
+ r.e.Wake()
+ if a := r.waitAnswer("q1", wire.QuestionQueued); a.Reason != wire.HoldBusy {
+ t.Fatalf("held %+v", a)
+ }
+ time.Sleep(50 * time.Millisecond)
+ if r.calls.Load() != 0 {
+ t.Fatal("a held question ran")
+ }
+ // The probe ends: the slot is released and the question runs.
+ if err := r.m.Finish(r.ctx, meteredLocal, probe, metered.Result{Ending: metered.Ending{Proven: true, NotStarted: true}}, nil); err != nil {
+ t.Fatal(err)
+ }
+ r.e.MeteredChanged()
+ got := r.waitAnswer("q1", wire.QuestionAnswered)
+ if r.calls.Load() != 1 || len(got.Usage) != 1 || got.Usage[0].CostMicros == nil || *got.Usage[0].CostMicros != 1750+450 {
+ t.Fatalf("answered %+v calls %d", got, r.calls.Load())
+ }
+ if s := r.spend(); s.Day != 2200 || s.Running || s.Unknown {
+ t.Fatalf("spend %+v", s)
+ }
+ // The budget is spent: the next question waits for the next day.
+ if err := r.s.tx(r.ctx, func(tx *sql.Tx) error {
+ _, err := metered.ApplyBudget(r.ctx, tx, meteredLocal, wire.Budget{Day: 2200, Month: 10_000_000, Revision: 2})
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ r.ask("q2")
+ r.e.Wake()
+ if a := r.waitAnswer("q2", wire.QuestionQueued); a.Reason != wire.HoldBudget {
+ t.Fatalf("held %+v", a)
+ }
+ var notBefore string
+ _ = r.s.db.QueryRow("SELECT not_before FROM asks WHERE question_id='q2'").Scan(&notBefore)
+ if notBefore == heldUntilChange || notBefore == "" {
+ t.Fatalf("a budget hold waits for %q, not the next day", notBefore)
+ }
+ // Looked at again with nothing changed: still held, said once.
+ r.e.MeteredChanged()
+ time.Sleep(100 * time.Millisecond)
+ if n := len(r.answers("q2")); n != 1 || r.calls.Load() != 1 {
+ t.Fatalf("reports %d calls %d", n, r.calls.Load())
+ }
+ // Raised and applied: it runs.
+ if _, err := r.m.ApplyBudget(r.ctx, meteredLocal, wire.Budget{Day: 5_000_000, Month: 10_000_000, Revision: 3}, nil); err != nil {
+ t.Fatal(err)
+ }
+ r.e.MeteredChanged()
+ r.waitAnswer("q2", wire.QuestionAnswered)
+ // Spend unknown: the next question waits for Resume.
+ if err := r.s.tx(r.ctx, func(tx *sql.Tx) error {
+ _, err := tx.Exec("UPDATE metered_connections SET spend_unknown=1, pause_revision=7")
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ r.ask("q3")
+ r.e.Wake()
+ if a := r.waitAnswer("q3", wire.QuestionQueued); a.Reason != wire.HoldSpendUnknown {
+ t.Fatalf("held %+v", a)
+ }
+ if ok, err := r.m.Resume(r.ctx, meteredLocal, 7, nil); err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ r.e.MeteredChanged()
+ r.waitAnswer("q3", wire.QuestionAnswered)
+ if r.calls.Load() != 3 {
+ t.Fatalf("calls %d", r.calls.Load())
+ }
+}
+
+// With no harness for its connection here, a question on a metered
+// connection fails without claiming the slot or charging anything.
+func TestMeteredQuestionWithNoHarness(t *testing.T) {
+ r := newAskRig(t, false)
+ if err := r.e.Start(r.ctx); err != nil {
+ t.Fatal(err)
+ }
+ r.ask("q1")
+ r.e.Wake()
+ if a := r.waitAnswer("q1", wire.QuestionFailed); a.Reason != "account_unavailable" {
+ t.Fatalf("%+v", a)
+ }
+ if s := r.spend(); s.Running || s.Unknown || s.Day != 0 {
+ t.Fatalf("spend %+v", s)
+ }
+}
diff --git a/internal/runner/thin/connector.go b/internal/runner/thin/connector.go
index 7bd74da3..e2e68463 100644
--- a/internal/runner/thin/connector.go
+++ b/internal/runner/thin/connector.go
@@ -3,8 +3,10 @@ package thin
import (
"context"
"database/sql"
+ "encoding/json"
"errors"
"log/slog"
+ "net/http"
"os"
"os/exec"
"path/filepath"
@@ -15,6 +17,7 @@ import (
"amadan.net/oficina/equipo/internal/runner"
"amadan.net/oficina/equipo/internal/runner/connect"
"amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/metered"
"amadan.net/oficina/equipo/internal/runner/provider"
runnersetup "amadan.net/oficina/equipo/internal/runner/setup"
"amadan.net/oficina/equipo/internal/sealbox"
@@ -83,6 +86,11 @@ type Connector struct {
codes map[string]*codeWait
// delivery serialises a secret's delivery with its attempt's end.
delivery sync.Mutex
+
+ // http and origin, in tests, send an API-key provider's requests to
+ // a fake provider on 127.0.0.1 (apikey.go).
+ http *http.Client
+ origin func(provider string) string
}
// cleanup is a sign-out the connector owes: recorded in the transaction
@@ -162,8 +170,8 @@ func (c *Connector) Start(ctx context.Context) error {
// waits on (or finishes) where it was. So does a sign-in attempt
// whose token was committed (it is kind token then); one that was
// not lost its CLI with the process, and ends below.
- if l.kind == wire.KindToken {
- if err = c.resumeToken(ctx, l.id, l.person, l.home, l.created); err != nil {
+ if l.kind == wire.KindToken || l.kind == wire.KindAPIKey {
+ if err = c.resumeToken(ctx, l.id, l.person, l.home, l.created, l.kind, l.provider); err != nil {
return err
}
continue
@@ -217,7 +225,12 @@ func (c *Connector) Accept(ctx context.Context, frameID string, cmd wire.Connect
if cmd.SameMachine {
same = 1
}
- _, err = t.Exec("INSERT INTO connect_attempts(id, person, provider, same_machine, state, kind, created_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", cmd.Connection, cmd.Person, cmd.Provider, same, "running", cmd.Kind, now())
+ budget := ""
+ if cmd.Budget != nil {
+ raw, _ := json.Marshal(cmd.Budget)
+ budget = string(raw)
+ }
+ _, err = t.Exec("INSERT INTO connect_attempts(id, person, provider, same_machine, state, kind, billing, budget, created_at) VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", cmd.Connection, cmd.Person, cmd.Provider, same, "running", cmd.Kind, cmd.Billing, budget, now())
return err
})
if err != nil || !fresh {
@@ -226,7 +239,8 @@ func (c *Connector) Accept(ctx context.Context, frameID string, cmd wire.Connect
// A token attempt's home is made before the next frame is read, so
// its secret, however soon it follows, finds the attempt ready (the
// attempt ends if this fails).
- if cmd.Kind == wire.KindToken && cmd.Provider == wire.ProviderClaude && slices.Contains(c.Owners, cmd.Person) {
+ _, apiKey := wire.APIKeyProviders[cmd.Provider]
+ if (cmd.Kind == wire.KindToken && cmd.Provider == wire.ProviderClaude || cmd.Kind == wire.KindAPIKey && apiKey) && slices.Contains(c.Owners, cmd.Person) {
if _, herr := c.tokenHome(ctx, cmd.Connection); herr != nil {
c.log("connect home", herr)
}
@@ -303,6 +317,14 @@ func (c *Connector) Check(ctx context.Context, frameID string, cmd wire.CheckCom
if err != nil || !fresh {
return err
}
+ if mc, ok, err := metered.Get(ctx, c.State.db, cmd.LocalID); err != nil {
+ return err
+ } else if ok {
+ if mc.Person == cmd.Person && mc.Validated {
+ c.checkMetered(mc)
+ }
+ return nil
+ }
b, ok := c.Conns.Binding(cmd.LocalID)
if !ok || b.PersonID != cmd.Person {
return nil
@@ -355,7 +377,24 @@ func (c *Connector) remove(k cleanup) bool {
return false
}
}
- if k.home != "" && exists(k.home) {
+ // A metered connection has no binding: its record names its home.
+ mc, isMetered, err := metered.Get(ctx, c.State.db, k.local)
+ if err != nil {
+ c.log("disconnect metered", err)
+ return false
+ }
+ if isMetered = isMetered && mc.Person == k.person && !bound; isMetered {
+ k.home, k.provider = mc.Home, mc.Provider
+ if _, err := c.State.db.ExecContext(ctx, "UPDATE connect_cleanups SET home=?, provider=? WHERE connection=?", k.home, k.provider, k.connection); err != nil {
+ c.log("disconnect record", err)
+ return false
+ }
+ if !c.removeMetered(k) {
+ return false
+ }
+ }
+ _, apiKey := wire.APIKeyProviders[k.provider]
+ if k.home != "" && exists(k.home) && !apiKey {
if lock, err := os.Open(k.home); err == nil {
if unix.Flock(int(lock.Fd()), unix.LOCK_EX) == nil {
if err := c.logout(ctx, k.provider, k.home); err != nil {
@@ -449,6 +488,10 @@ func (c *Connector) run(ctx context.Context, cancel context.CancelFunc, cmd wire
r.State, r.Reason = wire.ConnError, reason
c.finish(cmd.Connection, r)
}
+ if cmd.Kind == wire.KindAPIKey && slices.Contains(c.Owners, cmd.Person) {
+ c.runAPIKey(ctx, cmd, base)
+ return
+ }
if !slices.Contains(c.Owners, cmd.Person) || cmd.Provider != wire.ProviderClaude && cmd.Provider != wire.ProviderCodex {
fail("provider_refused")
return
@@ -607,7 +650,7 @@ func (c *Connector) mine(person string) []runner.AccountBinding {
// removeHome deletes a home this connector created that never became a
// connection: never one a binding names.
func (c *Connector) removeHome(home string) {
- if home == "" || filepath.Dir(home) != filepath.Clean(c.Root) {
+ if home == "" || filepath.Dir(home) != filepath.Clean(c.Root) || c.meteredHome(home) {
return
}
bs, _ := runner.LoadBindings(c.Runner.AccountBindingsPath)
diff --git a/internal/runner/thin/conns.go b/internal/runner/thin/conns.go
index 7804fc38..730440ee 100644
--- a/internal/runner/thin/conns.go
+++ b/internal/runner/thin/conns.go
@@ -11,6 +11,7 @@ import (
"amadan.net/oficina/equipo/internal/runner"
"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"
)
@@ -52,6 +53,9 @@ type Conns struct {
// Changed is called when a connection may have become usable or its
// standing changed (a hello is due; held turns look again).
Changed func()
+ // Meter is the metered guard over the metered connections in
+ // thin.db (connectors spec S1); nil, none can be added.
+ Meter *metered.Meter
mu sync.Mutex
live map[string]connState
@@ -398,9 +402,47 @@ func (c *Conns) Held() []wire.HeldConnection {
}
out = append(out, held)
}
+ return append(out, c.heldMetered(now)...)
+}
+
+// heldMetered are the metered connections for hello: each validated one
+// with its facts, budget and spend (a refused key reads sign_in_again).
+func (c *Conns) heldMetered(now time.Time) []wire.HeldConnection {
+ if c.Meter == nil {
+ return nil
+ }
+ ctx := context.Background()
+ conns, err := metered.List(ctx, c.State.db)
+ if err != nil {
+ c.warn("metered connections", err)
+ return nil
+ }
+ var out []wire.HeldConnection
+ for _, m := range conns {
+ if !m.Validated {
+ continue
+ }
+ spend, err := metered.SpendOf(ctx, c.State.db, m, now)
+ if err != nil {
+ c.warn("metered spend", err)
+ continue
+ }
+ state := wire.ConnHealthy
+ if m.Refused {
+ state = wire.ConnSignInAgain
+ }
+ budget := m.Budget
+ out = append(out, wire.HeldConnection{LocalID: m.LocalID, Person: m.Person, Provider: m.Provider, Kind: wire.KindAPIKey, State: state, Harness: m.Harness, Upstream: m.Upstream, Billing: m.Billing, Model: m.Model, Budget: &budget, Spend: &spend})
+ }
return out
}
+func (c *Conns) warn(msg string, err error) {
+ if c.Logger != nil {
+ c.Logger.Warn(msg, "err", sanitize(err))
+ }
+}
+
// setExpiry records when a token connection's token expires, so the
// date stays the same across restarts.
func (c *Conns) setExpiry(id string, at time.Time) error {
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index d81ae830..90869593 100644
--- a/internal/runner/thin/link.go
+++ b/internal/runner/thin/link.go
@@ -840,6 +840,28 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro
if err = l.Connector.Secret(ctx, f.ID, *v); err != nil {
return 0, err
}
+ case *wire.ModelCommand:
+ if l.Connector == nil {
+ continue
+ }
+ if err = l.Connector.Model(ctx, f.ID, *v); err != nil {
+ return 0, err
+ }
+ case *wire.BudgetCommand:
+ // Acked once applied: the instance shows it applied then.
+ if l.Connector == nil {
+ continue
+ }
+ if err = l.Connector.Budget(ctx, f.ID, *v); err != nil {
+ return 0, err
+ }
+ case *wire.ResumeSpendCommand:
+ if l.Connector == nil {
+ continue
+ }
+ if err = l.Connector.ResumeSpend(ctx, f.ID, *v); err != nil {
+ return 0, err
+ }
case *wire.CancelConnectCommand:
if l.Connector == nil {
continue
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 775f1934..b9879601 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -22,6 +22,7 @@ import (
"amadan.net/oficina/equipo/internal/runner"
"amadan.net/oficina/equipo/internal/runner/containment"
"amadan.net/oficina/equipo/internal/runner/mac"
+ "amadan.net/oficina/equipo/internal/runner/metered"
"amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runnerproto"
"amadan.net/oficina/equipo/internal/sealbox"
@@ -215,6 +216,13 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
o.AccountsRoot = DefaultAccountsRoot()
}
connector := &Connector{Runner: c, State: state, Conns: conns, Root: o.AccountsRoot, Owners: withPerson(coordinatorPersons(c)(), creds.Bearer.Person), Notify: link.Notify, Logger: o.Logger, Limit: o.ConnectLimit, RunnerID: creds.Bearer.RunnerID, Manager: manager}
+ // The metered guard (connectors spec S1). Its slots are reconciled
+ // before anything is admitted: a slot whose attempt's namespace is
+ // proven gone is released with its charge, or with the spend unknown.
+ conns.Meter = &metered.Meter{DB: state.db, Gone: connector.namespaceGone, Changed: func() { conns.changed() }}
+ if err = conns.Meter.Recover(ctx); err != nil && o.Logger != nil {
+ o.Logger.Warn("metered recovery", "err", sanitize(err))
+ }
// The seal key: the X25519 form of the enrolment key the owner
// approved; secrets for token connections are sealed to it.
sealKey := ""
@@ -313,7 +321,10 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
relay := &Relay{State: state, Engine: engineer, Notify: link.Notify, Logger: o.Logger}
link.Relay = relay
go relay.Loop(ctx)
- wake := steps.Wake
+ // A change of a connection's standing also looks again at questions
+ // held by the metered guard.
+ steps.Meter = conns.Meter
+ wake := steps.MeteredChanged
wakeSteps.Store(&wake)
if err = steps.Start(ctx); err != nil {
return err
diff --git a/internal/runner/thin/signin.go b/internal/runner/thin/signin.go
index 423a5b3a..876c43b8 100644
--- a/internal/runner/thin/signin.go
+++ b/internal/runner/thin/signin.go
@@ -140,7 +140,7 @@ func (c *Connector) runSignIn(ctx context.Context, cmd wire.ConnectCommand, base
c.delivery.Lock()
dir, err := pinHome(home)
if err == nil {
- err = c.keep(ctx, cmd.Connection, dir, token, func(*sql.Tx) error { return nil })
+ err = c.keep(ctx, cmd.Connection, wire.KindToken, dir, token, func(*sql.Tx) error { return nil })
dir.Close()
}
c.delivery.Unlock()
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go
index 40356c28..8789ba87 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -14,6 +14,7 @@ import (
"strings"
"time"
+ "amadan.net/oficina/equipo/internal/runner/metered"
"amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/wire"
_ "modernc.org/sqlite"
@@ -54,7 +55,7 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
return nil, err
}
d.SetMaxOpenConns(1)
- if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+connectSchema+effectSchema+fileSchema+relaySchema); err != nil {
+ if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+connectSchema+effectSchema+fileSchema+relaySchema+metered.Schema); err != nil {
d.Close()
return nil, err
}
@@ -69,7 +70,9 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
}
// Added in slice 4b review: a question's namespace, its held final
// report, and whether its provider started.
- for _, col := range []string{"ns_id TEXT NOT NULL DEFAULT ''", "final TEXT NOT NULL DEFAULT ''", "started INTEGER NOT NULL DEFAULT 0"} {
+ // Added with metered connections (connectors spec S1): a question
+ // held by its connection's guard, until when and why.
+ for _, col := range []string{"ns_id TEXT NOT NULL DEFAULT ''", "final TEXT NOT NULL DEFAULT ''", "started INTEGER NOT NULL DEFAULT 0", "not_before TEXT NOT NULL DEFAULT ''", "hold TEXT NOT NULL DEFAULT ''"} {
if _, err = d.ExecContext(ctx, "ALTER TABLE asks ADD COLUMN "+col); err != nil && !strings.Contains(err.Error(), "duplicate column") {
d.Close()
return nil, err
@@ -106,7 +109,9 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
// sealed secret is committed (credential_present).
// Added with Claude's sign-in by a link: the namespace record of the
// attempt's contained setup-token, proven gone before its home goes.
- for _, col := range []string{"kind", "secret", "namespace"} {
+ // Added with metered connections (connectors spec S1): an API-key
+ // attempt's billing, budget (JSON) and the model the person picked.
+ for _, col := range []string{"kind", "secret", "namespace", "billing", "budget", "model"} {
if _, err = d.ExecContext(ctx, "ALTER TABLE connect_attempts ADD COLUMN "+col+" TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") {
d.Close()
return nil, err
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go
index d9c21230..4c2be287 100644
--- a/internal/runner/thin/step.go
+++ b/internal/runner/thin/step.go
@@ -12,6 +12,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/metered"
"amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/wire"
)
@@ -141,7 +142,7 @@ func (s *State) deferredSince(ctx context.Context, r stepRow) time.Time {
// nextDue is when the earliest deferred attempt is due again.
func (s *State) nextDue(ctx context.Context) (time.Time, bool) {
var v string
- if s.db.QueryRowContext(ctx, "SELECT MIN(not_before) FROM steps WHERE state=? AND not_before<>''", runRunning).Scan(&v) != nil || v == "" {
+ if s.db.QueryRowContext(ctx, "SELECT MIN(v) FROM (SELECT not_before AS v FROM steps WHERE state=? AND not_before<>'' UNION ALL SELECT not_before FROM asks WHERE state=? AND started=0 AND not_before<>'' AND not_before<?)", runRunning, runRunning, heldUntilChange).Scan(&v) != nil || v == "" {
return time.Time{}, false
}
var ms int64
@@ -436,6 +437,11 @@ type StepEngine struct {
// TerminationKind is how this runner proves an attempt's end
// (wire.TerminationNamespace on Linux), reported with termination.
TerminationKind string
+ // Meter is the metered guard: a question on a metered connection
+ // passes it (askmetered.go). MeteredAsk is the harness that answers
+ // one (S2's Pi); nil, such a question cannot run here.
+ Meter *metered.Meter
+ MeteredAsk MeteredAskFunc
mu sync.Mutex
wake chan struct{}
@@ -483,6 +489,12 @@ func (e *StepEngine) Probe(ctx context.Context) {
e.log("step probe", e.State.proveTermination(ctx, p))
sent = true
}
+ if e.Meter != nil {
+ // A metered slot whose ended attempt's exit is proven now is
+ // released, with its charge or the spend unknown. One still
+ // unproven stays held, and is tried again at the next probe.
+ _ = e.Meter.Recover(ctx)
+ }
if sent && e.Notify != nil {
e.Notify()
}
@@ -591,7 +603,8 @@ func (e *StepEngine) loop(ctx context.Context) {
e.askOne(ctx, a)
}
// A deferred attempt (a merge waiting for the hub's CI) wakes the
- // worker when it is due, also after a restart.
+ // worker when it is due, also after a restart; so does a question
+ // held for its metered connection's budget at the next day.
if due, ok := e.State.nextDue(ctx); ok {
time.AfterFunc(max(time.Until(due), 10*time.Millisecond), e.Wake)
}
@@ -651,6 +664,11 @@ func (e *StepEngine) askOne(ctx context.Context, a askRow) {
if e.State.askCancelled(ctx, a) {
cancel()
}
+ if local, ok := e.meteredAsk(ctx, a); ok {
+ // On a metered connection: the guard admits it, with the start.
+ e.askMetered(ctx, actx, a, local, report)
+ return
+ }
// Started, durably, before the provider runs: never run twice.
if err := e.State.startAsk(ctx, a); err != nil {
e.log("ask start", err)
diff --git a/internal/runner/thin/token.go b/internal/runner/thin/token.go
index af08f854..6f69e8ad 100644
--- a/internal/runner/thin/token.go
+++ b/internal/runner/thin/token.go
@@ -44,7 +44,18 @@ type tokenAttempt struct {
}
func (a tokenAttempt) waiting() bool {
- return a.state == "running" && a.kind == wire.KindToken && !a.cancelled && a.secret == "" && a.home != ""
+ return a.state == "running" && (a.kind == wire.KindToken || a.kind == wire.KindAPIKey) && !a.cancelled && a.secret == "" && a.home != ""
+}
+
+// sealedFor is the provider and endpoint a box for the attempt must be
+// bound to: Claude's API for a token, the provider's own origin for an
+// API key (connectors spec §2.2).
+func (a tokenAttempt) sealedFor() (string, string, bool) {
+ if a.kind == wire.KindAPIKey {
+ kp, ok := wire.APIKeyProviders[a.provider]
+ return a.provider, kp.Endpoint, ok
+ }
+ return wire.ProviderClaude, wire.EndpointAnthropic, a.provider == wire.ProviderClaude
}
// signIn says the attempt is Claude's sign-in by the runner's own
@@ -105,7 +116,14 @@ func (c *Connector) tokenHome(ctx context.Context, id string) (string, error) {
if err = os.MkdirAll(c.Root, 0700); err != nil {
return "", err
}
- _, home, err := nextHome(c.Root, wire.ProviderClaude)
+ name := wire.ProviderClaude
+ if a.kind == wire.KindAPIKey {
+ if _, ok := wire.APIKeyProviders[a.provider]; !ok {
+ return "", provider.ErrIdentity
+ }
+ name = a.provider
+ }
+ _, home, err := nextHome(c.Root, name)
if err == nil {
err = provider.CheckLoginHome(home)
}
@@ -323,10 +341,15 @@ func (c *Connector) undoToken(cmd wire.ConnectCommand, id string, lock *os.File,
// recorded cancel ends it cancelled.
func (c *Connector) endToken(id, person, home, reason string) {
var cancelled int
- _ = c.State.db.QueryRow("SELECT cancelled FROM connect_attempts WHERE id=?", id).Scan(&cancelled)
+ kind, prov := "", wire.ProviderClaude
+ _ = c.State.db.QueryRow("SELECT cancelled, kind, provider FROM connect_attempts WHERE id=?", id).Scan(&cancelled, &kind, &prov)
if cancelled == 1 {
reason = "cancelled"
}
+ if kind == wire.KindAPIKey {
+ c.endAPIKey(id, person, prov, home, reason)
+ return
+ }
r := wire.ConnectionReport{Connection: id, Person: person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: reason}
// The connection's local id is its home's name.
local := filepath.Base(home)
@@ -388,7 +411,7 @@ func saveToken(ctx context.Context, bindings, person, id, home string, observed
// the final file must be there (a rename the stop interrupted is
// finished); a row with neither file cannot happen and ends the attempt
// in error. Then the attempt waits on for the rest of its time.
-func (c *Connector) resumeToken(ctx context.Context, id, person, home, created string) error {
+func (c *Connector) resumeToken(ctx context.Context, id, person, home, created, kind, prov string) error {
var rows int
if err := c.State.db.QueryRowContext(ctx, "SELECT count(*) FROM seen_seals WHERE connection_id=?", id).Scan(&rows); err != nil {
return err
@@ -437,7 +460,11 @@ func (c *Connector) resumeToken(ctx context.Context, id, person, home, created s
c.mu.Lock()
c.attempts[id] = cancel
c.mu.Unlock()
- go c.run(actx, cancel, wire.ConnectCommand{Connection: id, Person: person, Provider: wire.ProviderClaude, Kind: wire.KindToken})
+ cmd := wire.ConnectCommand{Connection: id, Person: person, Provider: wire.ProviderClaude, Kind: wire.KindToken}
+ if kind == wire.KindAPIKey {
+ cmd.Provider, cmd.Kind = prov, wire.KindAPIKey
+ }
+ go c.run(actx, cancel, cmd)
return nil
}
@@ -477,7 +504,7 @@ func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretC
}
refuse := func(reason string) error {
c.refused(reason)
- r := wire.ConnectionReport{Connection: a.id, Person: a.person, Provider: wire.ProviderClaude, State: wire.ConnError, Reason: reason}
+ r := wire.ConnectionReport{Connection: a.id, Person: a.person, Provider: a.provider, State: wire.ConnError, Reason: reason}
c.removeHome(a.home)
c.finish(a.id, r)
c.wake(a.id)
@@ -496,7 +523,8 @@ func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretC
secret := []byte(p.Secret)
p.Secret = ""
defer clear(secret)
- if p.RunnerID != c.RunnerID || c.RunnerID == "" || p.ConnectionID != cmd.Connection || cmd.Person != a.person || p.Provider != wire.ProviderClaude || p.Endpoint != wire.EndpointAnthropic || p.Attempt < 1 || !provider.ValidToken(secret) {
+ prov, endpoint, known := a.sealedFor()
+ if !known || p.RunnerID != c.RunnerID || c.RunnerID == "" || p.ConnectionID != cmd.Connection || cmd.Person != a.person || p.Provider != prov || p.Endpoint != endpoint || p.Attempt < 1 || !provider.ValidToken(secret) {
return refuse("provider_refused")
}
dir, err := pinHome(a.home)
@@ -504,7 +532,7 @@ func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretC
return err
}
defer dir.Close()
- err = c.keep(ctx, a.id, dir, secret, func(t *sql.Tx) error {
+ err = c.keep(ctx, a.id, a.kind, dir, secret, func(t *sql.Tx) error {
if _, err := t.Exec("INSERT INTO seen_seals(connection_id, attempt, frame_id, created_at) VALUES(?,?,?,?)", s.ConnectionID, s.Attempt, frameID, now()); err != nil {
return err
}
@@ -531,7 +559,7 @@ func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretC
// record, the rest of that transaction), and the staging file is renamed
// to the token file, the directory synced. Not committed, nothing of it
// stays. errNotWaiting: the attempt was not waiting for it (a cancel won).
-func (c *Connector) keep(ctx context.Context, id string, dir *os.File, secret []byte, record func(*sql.Tx) error) error {
+func (c *Connector) keep(ctx context.Context, id, kind string, dir *os.File, secret []byte, record func(*sql.Tx) error) error {
err := stage(dir, secret)
clear(secret)
if err != nil {
@@ -541,7 +569,7 @@ func (c *Connector) keep(ctx context.Context, id string, dir *os.File, secret []
return err
}
err = c.State.tx(ctx, func(t *sql.Tx) error {
- res, err := t.Exec("UPDATE connect_attempts SET secret=?, kind=? WHERE id=? AND state='running' AND cancelled=0 AND secret=''", credentialPresent, wire.KindToken, id)
+ res, err := t.Exec("UPDATE connect_attempts SET secret=?, kind=? WHERE id=? AND state='running' AND cancelled=0 AND secret=''", credentialPresent, kind, id)
if err != nil {
return err
}
diff --git a/internal/wire/connections.go b/internal/wire/connections.go
index 90687a4f..11dfe37c 100644
--- a/internal/wire/connections.go
+++ b/internal/wire/connections.go
@@ -59,6 +59,10 @@ var ConnectReasons = map[string]bool{
"runner_offline": true,
"identity_mismatch": true,
"already_connected": true,
+ // An API-key connection: the provider refused the key, or listed no
+ // model Equipo can price (ProtocolMetered).
+ "key_refused": true,
+ "no_priced_model": true,
}
// EventConnection fires on every state or headroom change of one of the
diff --git a/internal/wire/metered.go b/internal/wire/metered.go
index 2a9ba0de..2d7a2a9d 100644
--- a/internal/wire/metered.go
+++ b/internal/wire/metered.go
@@ -45,6 +45,10 @@ type APIKeyProvider struct {
Name string
Harness string
Upstream string
+ // APIPath is the provider's OpenAI-compatible base path under
+ // Upstream: models at APIPath+"/models", completions at
+ // APIPath+"/chat/completions" (§2.2, §4).
+ APIPath string
Endpoint string
PerToken bool
Overflow bool
@@ -53,7 +57,7 @@ type APIKeyProvider struct {
// APIKeyProviders are the providers an API key connects, by name.
var APIKeyProviders = map[string]APIKeyProvider{
- ProviderTensorX: {Name: "TensorX", Harness: HarnessPi, Upstream: "https://api.tensorx.ai", Endpoint: "https://api.tensorx.ai:443", PerToken: true, Currency: "USD"},
+ ProviderTensorX: {Name: "TensorX", Harness: HarnessPi, Upstream: "https://api.tensorx.ai", APIPath: "/v1", Endpoint: "https://api.tensorx.ai:443", PerToken: true, Currency: "USD"},
}
// Billing is how a new connection for p is billed, given the person's
@@ -66,6 +70,15 @@ func (p APIKeyProvider) Billing(paygOff bool) string {
return BillingMetered
}
+// Holds a metered connection's guard gives (§2.3, §7): its one slot is
+// busy, its budget is reached, or its spend is unknown. A question held
+// by the guard reports one as its reason while it waits.
+const (
+ HoldBusy = "busy"
+ HoldBudget = "budget"
+ HoldSpendUnknown = "spend_unknown"
+)
+
// ErrConfirmation refuses an API-key connection without the
// confirmations its billing needs (§2.1).
var ErrConfirmation = errors.New("wire: the connection needs its confirmations")
diff --git a/internal/wire/questions.go b/internal/wire/questions.go
index e3e18b85..b670f28b 100644
--- a/internal/wire/questions.go
+++ b/internal/wire/questions.go
@@ -173,4 +173,9 @@ var AnswerReasons = map[string]bool{
"task_ended": true,
// limited: the step's own connection is limited by its provider now.
"limited": true,
+ // A question held by its metered connection's guard (queued, with
+ // the hold as its reason; ProtocolMetered).
+ HoldBusy: true,
+ HoldBudget: true,
+ HoldSpendUnknown: true,
}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index 7e266324..f2bb053c 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -480,6 +480,9 @@ func Encode(f Frame, protocol int) (Frame, error) {
if c, ok := body.(*ConnectCommand); ok && c.Kind == KindAPIKey {
return Frame{}, fmt.Errorf("%w: an API-key connection at protocol %d", ErrProtocol, protocol)
}
+ if a, ok := body.(*AnswerReport); ok && a.State == QuestionQueued {
+ return Frame{}, fmt.Errorf("%w: a held question at protocol %d", ErrProtocol, protocol)
+ }
changed = downgradeMetered(body)
}
if h, ok := body.(*Hello); ok && protocol < ProtocolPreviewHost {