oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "encoding/json"
6 "net/http"
7 "net/http/httptest"
8 "net/netip"
9 "os"
10 "path/filepath"
11 "strings"
12 "sync"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/runner/connect"
17 "amadan.net/oficina/equipo/internal/runner/metered"
18 "amadan.net/oficina/equipo/internal/sealbox"
19 "amadan.net/oficina/equipo/internal/wire"
20)
21
22// fakeTensorX is an OpenAI-compatible provider on 127.0.0.1 standing in
23// for TensorX: one key it accepts, a model list, and one-token
24// completions it counts. No real provider is called.
25type fakeTensorX struct {
26 *httptest.Server
27 mu sync.Mutex
28 key string
29 probes []string
30 usage string
31 // answered, when set, is the model the provider says answered;
32 // hold, when set, keeps a completion open until it is closed.
33 answered string
34 hold chan struct{}
35 started chan struct{}
36 // swap names, per model asked for, the model that answers instead;
37 // gone, the models it does not have (404, model_not_found).
38 swap map[string]string
39 gone map[string]bool
40 // list, when set, is the model list it answers.
41 list string
42}
43
44func newFakeTensorX(t *testing.T, key string) *fakeTensorX {
45 f := &fakeTensorX{key: key, usage: `{"prompt_tokens":9,"completion_tokens":1}`}
46 f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
47 f.mu.Lock()
48 key, usage := f.key, f.usage
49 f.mu.Unlock()
50 if r.Header.Get("Authorization") != "Bearer "+key {
51 w.WriteHeader(http.StatusUnauthorized)
52 return
53 }
54 switch r.Method + " " + r.URL.Path {
55 case "GET /v1/models":
56 f.mu.Lock()
57 list := f.list
58 f.mu.Unlock()
59 if list == "" {
60 list = `{"data":[{"id":"z-ai/glm-5.3"},{"id":"vendor/unpriced"}]}`
61 }
62 w.Write([]byte(list))
63 case "POST /v1/chat/completions":
64 var in struct {
65 Model string `json:"model"`
66 MaxTokens int `json:"max_tokens"`
67 }
68 if json.NewDecoder(r.Body).Decode(&in) != nil || in.MaxTokens != 1 {
69 w.WriteHeader(http.StatusBadRequest)
70 return
71 }
72 f.mu.Lock()
73 f.probes = append(f.probes, in.Model)
74 model, hold, started := in.Model, f.hold, f.started
75 if f.answered != "" {
76 model = f.answered
77 }
78 if other, ok := f.swap[in.Model]; ok {
79 model = other
80 }
81 gone := f.gone[in.Model]
82 f.mu.Unlock()
83 if gone {
84 w.WriteHeader(http.StatusNotFound)
85 w.Write([]byte(`{"error":{"code":"model_not_found"}}`))
86 return
87 }
88 if hold != nil {
89 started <- struct{}{}
90 <-hold
91 }
92 w.Write([]byte(`{"model":"` + model + `","choices":[{"message":{"content":"ok"}}],"usage":` + usage + `}`))
93 default:
94 w.WriteHeader(http.StatusNotFound)
95 }
96 }))
97 t.Cleanup(f.Close)
98 if !strings.HasPrefix(f.URL, "http://127.0.0.1:") {
99 t.Fatalf("fake provider not on loopback: %s", f.URL)
100 }
101 return f
102}
103
104func (f *fakeTensorX) set(key, usage string) {
105 f.mu.Lock()
106 defer f.mu.Unlock()
107 if key != "" {
108 f.key = key
109 }
110 if usage != "" {
111 f.usage = usage
112 }
113}
114
115func (f *fakeTensorX) probeCount() int {
116 f.mu.Lock()
117 defer f.mu.Unlock()
118 return len(f.probes)
119}
120
121// meteredConnector is a connector with the metered guard, its API-key
122// providers pointed at fake.
123func (r *tokenRig) meteredConnector(fake *fakeTensorX) *Connector {
124 if r.conns.Meter == nil {
125 r.conns.Meter = &metered.Meter{DB: r.state.db}
126 }
127 c := r.connector()
128 // The production transport, with the fake's loopback address allowed.
129 c.http, c.origin = connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), func(string) string { return fake.URL }
130 return c
131}
132
133func (r *tokenRig) startAPIKey(c *Connector, id string) string {
134 r.t.Helper()
135 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}}
136 if err := c.Accept(r.ctx, "f-connect-"+id, cmd); err != nil {
137 r.t.Fatal(err)
138 }
139 r.card(id, wire.PromptAPIKey)
140 var home string
141 _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home)
142 if home == "" || filepath.Dir(home) != r.root || !strings.HasPrefix(filepath.Base(home), "tensorx-") {
143 r.t.Fatalf("attempt home %q", home)
144 }
145 return home
146}
147
148func (r *tokenRig) card(id, kind string) wire.ConnectPrompt {
149 r.t.Helper()
150 var p wire.ConnectPrompt
151 r.waitFor(func() bool {
152 for _, v := range r.reports(id) {
153 if v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == kind {
154 p = *v.Prompt
155 return true
156 }
157 }
158 return false
159 }, "the "+kind+" card")
160 return p
161}
162
163// sealedKey is a box for an API-key attempt, as the page seals it.
164func (r *tokenRig) sealedKey(id, key string, change func(*wire.SealedPayload)) wire.SecretCommand {
165 r.t.Helper()
166 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()}
167 if change != nil {
168 change(&p)
169 }
170 s, err := sealbox.Seal(r.keys.PublicString(), p)
171 if err != nil {
172 r.t.Fatal(err)
173 }
174 return wire.SecretCommand{Connection: id, Person: connPerson, Sealed: s}
175}
176
177func (r *tokenRig) held(local string) (wire.HeldConnection, bool) {
178 for _, h := range r.conns.Held() {
179 if h.LocalID == local {
180 return h, true
181 }
182 }
183 return wire.HeldConnection{}, false
184}
185
186// eligibleChoices are a models card's models that can be allowed.
187func eligibleChoices(p wire.ConnectPrompt) []string {
188 var out []string
189 for _, c := range p.Choices {
190 if c.Eligible {
191 out = append(out, c.ID)
192 }
193 }
194 return out
195}
196
197func (r *tokenRig) usageFrames() []wire.UsageReport {
198 frames, _, err := r.state.Unacked(context.Background(), 0)
199 if err != nil {
200 r.t.Fatal(err)
201 }
202 var out []wire.UsageReport
203 for _, f := range frames {
204 var v wire.UsageReport
205 if f.Type == wire.FrameUsage && json.Unmarshal(f.Data, &v) == nil {
206 out = append(out, v)
207 }
208 }
209 return out
210}
211
212// TestAPIKeyConnectionRoundTrip is S1's sealed API-key paste on the
213// runner: the box bound to TensorX's origin is delivered into the home
214// (0600); the runner reads the model list and offers the priced ones;
215// the picked model's one-token probe against the fake provider passes
216// the metered guard and is charged as a usage row with role probe; the
217// connection is then healthy in hello with its budget and spend; Check
218// again probes again and a refused key reads sign_in_again; a budget
219// frame applies above the revision held; sign-out deletes the home and
220// the record. The key is in no frame and no log line.
221func TestAPIKeyConnectionRoundTrip(t *testing.T) {
222 const key = "tx-fake-key-fake-key"
223 r := newTokenRig(t)
224 fake := newFakeTensorX(t, key)
225 c := r.meteredConnector(fake)
226 home := r.startAPIKey(c, "cn_tx")
227 local := filepath.Base(home)
228 if !r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil)) {
229 t.Fatalf("secret refused: %v", r.errs)
230 }
231 // The models card (§16.1): every listed model, the priced and tiered
232 // ones eligible. An older instance would be said the one-model pick
233 // (Encode); its model frame is taken as a set of one.
234 p := r.card("cn_tx", wire.PromptModels)
235 if strings.Join(eligibleChoices(p), ",") != "z-ai/glm-5.3" || len(p.Choices) != 2 {
236 t.Fatalf("offered %+v", p.Choices)
237 }
238 if fake.probeCount() != 0 {
239 t.Fatal("probed before a model was picked")
240 }
241 // A model not offered changes nothing; the offered one runs the probe.
242 if err := c.Model(r.ctx, "f-model-0", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "vendor/unpriced"}); err != nil {
243 t.Fatal(err)
244 }
245 if err := c.Model(r.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"}); err != nil {
246 t.Fatal(err)
247 }
248 end := r.ended("cn_tx")
249 if end.State != wire.ConnHealthy || end.LocalID != local || end.Provider != wire.ProviderTensorX {
250 t.Fatalf("end %+v", end)
251 }
252 if fake.probeCount() != 1 {
253 t.Fatalf("probes %d", fake.probeCount())
254 }
255 raw, err := os.ReadFile(filepath.Join(home, ".oauth-token"))
256 info, _ := os.Stat(filepath.Join(home, ".oauth-token"))
257 if err != nil || string(raw) != key || info.Mode().Perm() != 0600 {
258 t.Fatalf("key file: %v", err)
259 }
260 usage := r.usageFrames()
261 if len(usage) != 1 || usage[0].ProbeID != "pr_cn_tx" || len(usage[0].Rows) != 1 {
262 t.Fatalf("probe usage %+v", usage)
263 }
264 row := usage[0].Rows[0]
265 // 9 input at 1.75 and 1 output at 4.50 per million: 16 + 5 micros.
266 if row.CostMicros == nil || *row.CostMicros != 21 || row.PriceVersion != "tensorx-2026-11-12" || row.Connection != local || !row.Complete {
267 t.Fatalf("probe row %+v", row)
268 }
269 h, ok := r.held(local)
270 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 {
271 t.Fatalf("held %+v %v", h, ok)
272 }
273 // Check again: another billable probe, charged.
274 if err := c.Check(r.ctx, "f-check-1", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil {
275 t.Fatal(err)
276 }
277 r.waitFor(func() bool { h, _ := r.held(local); return h.Spend != nil && h.Spend.Day == 42 }, "the second probe's charge")
278 // The provider refuses the key now: sign_in_again, nothing charged.
279 fake.set("rotated", "")
280 if err := c.Check(r.ctx, "f-check-2", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil {
281 t.Fatal(err)
282 }
283 r.waitFor(func() bool { h, _ := r.held(local); return h.State == wire.ConnSignInAgain }, "sign_in_again")
284 if h, _ := r.held(local); h.Spend.Day != 42 || h.Spend.Unknown {
285 t.Fatalf("a refused probe charged: %+v", h.Spend)
286 }
287 // Budget frames: applied above the revision held, else not.
288 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 {
289 t.Fatal(err)
290 }
291 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 {
292 t.Fatal(err)
293 }
294 // Security round finding 4: a frame for another connection under the
295 // same runner name changes nothing, and a frame already consumed is
296 // not applied again whatever it now says.
297 for frame, cmd := range map[string]wire.BudgetCommand{
298 "f-budget-other": {Connection: "cn_earlier", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 3, Month: 3, Revision: 7}},
299 "f-budget-1": {Connection: "cn_tx", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 4, Month: 4, Revision: 8}},
300 } {
301 if err := c.Budget(r.ctx, frame, cmd); err != nil {
302 t.Fatal(err)
303 }
304 }
305 if h, _ := r.held(local); h.Budget.Day != 2_000_000 || h.Budget.Month != 20_000_000 || h.Budget.Revision != 2 {
306 t.Fatalf("budget %+v", h.Budget)
307 }
308 // Nothing in the outbox or the log is the key.
309 frames, _, _ := r.state.Unacked(context.Background(), 0)
310 for _, f := range frames {
311 if strings.Contains(string(f.Data), key) {
312 t.Fatalf("%s frame carries the key", f.Type)
313 }
314 }
315 if strings.Contains(r.logs.String(), key) {
316 t.Fatal("the log carries the key")
317 }
318 // Sign out: the record, the home and the key go.
319 if err := c.Disconnect(r.ctx, "f-disconnect", wire.DisconnectCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil {
320 t.Fatal(err)
321 }
322 r.waitFor(func() bool {
323 for _, v := range r.reports("cn_tx") {
324 if v.State == wire.ConnSignedOut {
325 return true
326 }
327 }
328 return false
329 }, "signed out")
330 if _, err := os.Lstat(home); !os.IsNotExist(err) {
331 t.Fatalf("home left: %v", err)
332 }
333 if _, ok := r.held(local); ok {
334 t.Fatal("still held")
335 }
336 // Security round finding 4: a later connection never takes the same
337 // runner name, so no frame for this one can reach it.
338 again := r.startAPIKey(c, "cn_tx2")
339 if filepath.Base(again) == local || filepath.Base(home) == "tensorx-1" {
340 t.Fatalf("the runner name %q was reused (%q)", filepath.Base(again), local)
341 }
342}
343
344// TestAPIKeySignOutDuringAProbe (security round, finding 3): a sign-out
345// while a Check again's probe runs admits nothing more, waits for the
346// probe, commits its charge, and only then deletes the connection.
347func TestAPIKeySignOutDuringAProbe(t *testing.T) {
348 const key = "tx-fake-key-fake-key"
349 r := newTokenRig(t)
350 fake := newFakeTensorX(t, key)
351 c := r.meteredConnector(fake)
352 home := r.startAPIKey(c, "cn_tx")
353 local := filepath.Base(home)
354 r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil))
355 r.card("cn_tx", wire.PromptModels)
356 c.Model(r.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"})
357 if end := r.ended("cn_tx"); end.State != wire.ConnHealthy {
358 t.Fatalf("end %+v", end)
359 }
360 fake.mu.Lock()
361 fake.hold, fake.started = make(chan struct{}), make(chan struct{}, 8)
362 fake.mu.Unlock()
363 var release sync.Once
364 t.Cleanup(func() { release.Do(func() { close(fake.hold) }) })
365 checked := make(chan error, 1)
366 go func() {
367 checked <- c.Check(r.ctx, "f-check-1", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local})
368 }()
369 <-fake.started
370 out := make(chan error, 1)
371 go func() {
372 out <- c.Disconnect(r.ctx, "f-disconnect", wire.DisconnectCommand{Connection: "cn_tx", Person: connPerson, LocalID: local})
373 }()
374 r.waitFor(func() bool {
375 conn, ok, _ := metered.Get(r.ctx, r.state.db, local)
376 return ok && conn.Retiring
377 }, "the connection retiring")
378 if a, err := r.conns.Meter.Admit(r.ctx, local, metered.Holder{Step: "s-late", Attempt: 1, Role: metered.RoleEngineering}, nil); err != nil || a.Admitted {
379 t.Fatalf("admitted while signing out: %+v %v", a, err)
380 }
381 if _, ok, _ := metered.Get(r.ctx, r.state.db, local); !ok {
382 t.Fatal("deleted while its probe ran")
383 }
384 release.Do(func() { close(fake.hold) })
385 if err := <-out; err != nil {
386 t.Fatal(err)
387 }
388 <-checked
389 r.waitFor(func() bool {
390 _, ok, _ := metered.Get(r.ctx, r.state.db, local)
391 return !ok
392 }, "the connection removed")
393 var charged int
394 r.state.db.QueryRow("SELECT count(*) FROM budget_charge WHERE connection=? AND step LIKE 'pr_tensorx%'", local).Scan(&charged)
395 probes := 0
396 for _, u := range r.usageFrames() {
397 if strings.HasPrefix(u.ProbeID, "pr_"+local) {
398 probes++
399 }
400 }
401 if charged != 1 || probes != 1 {
402 t.Fatalf("the running probe's charge: %d rows, %d usage frames", charged, probes)
403 }
404}
405
406// TestAPIKeyProbeAnsweredByAnotherModel (security round, finding 6):
407// a probe answered by another model proves nothing; its usage is that
408// model's, and an unpriced one leaves the spend unknown.
409func TestAPIKeyProbeAnsweredByAnotherModel(t *testing.T) {
410 const key = "tx-fake-key-fake-key"
411 r := newTokenRig(t)
412 fake := newFakeTensorX(t, key)
413 c := r.meteredConnector(fake)
414 home := r.startAPIKey(c, "cn_tx")
415 local := filepath.Base(home)
416 r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil))
417 r.card("cn_tx", wire.PromptModels)
418 c.Model(r.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"})
419 if end := r.ended("cn_tx"); end.State != wire.ConnHealthy {
420 t.Fatalf("end %+v", end)
421 }
422 fake.mu.Lock()
423 fake.answered = "vendor/unpriced"
424 fake.mu.Unlock()
425 if err := c.Check(r.ctx, "f-check-1", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil {
426 t.Fatal(err)
427 }
428 r.waitFor(func() bool { h, _ := r.held(local); return h.Spend != nil && h.Spend.Unknown }, "spend unknown")
429 var row *wire.Usage
430 for _, u := range r.usageFrames() {
431 if strings.HasPrefix(u.ProbeID, "pr_"+local) {
432 row = &u.Rows[0]
433 }
434 }
435 if row == nil || row.Model != "vendor/unpriced" || row.CostMicros != nil {
436 t.Fatalf("the probe's row %+v", row)
437 }
438 // A new attempt answered by another model is not made a connection.
439 r2 := newTokenRig(t)
440 fake2 := newFakeTensorX(t, key)
441 fake2.answered = "z-ai/glm-5.3-flash"
442 c2 := r2.meteredConnector(fake2)
443 r2.startAPIKey(c2, "cn_tx")
444 r2.deliver(c2, "f-secret-1", r2.sealedKey("cn_tx", key, nil))
445 r2.card("cn_tx", wire.PromptModels)
446 c2.Model(r2.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"})
447 if end := r2.ended("cn_tx"); end.State == wire.ConnHealthy {
448 t.Fatalf("made a connection on another model's answer: %+v", end)
449 }
450}
451
452// TestAPIKeyBoxBoundToTheProvider: a box for an API-key attempt bound to
453// Claude's endpoint, or naming Claude, is refused and ends the attempt;
454// a key the provider refuses ends it key_refused, home and all.
455func TestAPIKeyBoxBoundToTheProvider(t *testing.T) {
456 const key = "tx-fake-key-fake-key"
457 r := newTokenRig(t)
458 fake := newFakeTensorX(t, key)
459 c := r.meteredConnector(fake)
460 for i, change := range []func(*wire.SealedPayload){
461 func(p *wire.SealedPayload) { p.Endpoint = wire.EndpointAnthropic },
462 func(p *wire.SealedPayload) { p.Provider = wire.ProviderClaude },
463 } {
464 id := "cn_bad" + string(rune('a'+i))
465 home := r.startAPIKey(c, id)
466 r.deliver(c, "f-secret-"+id, r.sealedKey(id, key, change))
467 if end := r.ended(id); end.State != wire.ConnError || end.Reason != "provider_refused" {
468 t.Fatalf("%s: %+v", id, end)
469 }
470 if _, err := os.Lstat(home); !os.IsNotExist(err) {
471 t.Fatalf("%s: home left", id)
472 }
473 }
474 home := r.startAPIKey(c, "cn_wrong")
475 r.deliver(c, "f-secret-wrong", r.sealedKey("cn_wrong", "tx-not-the-key", nil))
476 if end := r.ended("cn_wrong"); end.State != wire.ConnError || end.Reason != "key_refused" {
477 t.Fatalf("wrong key: %+v", end)
478 }
479 if _, err := os.Lstat(home); !os.IsNotExist(err) {
480 t.Fatal("refused key's home left")
481 }
482 if fake.probeCount() != 0 || len(r.conns.Held()) != 0 {
483 t.Fatal("a refused attempt probed or stayed")
484 }
485}
486
487// OpenCode Go connects as TensorX does, at its own paths: the model list
488// at /inference/go/v1/models, the probe at /inference/go/openai/v1; only
489// models Go's price table knows are offered (not the free ones, nor
490// those Go serves on another API); the probe's row is priced by the
491// table although Go says cost 0 within its plan; the connection is run
492// by OpenCode, metered.
493func TestAPIKeyOpenCodeGoConnect(t *testing.T) {
494 const key = "go-fake-key-fake-key"
495 r := newTokenRig(t)
496 var probes []string
497 var mu sync.Mutex
498 fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) {
499 if q.Header.Get("Authorization") != "Bearer "+key {
500 w.WriteHeader(http.StatusUnauthorized)
501 return
502 }
503 switch q.Method + " " + q.URL.Path {
504 case "GET /inference/go/v1/models":
505 w.Write([]byte(`{"data":[{"id":"glm-5.3"},{"id":"beam-free"},{"id":"qwen3.8-max"}]}`))
506 case "POST /inference/go/openai/v1/chat/completions":
507 var in struct {
508 Model string `json:"model"`
509 MaxTokens int `json:"max_tokens"`
510 }
511 if json.NewDecoder(q.Body).Decode(&in) != nil || in.MaxTokens != 1 {
512 w.WriteHeader(http.StatusBadRequest)
513 return
514 }
515 mu.Lock()
516 probes = append(probes, in.Model)
517 mu.Unlock()
518 w.Write([]byte(`{"model":"` + in.Model + `","choices":[{"message":{"content":"ok"}}],"usage":{"prompt_tokens":9,"completion_tokens":1,"cost":0,"opencode":{"billing_source":"go","allowance":0.00002}}}`))
519 default:
520 w.WriteHeader(http.StatusNotFound)
521 }
522 }))
523 t.Cleanup(fake.Close)
524 r.conns.Meter = &metered.Meter{DB: r.state.db}
525 c := r.connector()
526 c.http, c.origin = connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), func(string) string { return fake.URL }
527 cmd := wire.ConnectCommand{Connection: "cn_go", Person: connPerson, Provider: wire.ProviderOpenCodeGo, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth, Currency: "USD", Revision: 1}}
528 if err := c.Accept(r.ctx, "f-connect-cn_go", cmd); err != nil {
529 t.Fatal(err)
530 }
531 r.card("cn_go", wire.PromptAPIKey)
532 var home string
533 _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", "cn_go").Scan(&home)
534 local := filepath.Base(home)
535 if !strings.HasPrefix(local, "opencode-go-") {
536 t.Fatalf("home %q", home)
537 }
538 box := r.sealedKey("cn_go", key, func(p *wire.SealedPayload) {
539 p.Provider, p.Endpoint = wire.ProviderOpenCodeGo, wire.APIKeyProviders[wire.ProviderOpenCodeGo].Endpoint
540 })
541 if !r.deliver(c, "f-secret-go", box) {
542 t.Fatalf("secret refused: %v", r.errs)
543 }
544 if p := r.card("cn_go", wire.PromptModels); strings.Join(eligibleChoices(p), ",") != "glm-5.3" {
545 t.Fatalf("offered %v", p.Models)
546 }
547 if err := c.Model(r.ctx, "f-model-go", wire.ModelCommand{Connection: "cn_go", Person: connPerson, Model: "glm-5.3"}); err != nil {
548 t.Fatal(err)
549 }
550 if end := r.ended("cn_go"); end.State != wire.ConnHealthy || end.Provider != wire.ProviderOpenCodeGo {
551 t.Fatalf("end %+v", end)
552 }
553 usage := r.usageFrames()
554 if len(usage) != 1 || len(usage[0].Rows) != 1 {
555 t.Fatalf("probe usage %+v", usage)
556 }
557 row := usage[0].Rows[0]
558 // 9 input at 1.40 and 1 output at 4.40 per million: 13 + 5 micros.
559 if row.CostMicros == nil || *row.CostMicros != 18 || row.PriceVersion != "opencode-go-2026-11-12" || row.Provider != wire.ProviderOpenCodeGo {
560 t.Fatalf("probe row %+v", row)
561 }
562 h, ok := r.held(local)
563 if !ok || h.Harness != wire.HarnessOpenCode || h.Upstream != "https://opencode.ai" || h.Billing != wire.BillingMetered || h.Model != "glm-5.3" || h.Spend == nil || h.Spend.Day != 18 {
564 t.Fatalf("held %+v %v", h, ok)
565 }
566 if b := r.conns.MeteredMine(r.ctx, connPerson); len(b) != 1 || b[0].Family != "glm" || harnessOf(b[0]) != wire.HarnessOpenCode {
567 t.Fatalf("bindings %+v", b)
568 }
569 mu.Lock()
570 defer mu.Unlock()
571 if len(probes) != 1 || probes[0] != "glm-5.3" {
572 t.Fatalf("probes %v", probes)
573 }
574}
575