oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package wire_test
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "strings"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/wire"
13)
14
15// Frozen protocol 17 schemas (main at 5880ab10, before S5b): the JSON
16// keys each body had at 17, written out so that a field S5b added
17// cannot slip into what an older peer is sent.
18var (
19 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")
20 frozen17Held = keySet("local_id person provider kind label state plan headroom expires_at expires_estimated harness upstream billing model budget spend")
21 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")
22 frozen17Prompt = keySet("kind url code attempt wrong_code models")
23 // frozen17Prompts and frozen17AnswerReasons are the values a
24 // protocol 17 instance knows.
25 frozen17Prompts = keySet("authorize device token api_key model")
26 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")
27)
28
29// keysAt checks every object under key name (at any depth) against a
30// frozen schema.
31func keysAt(t *testing.T, what string, raw []byte, name string, schema map[string]bool) {
32 t.Helper()
33 var walk func(key string, v any)
34 walk = func(key string, v any) {
35 switch x := v.(type) {
36 case map[string]any:
37 if key == name {
38 for k := range x {
39 if !schema[k] {
40 t.Fatalf("%s: %s carries %q, which a protocol 17 peer refuses: %s", what, name, k, raw)
41 }
42 }
43 }
44 for k, val := range x {
45 walk(k, val)
46 }
47 case []any:
48 for _, e := range x {
49 walk(key, e)
50 }
51 }
52 }
53 var v any
54 if err := json.Unmarshal(raw, &v); err != nil {
55 t.Fatal(err)
56 }
57 walk("", v)
58}
59
60func modelsFrames(t *testing.T) map[string]wire.Frame {
61 frame := func(id, typ string, v any) wire.Frame {
62 f, err := wire.NewFrame(id, typ, v)
63 if err != nil {
64 t.Fatal(err)
65 }
66 return f
67 }
68 n := int64(10)
69 failed := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)
70 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}
71 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"},
72 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,
73 Choices: []wire.ModelChoice{{ID: "z-ai/glm-5.3", Eligible: true}, {ID: "vendor/unpriced"}}}
74 return map[string]wire.Frame{
75 "models": frame("m", wire.FrameModels, wire.ModelsCommand{Connection: "cn", Person: "p", LocalID: "tensorx-a", Allowed: []string{"z-ai/glm-5.3"}, Revision: 2}),
76 "hello": frame("h", wire.FrameHello, wire.Hello{Protocol: wire.ProtocolCurrent, Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{held}}),
77 "sync": frame("y", wire.FrameSync, wire.Sync{Connections: []wire.HeldConnection{held}}),
78 "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"}),
79 "usage": frame("u", wire.FrameUsage, wire.UsageReport{StepID: "s", Rows: []wire.Usage{row}}),
80 "step": frame("s", wire.FrameStep, wire.StepReport{TaskID: "tk", StepID: "s", Attempt: 1, State: wire.StepRunning, Findings: []wire.Finding{}, Usage: []wire.Usage{row}}),
81 "answer": frame("a", wire.FrameAnswer, wire.AnswerReport{TaskID: "tk", QuestionID: "q", Attempt: 1, State: wire.QuestionFailed, Reason: wire.ReasonModelUnavailable, Usage: []wire.Usage{row}}),
82 "reply": frame("p", wire.FrameReply, wire.Reply{TurnID: "t", Attempt: 1, Text: "ok", Usage: []wire.Usage{row}}),
83 "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{
84 {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"}}}}),
85 }
86}
87
88// Protocol 18 (ProtocolModels, slice S5b): at 18 every frame goes out
89// whole. Below it, at every lower protocol, nothing an older peer is
90// sent carries a key or a value protocol 17 did not have: the models
91// frame is refused; the models card is said as the one-model pick of
92// the eligible models; the held set, the usage fields and avoid_family
93// go; model_unavailable is said as account_unavailable. Each lower
94// protocol is checked because an older step in Encode's chain could
95// undo a newer one (S5's bug).
96func TestEncodeBelowProtocol18AgainstFrozenSchemas(t *testing.T) {
97 if wire.ProtocolModels != wire.Protocol18 || wire.ProtocolCurrent != wire.ProtocolDesign {
98 t.Fatalf("models %d, current %d", wire.ProtocolModels, wire.ProtocolCurrent)
99 }
100 fs := modelsFrames(t)
101 for name, f := range fs {
102 if same, err := wire.Encode(f, wire.Protocol18); err != nil || !bytes.Equal(same.Data, f.Data) {
103 t.Fatalf("%s changed at 18: %v", name, err)
104 }
105 }
106 for p := wire.Protocol17; p >= wire.Protocol1; p-- {
107 if _, err := wire.Encode(fs["models"], p); !errors.Is(err, wire.ErrProtocol) {
108 t.Fatalf("a models frame encoded at %d: %v", p, err)
109 }
110 for _, name := range []string{"hello", "sync", "dispatch", "usage", "step", "answer", "reply", "prompt"} {
111 got, err := wire.Encode(fs[name], p)
112 if errors.Is(err, wire.ErrProtocol) {
113 // Refused at this protocol by an older step: never sent.
114 continue
115 }
116 if err != nil {
117 t.Fatalf("%s at %d: %v", name, p, err)
118 }
119 what := fmt.Sprintf("%s at %d", name, p)
120 if _, _, err := wire.ParseFrame(mustFrame(t, got)); err != nil {
121 t.Fatalf("%s does not parse: %v", what, err)
122 }
123 keysAt(t, what, got.Data, "connections", frozen17Held)
124 keysAt(t, what, got.Data, "rows", frozen17Usage)
125 keysAt(t, what, got.Data, "usage", frozen17Usage)
126 keysAt(t, what, got.Data, "prompt", frozen17Prompt)
127 if name == "dispatch" {
128 frozen13(t, what, got.Data, frozen17Dispatch)
129 }
130 for _, banned := range []string{"model_mismatch", "tier_version", "avoid_family", "models_revision", "choices", wire.ReasonModelUnavailable} {
131 if strings.Contains(string(got.Data), banned) {
132 t.Fatalf("%s carries %s: %s", what, banned, got.Data)
133 }
134 }
135 switch name {
136 case "answer":
137 var a wire.AnswerReport
138 if err := wire.Strict(got.Data, &a); err != nil || !frozen17AnswerReasons[a.Reason] {
139 t.Fatalf("%s: reason %q unknown at 17 (%v)", what, a.Reason, err)
140 }
141 case "prompt":
142 var r wire.ConnectionReport
143 if err := wire.Strict(got.Data, &r); err != nil || r.Prompt == nil || !frozen17Prompts[r.Prompt.Kind] {
144 t.Fatalf("%s: prompt %+v (%v)", what, r.Prompt, err)
145 }
146 if strings.Join(r.Prompt.Models, ",") != "z-ai/glm-5.3,z-ai/glm-5.3-flash" {
147 t.Fatalf("%s: the one-model pick offers %v, not the eligible models", what, r.Prompt.Models)
148 }
149 }
150 }
151 }
152}
153
154// The models frame is durable and decodes strictly; an allowed set is
155// at least one model, each once.
156func TestModelsFrameAndAllowedSet(t *testing.T) {
157 if !(wire.Frame{Type: wire.FrameModels}).Durable() {
158 t.Fatal("the models frame is not durable")
159 }
160 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 {
161 t.Fatal("an unknown field accepted")
162 }
163 for _, c := range []struct {
164 allowed []string
165 ok bool
166 }{{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}} {
167 if wire.ValidAllowed(c.allowed) != c.ok {
168 t.Fatalf("ValidAllowed(%v) = %v", c.allowed, !c.ok)
169 }
170 }
171}
172