package wire_test import ( "bytes" "encoding/json" "errors" "strings" "testing" "amadan.net/oficina/equipo/internal/wire" ) // frozen16Providers are the API-key providers a protocol 16 or older // peer knows (S1's table): any other provider value is one it cannot // read. var frozen16Providers = map[string]bool{wire.ProviderTensorX: true} // frozen16Harnesses are the harnesses of API-key connections at 16. var frozen16Harnesses = map[string]bool{"": true, wire.HarnessPi: true} // providersIn are every provider and harness value a frame's body names, // at any depth: connections, usage rows and reports. func providersIn(t *testing.T, raw []byte) (providers, harnesses []string) { t.Helper() var walk func(v any) walk = func(v any) { switch x := v.(type) { case map[string]any: for k, val := range x { if s, ok := val.(string); ok { switch k { case "provider": providers = append(providers, s) case "harness": harnesses = append(harnesses, s) } } walk(val) } case []any: for _, e := range x { walk(e) } } } var v any if err := json.Unmarshal(raw, &v); err != nil { t.Fatal(err) } walk(v) return providers, harnesses } // Protocol 17 (ProtocolOpenCode) adds the OpenCode Go provider behind the // OpenCode harness (connectors spec §4.2, slice S5). Below it, nothing an // older peer is sent names that provider or harness: its connections // leave hello and sync, its usage rows leave every report, and a connect // or a report about one is refused. At 17 nothing changes. func TestEncodeBelowProtocol17DropsOpenCode(t *testing.T) { if wire.ProtocolOpenCode != wire.Protocol17 || wire.ProtocolCurrent != wire.ProtocolDesign { t.Fatalf("opencode %d, current %d", wire.ProtocolOpenCode, wire.ProtocolCurrent) } budget := &wire.Budget{Day: 1_000_000, Month: 10_000_000, Currency: "USD", Revision: 1} spend := &wire.Spend{Currency: "USD"} held := []wire.HeldConnection{ {LocalID: "tensorx-a", Person: "p", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: budget, Spend: spend}, {LocalID: "opencode-go-b", Person: "p", Provider: wire.ProviderOpenCodeGo, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessOpenCode, Upstream: "https://opencode.ai", Billing: wire.BillingMetered, Model: "glm-5.3", Budget: budget, Spend: spend}, } n := int64(10) rows := []wire.Usage{{Provider: wire.ProviderTensorX, Connection: "tensorx-a", Model: "z-ai/glm-5.3", InputTokens: &n, OutputTokens: &n, Complete: true}, {Provider: wire.ProviderOpenCodeGo, Connection: "opencode-go-b", Model: "glm-5.3", InputTokens: &n, OutputTokens: &n, Complete: true}} frame := func(id, typ string, v any) wire.Frame { f, err := wire.NewFrame(id, typ, v) if err != nil { t.Fatal(err) } return f } kept := []wire.Frame{ frame("h", wire.FrameHello, wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: held, Protocol: wire.ProtocolCurrent}), frame("s", wire.FrameSync, wire.Sync{Connections: held}), frame("u", wire.FrameUsage, wire.UsageReport{Rows: rows}), frame("st", wire.FrameStep, wire.StepReport{TaskID: "t", StepID: "s", Attempt: 1, State: wire.StepDone, Usage: rows}), frame("a", wire.FrameAnswer, wire.AnswerReport{TaskID: "t", QuestionID: "q", Attempt: 1, State: wire.QuestionAnswered, Text: "ok", Usage: rows}), } for _, f := range kept { if same, err := wire.Encode(f, wire.Protocol17); err != nil || string(same.Data) != string(f.Data) { t.Fatalf("%s changed at 17: %v", f.Type, err) } for _, p := range []int{wire.Protocol16, wire.Protocol15} { old, err := wire.Encode(f, p) if err != nil { t.Fatalf("%s at %d: %v", f.Type, p, err) } providers, harnesses := providersIn(t, old.Data) sawTensorX := false for _, name := range providers { if _, apiKey := wire.APIKeyProviders[name]; apiKey && !frozen16Providers[name] { t.Fatalf("%s at %d names provider %q, which an older peer cannot read: %s", f.Type, p, name, old.Data) } sawTensorX = sawTensorX || name == wire.ProviderTensorX } if !sawTensorX { t.Fatalf("%s at %d lost the TensorX entry too: %s", f.Type, p, old.Data) } for _, h := range harnesses { if !frozen16Harnesses[h] { t.Fatalf("%s at %d names harness %q: %s", f.Type, p, h, old.Data) } } if _, _, err := wire.ParseFrame(mustFrame(t, old)); err != nil { t.Fatalf("%s at %d does not parse: %v", f.Type, p, err) } } } if len(held) != 2 || len(rows) != 2 { t.Fatal("Encode changed the caller's values") } refused := []wire.Frame{ frame("c", wire.FrameConnect, wire.ConnectCommand{Connection: "c1", Person: "p", Provider: wire.ProviderOpenCodeGo, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: budget}), frame("r", wire.FrameConnection, wire.ConnectionReport{Connection: "c1", Person: "p", Provider: wire.ProviderOpenCodeGo, State: wire.ConnHealthy}), frame("r2", wire.FrameConnection, wire.ConnectionReport{Person: "p", LocalID: "opencode-go-b", Provider: wire.ProviderOpenCodeGo, State: wire.ConnSignInAgain}), } for _, f := range refused { if _, err := wire.Encode(f, wire.Protocol17); err != nil { t.Fatalf("%s refused at 17: %v", f.Type, err) } for _, p := range []int{wire.Protocol16, wire.Protocol15} { if _, err := wire.Encode(f, p); !errors.Is(err, wire.ErrProtocol) { t.Fatalf("%s about OpenCode Go encoded at %d: %v", f.Type, p, err) } } } // A TensorX connect still goes to a protocol 16 or 15 runner. tx := frame("c", wire.FrameConnect, wire.ConnectCommand{Connection: "c1", Person: "p", Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: budget}) for _, p := range []int{wire.Protocol16, wire.Protocol15} { if _, err := wire.Encode(tx, p); err != nil { t.Fatalf("a TensorX connect refused at %d: %v", p, err) } } } // Mixed versions across OpenCode (17) and publishing (16), on the same // frames. A protocol 16 runner is never sent an OpenCode Go connect and // never names that provider, yet keeps every publish frame and field // whole. At 17 both go out unchanged. At 15 both are downgraded: the // OpenCode Go connect and the publish dispatch are refused, and the // OpenCode Go rows and the publish result and sites capability dropped. func TestEncodeMixedVersionsOpenCodeAndPublish(t *testing.T) { frame := func(id, typ string, v any) wire.Frame { f, err := wire.NewFrame(id, typ, v) if err != nil { t.Fatal(err) } return f } budget := &wire.Budget{Day: 1_000_000, Month: 10_000_000, Currency: "USD", Revision: 1} n := int64(10) rows := []wire.Usage{{Provider: wire.ProviderTensorX, Connection: "tensorx-a", Model: "z-ai/glm-5.3", InputTokens: &n, OutputTokens: &n, Complete: true}, {Provider: wire.ProviderOpenCodeGo, Connection: "opencode-go-b", Model: "glm-5.3", InputTokens: &n, OutputTokens: &n, Complete: true}} held := []wire.HeldConnection{{LocalID: "opencode-go-b", Person: "p", Provider: wire.ProviderOpenCodeGo, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessOpenCode, Upstream: "https://opencode.ai", Billing: wire.BillingMetered, Model: "glm-5.3", Budget: budget, Spend: &wire.Spend{Currency: "USD"}}} connect := frame("c", wire.FrameConnect, wire.ConnectCommand{Connection: "c1", Person: "p", Provider: wire.ProviderOpenCodeGo, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: budget}) publish := frame("d", wire.FrameDispatch, wire.DispatchCommand{Person: "p", TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistPublish, Findings: []wire.Finding{}, CandidateSHA: strings.Repeat("e", 40), Publish: &wire.PublishDispatch{App: "site-sample", Into: "main"}}) check := frame("l", wire.FrameLease, wire.LeaseCheck{Generation: 1, StepID: "s", Attempt: 1, Purpose: wire.LeasePurposePublish, Digest: strings.Repeat("a", 64)}) built := wire.StepReport{TaskID: "tk", StepID: "s", Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}, Usage: rows, Publish: &wire.PublishResult{Phase: wire.PublishBuilt, Digest: strings.Repeat("a", 64), Files: 2, Bytes: 40}} report := frame("r", wire.FrameStep, built) hello := frame("h", wire.FrameHello, wire.Hello{Protocol: wire.ProtocolCurrent, Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: held, Capabilities: &wire.Capabilities{Sites: true, Tags: []string{wire.TagLinux}}}) // At 17 both go out whole, but a publish dispatch, place-bound since // 31, is refused below 31. for _, f := range []wire.Frame{publish, check} { if _, err := wire.Encode(f, wire.Protocol17); !errors.Is(err, wire.ErrProtocol) { t.Fatalf("a publish %s encoded at 17: %v", f.Type, err) } } for _, f := range []wire.Frame{connect, report, hello} { if same, err := wire.Encode(f, wire.Protocol17); err != nil || !bytes.Equal(same.Data, f.Data) { t.Fatalf("%s changed at 17: %v", f.Type, err) } } // At 16 OpenCode Go is refused or dropped; publish is untouched. if _, err := wire.Encode(connect, wire.Protocol16); !errors.Is(err, wire.ErrProtocol) { t.Fatalf("an OpenCode Go connect encoded at 16: %v", err) } got, err := wire.Encode(report, wire.Protocol16) if err != nil || strings.Contains(string(got.Data), wire.ProviderOpenCodeGo) || !strings.Contains(string(got.Data), `"publish":`) || !strings.Contains(string(got.Data), wire.ProviderTensorX) { t.Fatalf("report at 16 (OpenCode Go rows out, publish result kept): %v %s", err, got.Data) } got, err = wire.Encode(hello, wire.Protocol16) if err != nil || strings.Contains(string(got.Data), wire.ProviderOpenCodeGo) || !strings.Contains(string(got.Data), `"sites":true`) { t.Fatalf("hello at 16 (OpenCode Go out, sites kept): %v %s", err, got.Data) } // At 15 both are downgraded, OpenCode's step first, then publish's. for _, f := range []wire.Frame{connect, publish, check} { if _, err := wire.Encode(f, wire.Protocol15); !errors.Is(err, wire.ErrProtocol) { t.Fatalf("%s encoded at 15: %v", f.Type, err) } } got, err = wire.Encode(report, wire.Protocol15) if err != nil || strings.Contains(string(got.Data), wire.ProviderOpenCodeGo) || strings.Contains(string(got.Data), `"publish":`) || !strings.Contains(string(got.Data), wire.ProviderTensorX) { t.Fatalf("report at 15 (OpenCode Go rows and publish result out): %v %s", err, got.Data) } got, err = wire.Encode(hello, wire.Protocol15) if err != nil || strings.Contains(string(got.Data), wire.ProviderOpenCodeGo) || strings.Contains(string(got.Data), `"sites"`) { t.Fatalf("hello at 15 (OpenCode Go and sites out): %v %s", err, got.Data) } if _, _, err := wire.ParseFrame(mustFrame(t, got)); err != nil { t.Fatalf("hello at 15 does not parse: %v", err) } } // OpenCode Go is metered whatever the person says (§0 decision 7: no // standing overflow-off setting is confirmed), so a pay-as-you-go // confirmation is refused and the limit confirmation is required. Its // models list and its chat completions live under different paths. func TestOpenCodeGoProvider(t *testing.T) { p, ok := wire.APIKeyProviders[wire.ProviderOpenCodeGo] if !ok { t.Fatal("no OpenCode Go row") } if p.Harness != wire.HarnessOpenCode || p.Upstream != "https://opencode.ai" || p.Endpoint != "https://opencode.ai:443" || p.Currency != "USD" { t.Fatalf("row %+v", p) } if p.Billing(true) != wire.BillingMetered || p.Billing(false) != wire.BillingMetered { t.Fatal("OpenCode Go not always metered") } if p.CheckConfirmations(true, true) == nil { t.Fatal("a pay-as-you-go confirmation accepted for OpenCode Go") } if p.CheckConfirmations(false, false) == nil { t.Fatal("OpenCode Go accepted without the limit confirmation") } if p.CheckConfirmations(true, false) != nil { t.Fatal("OpenCode Go refused with the limit confirmed") } if p.ModelsURL() != "https://opencode.ai/inference/go/v1/models" || p.CompletionsURL() != "https://opencode.ai/inference/go/openai/v1/chat/completions" || p.BaseURL() != "https://opencode.ai/inference/go/openai/v1" { t.Fatalf("paths %s %s %s", p.ModelsURL(), p.CompletionsURL(), p.BaseURL()) } tx := wire.APIKeyProviders[wire.ProviderTensorX] if tx.ModelsURL() != "https://api.tensorx.ai/v1/models" || tx.CompletionsURL() != "https://api.tensorx.ai/v1/chat/completions" { t.Fatalf("TensorX paths %s %s", tx.ModelsURL(), tx.CompletionsURL()) } }