| 1 | package opencode |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "encoding/json" |
| 6 | "os" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 12 | "amadan.net/oficina/equipo/internal/runner/provider/pi" |
| 13 | ) |
| 14 | |
| 15 | // replay decodes a recording of one turn of the real OpenCode 2.2.7 |
| 16 | // (testdata, captured from `opencode acp` against a fake Go on |
| 17 | // 127.0.0.1): the turn started with its prompt's id, every message after. |
| 18 | func replay(t *testing.T, name string, prompt string) ([]provider.Event, *Decoder) { |
| 19 | t.Helper() |
| 20 | f, err := os.Open("testdata/" + name + ".jsonl") |
| 21 | if err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | defer f.Close() |
| 25 | d := &Decoder{Model: "glm-5.3"} |
| 26 | var out []provider.Event |
| 27 | s := bufio.NewScanner(f) |
| 28 | s.Buffer(nil, 1<<20) |
| 29 | first := true |
| 30 | for s.Scan() { |
| 31 | var m Message |
| 32 | if err := json.Unmarshal(s.Bytes(), &m); err != nil { |
| 33 | t.Fatal(err) |
| 34 | } |
| 35 | if first { |
| 36 | var p struct{ SessionID string } |
| 37 | json.Unmarshal(m.Params, &p) |
| 38 | d.Session = p.SessionID |
| 39 | d.Start(prompt) |
| 40 | first = false |
| 41 | } |
| 42 | out = append(out, d.Decode(m)...) |
| 43 | } |
| 44 | return out, d |
| 45 | } |
| 46 | |
| 47 | func kinds(evs []provider.Event) string { |
| 48 | var k []string |
| 49 | for _, e := range evs { |
| 50 | k = append(k, e.Kind) |
| 51 | } |
| 52 | return strings.Join(k, ",") |
| 53 | } |
| 54 | |
| 55 | func last[T any](t *testing.T, evs []provider.Event, kind string) T { |
| 56 | t.Helper() |
| 57 | var v T |
| 58 | for _, e := range evs { |
| 59 | if e.Kind == kind { |
| 60 | if err := json.Unmarshal(e.Payload, &v); err != nil { |
| 61 | t.Fatal(err) |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | return v |
| 66 | } |
| 67 | |
| 68 | // Each recorded turn maps to Equipo's kinds: text to delta, a tool call |
| 69 | // (once its arguments are known) to tool_call and its end to |
| 70 | // tool_result, a permission request to ask, the prompt's answer to |
| 71 | // usage and done with the turn's status and failure class. |
| 72 | func TestDecodeRecordedRuns(t *testing.T) { |
| 73 | for _, tc := range []struct { |
| 74 | name, prompt, kinds string |
| 75 | status, failure string |
| 76 | valid bool |
| 77 | input, output, read int64 |
| 78 | }{ |
| 79 | {"text", "3", "delta,usage,done", pi.StatusCompleted, "", true, 60, 7, 40}, |
| 80 | {"tool-failed", "4", "tool_call,tool_result,delta,usage,done", pi.StatusCompleted, "", true, 120, 14, 80}, |
| 81 | {"mcp-tool", "3", "tool_call,tool_result,delta,usage,done", pi.StatusCompleted, "", true, 120, 14, 80}, |
| 82 | {"permission-rejected", "4", "tool_call,ask,tool_result,usage,done", pi.StatusInterrupted, "", true, 60, 7, 40}, |
| 83 | {"external-directory", "5", "tool_call,tool_result,delta,usage,done", pi.StatusCompleted, "", true, 120, 14, 80}, |
| 84 | {"key-refused", "3", "usage,done", pi.StatusFailed, pi.FailAuth, false, 0, 0, 0}, |
| 85 | {"rate-limited", "4", "usage,done", pi.StatusFailed, pi.FailQuota, false, 0, 0, 0}, |
| 86 | {"no-usage", "5", "delta,usage,done", pi.StatusCompleted, "", false, 0, 0, 0}, |
| 87 | {"cancelled", "4", "delta,usage,done", pi.StatusInterrupted, "", false, 0, 0, 0}, |
| 88 | } { |
| 89 | t.Run(tc.name, func(t *testing.T) { |
| 90 | evs, d := replay(t, tc.name, tc.prompt) |
| 91 | if got := kinds(evs); got != tc.kinds { |
| 92 | t.Fatalf("kinds %s, want %s", got, tc.kinds) |
| 93 | } |
| 94 | done := last[pi.Done](t, evs, KindDone) |
| 95 | if done.Status != tc.status || done.Failure != tc.failure { |
| 96 | t.Fatalf("done %+v", done) |
| 97 | } |
| 98 | u := last[pi.Usage](t, evs, KindUsage) |
| 99 | if u.Valid != tc.valid || u.Input != tc.input || u.Output != tc.output || u.CacheRead != tc.read || u.Model != "glm-5.3" { |
| 100 | t.Fatalf("usage %+v", u) |
| 101 | } |
| 102 | if d.Active() { |
| 103 | t.Fatal("the turn did not end") |
| 104 | } |
| 105 | if len(d.Unknown) != 0 { |
| 106 | t.Fatalf("unknown %v", d.Unknown) |
| 107 | } |
| 108 | }) |
| 109 | } |
| 110 | // The MCP call's arguments arrive with its first update that runs it. |
| 111 | evs, _ := replay(t, "mcp-tool", "3") |
| 112 | call := last[pi.ToolCall](t, evs, KindToolCall) |
| 113 | if call.Tool != "equipo_submit_review" || string(call.Args) != `{"verdict":"approve"}` { |
| 114 | t.Fatalf("call %+v %s", call, call.Args) |
| 115 | } |
| 116 | evs, _ = replay(t, "permission-rejected", "4") |
| 117 | ask := last[pi.Ask](t, evs, KindAsk) |
| 118 | if ask.ID != "0" || ask.Call.Tool != "shell" || evs[1].Kind != KindAsk || evs[1].RequestID != "0" { |
| 119 | t.Fatalf("ask %+v", ask) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // Updates before a turn starts (a session/load replays the session's |
| 124 | // history) and updates about another session are not this turn's; a |
| 125 | // response that is not the prompt's ends nothing. |
| 126 | func TestDecodeOnlyTheTurn(t *testing.T) { |
| 127 | d := &Decoder{Session: "ses_aaaaaaaaaaaa"} |
| 128 | chunk := func(session string) Message { |
| 129 | return Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"` + session + `","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"old"}}}`)} |
| 130 | } |
| 131 | if evs := d.Decode(chunk("ses_aaaaaaaaaaaa")); len(evs) != 0 { |
| 132 | t.Fatalf("a replayed update decoded: %v", kinds(evs)) |
| 133 | } |
| 134 | d.Start("equipo-7") |
| 135 | if evs := d.Decode(chunk("ses_bbbbbbbbbbbb")); len(evs) != 0 { |
| 136 | t.Fatalf("another session's update decoded: %v", kinds(evs)) |
| 137 | } |
| 138 | if evs := d.Decode(chunk("ses_aaaaaaaaaaaa")); kinds(evs) != "delta" { |
| 139 | t.Fatalf("the turn's update: %v", kinds(evs)) |
| 140 | } |
| 141 | if evs := d.Decode(Message{ID: json.RawMessage(`"equipo-6"`), Result: json.RawMessage(`{"stopReason":"end_turn"}`)}); len(evs) != 0 || !d.Active() { |
| 142 | t.Fatal("another request's answer ended the turn") |
| 143 | } |
| 144 | if evs := d.Decode(Message{ID: json.RawMessage(`"equipo-7"`), Result: json.RawMessage(`{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":1}}`)}); kinds(evs) != "usage,done" || d.Active() { |
| 145 | t.Fatalf("the prompt's answer: %v", kinds(evs)) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // Unknown updates and methods are counted by name and dropped. |
| 150 | func TestDecodeUnknownMessages(t *testing.T) { |
| 151 | d := &Decoder{Session: "s"} |
| 152 | d.Start("1") |
| 153 | d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"brand_new_thing"}}`)}) |
| 154 | d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"brand_new_thing"}}`)}) |
| 155 | d.Decode(Message{Method: "_opencode/something"}) |
| 156 | d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"usage_update"}}`)}) |
| 157 | if d.Unknown["session/update:brand_new_thing"] != 2 || d.Unknown["_opencode/something"] != 1 || len(d.Unknown) != 2 { |
| 158 | t.Fatalf("unknown %v", d.Unknown) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | // The turn's usage (spec §2.3): output is the visible output and the |
| 163 | // reasoning together (OpenCode reports them apart, Go bills reasoning as |
| 164 | // output); a figure missing, negative, overflowing, or a turn whose |
| 165 | // input is zero (OpenCode's zero for a figure never given) cannot be |
| 166 | // counted. |
| 167 | func TestDecodeUsage(t *testing.T) { |
| 168 | d := &Decoder{Model: "kimi-k3"} |
| 169 | u := d.usageOf(json.RawMessage(`{"inputTokens":100,"outputTokens":20,"thoughtTokens":5,"cachedReadTokens":30,"cachedWriteTokens":2}`)) |
| 170 | if !u.Valid || u.Input != 100 || u.Output != 25 || u.Reasoning != 5 || u.CacheRead != 30 || u.CacheWrite != 2 { |
| 171 | t.Fatalf("usage %+v", u) |
| 172 | } |
| 173 | if u := d.usageOf(json.RawMessage(`{"inputTokens":0,"outputTokens":0,"cachedReadTokens":50}`)); !u.Valid || u.CacheRead != 50 { |
| 174 | t.Fatalf("a cached-only turn %+v", u) |
| 175 | } |
| 176 | for name, raw := range map[string]string{ |
| 177 | "none": ``, |
| 178 | "zero": `{"inputTokens":0,"outputTokens":0,"totalTokens":0}`, |
| 179 | "no input": `{"outputTokens":3}`, |
| 180 | "no output": `{"inputTokens":3}`, |
| 181 | "negative": `{"inputTokens":3,"outputTokens":-1}`, |
| 182 | "negative cached": `{"inputTokens":3,"outputTokens":1,"cachedReadTokens":-4}`, |
| 183 | "overflow": `{"inputTokens":3,"outputTokens":9223372036854775807,"thoughtTokens":1}`, |
| 184 | "overflow input": `{"inputTokens":9223372036854775807,"outputTokens":1,"cachedReadTokens":1}`, |
| 185 | "not an object": `[1,2]`, |
| 186 | } { |
| 187 | if u := d.usageOf(json.RawMessage(raw)); u.Valid { |
| 188 | t.Errorf("%s counted: %+v", name, u) |
| 189 | } |
| 190 | } |
| 191 | // Through the tally: a turn's row, complete at its end; without the |
| 192 | // end, or with an uncountable figure, not. |
| 193 | var tally Tally |
| 194 | evs, _ := replay(t, "mcp-tool", "3") |
| 195 | for _, e := range evs { |
| 196 | tally.Add(e) |
| 197 | } |
| 198 | row := tally.Row() |
| 199 | if !row.Complete || *row.InputTokens != 120 || *row.OutputTokens != 14 || *row.CachedInputTokens != 80 || row.Model != "glm-5.3" || row.CostReportedMicros != nil { |
| 200 | t.Fatalf("row %+v", row) |
| 201 | } |
| 202 | var none Tally |
| 203 | evs, _ = replay(t, "no-usage", "5") |
| 204 | for _, e := range evs { |
| 205 | none.Add(e) |
| 206 | } |
| 207 | if r := none.Row(); r.InputTokens != nil || r.OutputTokens != nil { |
| 208 | t.Fatalf("a turn with no usage counted: %+v", r) |
| 209 | } |
| 210 | var open Tally |
| 211 | open.Add(provider.Event{Kind: KindUsage, Payload: payload(pi.Usage{Valid: true, Input: 1, Output: 1})}) |
| 212 | if open.Row().Complete { |
| 213 | t.Fatal("complete before the turn's end") |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // A tool call's arguments over the event bound are dropped; its name is |
| 218 | // clipped. |
| 219 | func TestDecodeClipsToolArguments(t *testing.T) { |
| 220 | d := &Decoder{Session: "s"} |
| 221 | d.Start("1") |
| 222 | big := `{"command":"` + strings.Repeat("x", maxEventArgs) + `"}` |
| 223 | d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"c1","name":"` + strings.Repeat("n", 300) + `","status":"pending","rawInput":{}}}`)}) |
| 224 | evs := d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"c1","status":"in_progress","rawInput":` + big + `}}`)}) |
| 225 | call := last[pi.ToolCall](t, evs, KindToolCall) |
| 226 | if len(call.Args) != 0 || len(call.Tool) != 128 { |
| 227 | t.Fatalf("args %d bytes, tool %d", len(call.Args), len(call.Tool)) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | func TestFamilyFromModel(t *testing.T) { |
| 232 | for model, want := range map[string]string{ |
| 233 | "glm-5.3": "glm", "glm-5.3-flash": "glm", "kimi-k3.1-pro": "kimi", "kimi-k2.7-code": "kimi", "deepseek-v4-pro": "deepseek", |
| 234 | "mimo-v2.6-pro": "mimo", "minimax-m3.1-flash": "minimax", "longcat-2.0": "longcat", "hy4": "hunyuan", "hy3": "hunyuan", |
| 235 | "step-5-preview": "step", "qwen3.8-max": "qwen", "equipo/glm-5.3": "glm", |
| 236 | } { |
| 237 | if got := Family(model); got != want { |
| 238 | t.Errorf("%s: %q, want %q", model, got, want) |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // Security round finding 4: OpenCode reports the session's cost so far |
| 244 | // (usage_update, cumulative); a turn's reported cost is what it added, |
| 245 | // from the session's baseline (a resumed session's is the cost recorded |
| 246 | // when it was kept), so §2.3's larger-of rule can charge it. A cost that |
| 247 | // is not a finite, non-negative USD amount, or that goes down, makes the |
| 248 | // turn's usage uncountable (spend unknown). |
| 249 | func TestDecodeReportedCost(t *testing.T) { |
| 250 | update := func(amount string) Message { |
| 251 | return Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"usage_update","used":10,"size":100,"cost":{"amount":` + amount + `,"currency":"USD"}}}`)} |
| 252 | } |
| 253 | answer := func(id string) Message { |
| 254 | return Message{ID: json.RawMessage(`"` + id + `"`), Result: json.RawMessage(`{"stopReason":"end_turn","usage":{"inputTokens":100,"outputTokens":10}}`)} |
| 255 | } |
| 256 | turn := func(d *Decoder, id string, msgs ...Message) pi.Usage { |
| 257 | d.Start(id) |
| 258 | var evs []provider.Event |
| 259 | for _, m := range append(msgs, answer(id)) { |
| 260 | evs = append(evs, d.Decode(m)...) |
| 261 | } |
| 262 | return last[pi.Usage](t, evs, KindUsage) |
| 263 | } |
| 264 | d := &Decoder{Session: "s", Model: "glm-5.3", CostBase: 0.10} |
| 265 | if u := turn(d, "1", update("0.35")); !u.Valid || !u.Priced || u.Cost < 0.2499 || u.Cost > 0.2501 { |
| 266 | t.Fatalf("first turn %+v", u) |
| 267 | } |
| 268 | if u := turn(d, "2", update("0.35")); !u.Valid || u.Priced || u.Cost != 0 { |
| 269 | t.Fatalf("a turn that added nothing %+v", u) |
| 270 | } |
| 271 | if u := turn(d, "3"); !u.Valid || u.Priced { |
| 272 | t.Fatalf("a turn with no cost update %+v", u) |
| 273 | } |
| 274 | if d.SessionCost() != 0.35 { |
| 275 | t.Fatalf("session cost %v", d.SessionCost()) |
| 276 | } |
| 277 | for name, amount := range map[string]string{"down": "0.20", "negative": "-1", "not a number": `"x"`} { |
| 278 | d := &Decoder{Session: "s", Model: "glm-5.3", CostBase: 0.30} |
| 279 | if u := turn(d, "1", update(amount)); u.Valid { |
| 280 | t.Errorf("%s: counted %+v", name, u) |
| 281 | } |
| 282 | } |
| 283 | other := Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"usage_update","cost":{"amount":1,"currency":"EUR"}}}`)} |
| 284 | if u := turn(&Decoder{Session: "s"}, "1", other); u.Valid { |
| 285 | t.Errorf("another currency counted %+v", u) |
| 286 | } |
| 287 | // Through the tally: the reported cost, in micro-units. |
| 288 | var tally Tally |
| 289 | d = &Decoder{Session: "s", Model: "glm-5.3"} |
| 290 | d.Start("9") |
| 291 | for _, m := range []Message{update("0.5"), answer("9")} { |
| 292 | for _, e := range d.Decode(m) { |
| 293 | tally.Add(e) |
| 294 | } |
| 295 | } |
| 296 | if r := tally.Row(); r.CostReportedMicros == nil || *r.CostReportedMicros != 500_000 { |
| 297 | t.Fatalf("row %+v", r) |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | // Security round finding 5: a tool call's id over the bound is dropped |
| 302 | // and counted; the arguments the decoder keeps for calls not yet run are |
| 303 | // bounded in total, however many calls are announced. |
| 304 | func TestDecodeBoundsRetainedCalls(t *testing.T) { |
| 305 | d := &Decoder{Session: "s"} |
| 306 | d.Start("1") |
| 307 | long := strings.Repeat("i", maxToolID+1) |
| 308 | if evs := d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"` + long + `","name":"read","status":"completed"}}`)}); len(evs) != 0 || len(d.calls) != 0 || d.Unknown["tool id too long"] != 1 { |
| 309 | t.Fatalf("a long id kept: %v %d %v", eventKinds(evs), len(d.calls), d.Unknown) |
| 310 | } |
| 311 | args := `{"command":"` + strings.Repeat("a", 60<<10) + `"}` |
| 312 | for i := range 2000 { |
| 313 | d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"c` + strconv.Itoa(i) + `","name":"shell","status":"pending","rawInput":` + args + `}}`)}) |
| 314 | } |
| 315 | if d.retained > maxRetained || len(d.calls) > maxCalls { |
| 316 | t.Fatalf("retained %d bytes in %d calls", d.retained, len(d.calls)) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | // §16.5: the session's model is fixed. A config_option_update naming |
| 321 | // another model fails the turn (never completed) and marks the session; |
| 322 | // one naming the fixed model changes nothing. A model the provider does |
| 323 | // not have is the model's failure, not the key's. |
| 324 | func TestDecodeModelFixed(t *testing.T) { |
| 325 | d := &Decoder{Model: "glm-5.3", Session: "ses_1"} |
| 326 | d.Start("equipo-2") |
| 327 | update := func(value string) Message { |
| 328 | return Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"ses_1","update":{"sessionUpdate":"config_option_update","configOptions":[{"id":"mode","currentValue":"build"},{"id":"model","currentValue":"` + value + `"}]}}`)} |
| 329 | } |
| 330 | d.Decode(update(provider.OpenCodeModel("glm-5.3"))) |
| 331 | if d.ModelChanged() { |
| 332 | t.Fatal("the fixed model taken as a change") |
| 333 | } |
| 334 | d.Decode(update(provider.OpenCodeModel("kimi-k3"))) |
| 335 | if !d.ModelChanged() { |
| 336 | t.Fatal("a changed model not seen") |
| 337 | } |
| 338 | evs := d.Decode(Message{ID: json.RawMessage(`"equipo-2"`), Result: json.RawMessage(`{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":1,"totalTokens":2}}`)}) |
| 339 | var done pi.Done |
| 340 | for _, e := range evs { |
| 341 | if e.Kind == KindDone { |
| 342 | json.Unmarshal(e.Payload, &done) |
| 343 | } |
| 344 | } |
| 345 | if done.Status != pi.StatusFailed { |
| 346 | t.Fatalf("a turn after the model changed: %+v", done) |
| 347 | } |
| 348 | for name, want := range map[string]string{"provider.model-not-found": pi.FailModel, "provider.rate-limit": pi.FailQuota, "provider.other": pi.FailProvider} { |
| 349 | e := &RPCError{Code: -32603, Message: "x"} |
| 350 | e.Data.ErrorName = name |
| 351 | if got := failure(e); got != want { |
| 352 | t.Fatalf("%s: %s, want %s", name, got, want) |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 | |