package wire_test import ( "bytes" "encoding/json" "errors" "fmt" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // Frozen protocol 17 schemas (main at 5880ab10, before S5b): the JSON // keys each body had at 17, written out so that a field S5b added // cannot slip into what an older peer is sent. var ( frozen17Dispatch = keySet("person task_id step_id attempt specialist repo branch base_sha title brief findings candidate_sha republish from_attempt avoid_account round feedback rebase from_base needs runner_id revert_sha hosted_checks unsandboxed research research_note priority by release priority_revision housekeeping publish") frozen17Held = keySet("local_id person provider kind label state plan headroom expires_at expires_estimated harness upstream billing model budget spend") frozen17Usage = keySet("provider connection model attempt outcome complete input_tokens cached_input_tokens cache_write_tokens output_tokens reasoning_output_tokens turns cost_micros currency price_version cost_reported_micros") frozen17Prompt = keySet("kind url code attempt wrong_code models") // frozen17Prompts and frozen17AnswerReasons are the values a // protocol 17 instance knows. frozen17Prompts = keySet("authorize device token api_key model") frozen17AnswerReasons = keySet("cancelled interrupted runner_restarted turn_timeout provider_failed provider_rejected policy_rejected account_unavailable sign_in_again clone_failed candidate_unavailable session_gone superseded task_ended limited busy budget spend_unknown") ) // keysAt checks every object under key name (at any depth) against a // frozen schema. func keysAt(t *testing.T, what string, raw []byte, name string, schema map[string]bool) { t.Helper() var walk func(key string, v any) walk = func(key string, v any) { switch x := v.(type) { case map[string]any: if key == name { for k := range x { if !schema[k] { t.Fatalf("%s: %s carries %q, which a protocol 17 peer refuses: %s", what, name, k, raw) } } } for k, val := range x { walk(k, val) } case []any: for _, e := range x { walk(key, e) } } } var v any if err := json.Unmarshal(raw, &v); err != nil { t.Fatal(err) } walk("", v) } func modelsFrames(t *testing.T) map[string]wire.Frame { frame := func(id, typ string, v any) wire.Frame { f, err := wire.NewFrame(id, typ, v) if err != nil { t.Fatal(err) } return f } n := int64(10) failed := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC) row := wire.Usage{Provider: wire.ProviderTensorX, Connection: "tensorx-a", Model: "z-ai/glm-5.3-flash", InputTokens: &n, OutputTokens: &n, Complete: true, Family: "glm", Tier: "cheap", TierVersion: "tiers-2026-11-12", ModelMismatch: true} 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-flash", Budget: &wire.Budget{Day: 1, Month: 2, Currency: "USD"}, Spend: &wire.Spend{Currency: "USD"}, Models: []wire.ModelState{{ID: "z-ai/glm-5.3-flash", State: wire.ModelHealthy, Family: "glm", Tier: "cheap"}, {ID: "z-ai/glm-5.3", State: wire.ModelUnhealthy, FailedAt: &failed, Reason: wire.ModelNotFound}}, ModelsRevision: 2, Choices: []wire.ModelChoice{{ID: "z-ai/glm-5.3", Eligible: true}, {ID: "vendor/unpriced"}}} return map[string]wire.Frame{ "models": frame("m", wire.FrameModels, wire.ModelsCommand{Connection: "cn", Person: "p", LocalID: "tensorx-a", Allowed: []string{"z-ai/glm-5.3"}, Revision: 2}), "hello": frame("h", wire.FrameHello, wire.Hello{Protocol: wire.ProtocolCurrent, Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{held}}), "sync": frame("y", wire.FrameSync, wire.Sync{Connections: []wire.HeldConnection{held}}), "dispatch": frame("d", wire.FrameDispatch, wire.DispatchCommand{Person: "p", TaskID: "tk", StepID: "s", Attempt: 1, Specialist: wire.SpecialistReview, Findings: []wire.Finding{}, AvoidAccount: "tensorx-a", AvoidFamily: "glm"}), "usage": frame("u", wire.FrameUsage, wire.UsageReport{StepID: "s", Rows: []wire.Usage{row}}), "step": frame("s", wire.FrameStep, wire.StepReport{TaskID: "tk", StepID: "s", Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}, Usage: []wire.Usage{row}}), "answer": frame("a", wire.FrameAnswer, wire.AnswerReport{TaskID: "tk", QuestionID: "q", Attempt: 1, State: wire.QuestionFailed, Reason: wire.ReasonModelUnavailable, Usage: []wire.Usage{row}}), "reply": frame("p", wire.FrameReply, wire.Reply{TurnID: "t", Attempt: 1, Text: "ok", Usage: []wire.Usage{row}}), "prompt": frame("c", wire.FrameConnection, wire.ConnectionReport{Connection: "cn", Person: "p", Provider: wire.ProviderTensorX, State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptModels, Choices: []wire.ModelChoice{ {ID: "vendor/unpriced"}, {ID: "z-ai/glm-5.3", Eligible: true, Family: "glm", Tier: "strong"}, {ID: "z-ai/glm-5.3-flash", Eligible: true, Family: "glm", Tier: "cheap"}}}}), } } // Protocol 18 (ProtocolModels, slice S5b): at 18 every frame goes out // whole. Below it, at every lower protocol, nothing an older peer is // sent carries a key or a value protocol 17 did not have: the models // frame is refused; the models card is said as the one-model pick of // the eligible models; the held set, the usage fields and avoid_family // go; model_unavailable is said as account_unavailable. Each lower // protocol is checked because an older step in Encode's chain could // undo a newer one (S5's bug). func TestEncodeBelowProtocol18AgainstFrozenSchemas(t *testing.T) { if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.ProtocolDesign { t.Fatalf("models %d, current %d", wire.ProtocolModels, wire.ProtocolCurrent) } fs := modelsFrames(t) for name, f := range fs { if same, err := wire.Encode(f, wire.Protocol18); err != nil || !bytes.Equal(same.Data, f.Data) { t.Fatalf("%s changed at 18: %v", name, err) } } for p := wire.Protocol17; p >= wire.Protocol1; p-- { if _, err := wire.Encode(fs["models"], p); !errors.Is(err, wire.ErrProtocol) { t.Fatalf("a models frame encoded at %d: %v", p, err) } for _, name := range []string{"hello", "sync", "dispatch", "usage", "step", "answer", "reply", "prompt"} { got, err := wire.Encode(fs[name], p) if errors.Is(err, wire.ErrProtocol) { // Refused at this protocol by an older step: never sent. continue } if err != nil { t.Fatalf("%s at %d: %v", name, p, err) } what := fmt.Sprintf("%s at %d", name, p) if _, _, err := wire.ParseFrame(mustFrame(t, got)); err != nil { t.Fatalf("%s does not parse: %v", what, err) } keysAt(t, what, got.Data, "connections", frozen17Held) keysAt(t, what, got.Data, "rows", frozen17Usage) keysAt(t, what, got.Data, "usage", frozen17Usage) keysAt(t, what, got.Data, "prompt", frozen17Prompt) if name == "dispatch" { frozen13(t, what, got.Data, frozen17Dispatch) } for _, banned := range []string{"model_mismatch", "tier_version", "avoid_family", "models_revision", "choices", wire.ReasonModelUnavailable} { if strings.Contains(string(got.Data), banned) { t.Fatalf("%s carries %s: %s", what, banned, got.Data) } } switch name { case "answer": var a wire.AnswerReport if err := wire.Strict(got.Data, &a); err != nil || !frozen17AnswerReasons[a.Reason] { t.Fatalf("%s: reason %q unknown at 17 (%v)", what, a.Reason, err) } case "prompt": var r wire.ConnectionReport if err := wire.Strict(got.Data, &r); err != nil || r.Prompt == nil || !frozen17Prompts[r.Prompt.Kind] { t.Fatalf("%s: prompt %+v (%v)", what, r.Prompt, err) } if strings.Join(r.Prompt.Models, ",") != "z-ai/glm-5.3,z-ai/glm-5.3-flash" { t.Fatalf("%s: the one-model pick offers %v, not the eligible models", what, r.Prompt.Models) } } } } } // The models frame is durable and decodes strictly; an allowed set is // at least one model, each once. func TestModelsFrameAndAllowedSet(t *testing.T) { if !(wire.Frame{Type: wire.FrameModels}).Durable() { t.Fatal("the models frame is not durable") } if _, _, err := wire.ParseFrame([]byte(`{"id":"m","type":"models","data":{"connection":"c","person":"p","local_id":"l","allowed":["a"],"revision":1,"extra":1}}`)); err == nil { t.Fatal("an unknown field accepted") } for _, c := range []struct { allowed []string ok bool }{{nil, false}, {[]string{}, false}, {[]string{"a"}, true}, {[]string{"a", "a"}, false}, {[]string{""}, false}, {[]string{strings.Repeat("m", wire.MaxModelName+1)}, false}, {[]string{"a", "b"}, true}} { if wire.ValidAllowed(c.allowed) != c.ok { t.Fatalf("ValidAllowed(%v) = %v", c.allowed, !c.ok) } } }