package opencode import ( "bufio" "encoding/json" "os" "strconv" "strings" "testing" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/pi" ) // replay decodes a recording of one turn of the real OpenCode 2.2.7 // (testdata, captured from `opencode acp` against a fake Go on // 127.0.0.1): the turn started with its prompt's id, every message after. func replay(t *testing.T, name string, prompt string) ([]provider.Event, *Decoder) { t.Helper() f, err := os.Open("testdata/" + name + ".jsonl") if err != nil { t.Fatal(err) } defer f.Close() d := &Decoder{Model: "glm-5.3"} var out []provider.Event s := bufio.NewScanner(f) s.Buffer(nil, 1<<20) first := true for s.Scan() { var m Message if err := json.Unmarshal(s.Bytes(), &m); err != nil { t.Fatal(err) } if first { var p struct{ SessionID string } json.Unmarshal(m.Params, &p) d.Session = p.SessionID d.Start(prompt) first = false } out = append(out, d.Decode(m)...) } return out, d } func kinds(evs []provider.Event) string { var k []string for _, e := range evs { k = append(k, e.Kind) } return strings.Join(k, ",") } func last[T any](t *testing.T, evs []provider.Event, kind string) T { t.Helper() var v T for _, e := range evs { if e.Kind == kind { if err := json.Unmarshal(e.Payload, &v); err != nil { t.Fatal(err) } } } return v } // Each recorded turn maps to Equipo's kinds: text to delta, a tool call // (once its arguments are known) to tool_call and its end to // tool_result, a permission request to ask, the prompt's answer to // usage and done with the turn's status and failure class. func TestDecodeRecordedRuns(t *testing.T) { for _, tc := range []struct { name, prompt, kinds string status, failure string valid bool input, output, read int64 }{ {"text", "3", "delta,usage,done", pi.StatusCompleted, "", true, 60, 7, 40}, {"tool-failed", "4", "tool_call,tool_result,delta,usage,done", pi.StatusCompleted, "", true, 120, 14, 80}, {"mcp-tool", "3", "tool_call,tool_result,delta,usage,done", pi.StatusCompleted, "", true, 120, 14, 80}, {"permission-rejected", "4", "tool_call,ask,tool_result,usage,done", pi.StatusInterrupted, "", true, 60, 7, 40}, {"external-directory", "5", "tool_call,tool_result,delta,usage,done", pi.StatusCompleted, "", true, 120, 14, 80}, {"key-refused", "3", "usage,done", pi.StatusFailed, pi.FailAuth, false, 0, 0, 0}, {"rate-limited", "4", "usage,done", pi.StatusFailed, pi.FailQuota, false, 0, 0, 0}, {"no-usage", "5", "delta,usage,done", pi.StatusCompleted, "", false, 0, 0, 0}, {"cancelled", "4", "delta,usage,done", pi.StatusInterrupted, "", false, 0, 0, 0}, } { t.Run(tc.name, func(t *testing.T) { evs, d := replay(t, tc.name, tc.prompt) if got := kinds(evs); got != tc.kinds { t.Fatalf("kinds %s, want %s", got, tc.kinds) } done := last[pi.Done](t, evs, KindDone) if done.Status != tc.status || done.Failure != tc.failure { t.Fatalf("done %+v", done) } u := last[pi.Usage](t, evs, KindUsage) if u.Valid != tc.valid || u.Input != tc.input || u.Output != tc.output || u.CacheRead != tc.read || u.Model != "glm-5.3" { t.Fatalf("usage %+v", u) } if d.Active() { t.Fatal("the turn did not end") } if len(d.Unknown) != 0 { t.Fatalf("unknown %v", d.Unknown) } }) } // The MCP call's arguments arrive with its first update that runs it. evs, _ := replay(t, "mcp-tool", "3") call := last[pi.ToolCall](t, evs, KindToolCall) if call.Tool != "equipo_submit_review" || string(call.Args) != `{"verdict":"approve"}` { t.Fatalf("call %+v %s", call, call.Args) } evs, _ = replay(t, "permission-rejected", "4") ask := last[pi.Ask](t, evs, KindAsk) if ask.ID != "0" || ask.Call.Tool != "shell" || evs[1].Kind != KindAsk || evs[1].RequestID != "0" { t.Fatalf("ask %+v", ask) } } // Updates before a turn starts (a session/load replays the session's // history) and updates about another session are not this turn's; a // response that is not the prompt's ends nothing. func TestDecodeOnlyTheTurn(t *testing.T) { d := &Decoder{Session: "ses_aaaaaaaaaaaa"} chunk := func(session string) Message { return Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"` + session + `","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"old"}}}`)} } if evs := d.Decode(chunk("ses_aaaaaaaaaaaa")); len(evs) != 0 { t.Fatalf("a replayed update decoded: %v", kinds(evs)) } d.Start("equipo-7") if evs := d.Decode(chunk("ses_bbbbbbbbbbbb")); len(evs) != 0 { t.Fatalf("another session's update decoded: %v", kinds(evs)) } if evs := d.Decode(chunk("ses_aaaaaaaaaaaa")); kinds(evs) != "delta" { t.Fatalf("the turn's update: %v", kinds(evs)) } if evs := d.Decode(Message{ID: json.RawMessage(`"equipo-6"`), Result: json.RawMessage(`{"stopReason":"end_turn"}`)}); len(evs) != 0 || !d.Active() { t.Fatal("another request's answer ended the turn") } 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() { t.Fatalf("the prompt's answer: %v", kinds(evs)) } } // Unknown updates and methods are counted by name and dropped. func TestDecodeUnknownMessages(t *testing.T) { d := &Decoder{Session: "s"} d.Start("1") d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"brand_new_thing"}}`)}) d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"brand_new_thing"}}`)}) d.Decode(Message{Method: "_opencode/something"}) d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"usage_update"}}`)}) if d.Unknown["session/update:brand_new_thing"] != 2 || d.Unknown["_opencode/something"] != 1 || len(d.Unknown) != 2 { t.Fatalf("unknown %v", d.Unknown) } } // The turn's usage (spec §2.3): output is the visible output and the // reasoning together (OpenCode reports them apart, Go bills reasoning as // output); a figure missing, negative, overflowing, or a turn whose // input is zero (OpenCode's zero for a figure never given) cannot be // counted. func TestDecodeUsage(t *testing.T) { d := &Decoder{Model: "kimi-k3"} u := d.usageOf(json.RawMessage(`{"inputTokens":100,"outputTokens":20,"thoughtTokens":5,"cachedReadTokens":30,"cachedWriteTokens":2}`)) if !u.Valid || u.Input != 100 || u.Output != 25 || u.Reasoning != 5 || u.CacheRead != 30 || u.CacheWrite != 2 { t.Fatalf("usage %+v", u) } if u := d.usageOf(json.RawMessage(`{"inputTokens":0,"outputTokens":0,"cachedReadTokens":50}`)); !u.Valid || u.CacheRead != 50 { t.Fatalf("a cached-only turn %+v", u) } for name, raw := range map[string]string{ "none": ``, "zero": `{"inputTokens":0,"outputTokens":0,"totalTokens":0}`, "no input": `{"outputTokens":3}`, "no output": `{"inputTokens":3}`, "negative": `{"inputTokens":3,"outputTokens":-1}`, "negative cached": `{"inputTokens":3,"outputTokens":1,"cachedReadTokens":-4}`, "overflow": `{"inputTokens":3,"outputTokens":9223372036854775807,"thoughtTokens":1}`, "overflow input": `{"inputTokens":9223372036854775807,"outputTokens":1,"cachedReadTokens":1}`, "not an object": `[1,2]`, } { if u := d.usageOf(json.RawMessage(raw)); u.Valid { t.Errorf("%s counted: %+v", name, u) } } // Through the tally: a turn's row, complete at its end; without the // end, or with an uncountable figure, not. var tally Tally evs, _ := replay(t, "mcp-tool", "3") for _, e := range evs { tally.Add(e) } row := tally.Row() if !row.Complete || *row.InputTokens != 120 || *row.OutputTokens != 14 || *row.CachedInputTokens != 80 || row.Model != "glm-5.3" || row.CostReportedMicros != nil { t.Fatalf("row %+v", row) } var none Tally evs, _ = replay(t, "no-usage", "5") for _, e := range evs { none.Add(e) } if r := none.Row(); r.InputTokens != nil || r.OutputTokens != nil { t.Fatalf("a turn with no usage counted: %+v", r) } var open Tally open.Add(provider.Event{Kind: KindUsage, Payload: payload(pi.Usage{Valid: true, Input: 1, Output: 1})}) if open.Row().Complete { t.Fatal("complete before the turn's end") } } // A tool call's arguments over the event bound are dropped; its name is // clipped. func TestDecodeClipsToolArguments(t *testing.T) { d := &Decoder{Session: "s"} d.Start("1") big := `{"command":"` + strings.Repeat("x", maxEventArgs) + `"}` d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"c1","name":"` + strings.Repeat("n", 300) + `","status":"pending","rawInput":{}}}`)}) evs := d.Decode(Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"c1","status":"in_progress","rawInput":` + big + `}}`)}) call := last[pi.ToolCall](t, evs, KindToolCall) if len(call.Args) != 0 || len(call.Tool) != 128 { t.Fatalf("args %d bytes, tool %d", len(call.Args), len(call.Tool)) } } func TestFamilyFromModel(t *testing.T) { for model, want := range map[string]string{ "glm-5.3": "glm", "glm-5.3-flash": "glm", "kimi-k3.1-pro": "kimi", "kimi-k2.7-code": "kimi", "deepseek-v4-pro": "deepseek", "mimo-v2.6-pro": "mimo", "minimax-m3.1-flash": "minimax", "longcat-2.0": "longcat", "hy4": "hunyuan", "hy3": "hunyuan", "step-5-preview": "step", "qwen3.8-max": "qwen", "equipo/glm-5.3": "glm", } { if got := Family(model); got != want { t.Errorf("%s: %q, want %q", model, got, want) } } } // Security round finding 4: OpenCode reports the session's cost so far // (usage_update, cumulative); a turn's reported cost is what it added, // from the session's baseline (a resumed session's is the cost recorded // when it was kept), so §2.3's larger-of rule can charge it. A cost that // is not a finite, non-negative USD amount, or that goes down, makes the // turn's usage uncountable (spend unknown). func TestDecodeReportedCost(t *testing.T) { update := func(amount string) Message { return Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"usage_update","used":10,"size":100,"cost":{"amount":` + amount + `,"currency":"USD"}}}`)} } answer := func(id string) Message { return Message{ID: json.RawMessage(`"` + id + `"`), Result: json.RawMessage(`{"stopReason":"end_turn","usage":{"inputTokens":100,"outputTokens":10}}`)} } turn := func(d *Decoder, id string, msgs ...Message) pi.Usage { d.Start(id) var evs []provider.Event for _, m := range append(msgs, answer(id)) { evs = append(evs, d.Decode(m)...) } return last[pi.Usage](t, evs, KindUsage) } d := &Decoder{Session: "s", Model: "glm-5.3", CostBase: 0.10} if u := turn(d, "1", update("0.35")); !u.Valid || !u.Priced || u.Cost < 0.2499 || u.Cost > 0.2501 { t.Fatalf("first turn %+v", u) } if u := turn(d, "2", update("0.35")); !u.Valid || u.Priced || u.Cost != 0 { t.Fatalf("a turn that added nothing %+v", u) } if u := turn(d, "3"); !u.Valid || u.Priced { t.Fatalf("a turn with no cost update %+v", u) } if d.SessionCost() != 0.35 { t.Fatalf("session cost %v", d.SessionCost()) } for name, amount := range map[string]string{"down": "0.20", "negative": "-1", "not a number": `"x"`} { d := &Decoder{Session: "s", Model: "glm-5.3", CostBase: 0.30} if u := turn(d, "1", update(amount)); u.Valid { t.Errorf("%s: counted %+v", name, u) } } other := Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"s","update":{"sessionUpdate":"usage_update","cost":{"amount":1,"currency":"EUR"}}}`)} if u := turn(&Decoder{Session: "s"}, "1", other); u.Valid { t.Errorf("another currency counted %+v", u) } // Through the tally: the reported cost, in micro-units. var tally Tally d = &Decoder{Session: "s", Model: "glm-5.3"} d.Start("9") for _, m := range []Message{update("0.5"), answer("9")} { for _, e := range d.Decode(m) { tally.Add(e) } } if r := tally.Row(); r.CostReportedMicros == nil || *r.CostReportedMicros != 500_000 { t.Fatalf("row %+v", r) } } // Security round finding 5: a tool call's id over the bound is dropped // and counted; the arguments the decoder keeps for calls not yet run are // bounded in total, however many calls are announced. func TestDecodeBoundsRetainedCalls(t *testing.T) { d := &Decoder{Session: "s"} d.Start("1") long := strings.Repeat("i", maxToolID+1) 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 { t.Fatalf("a long id kept: %v %d %v", eventKinds(evs), len(d.calls), d.Unknown) } args := `{"command":"` + strings.Repeat("a", 60<<10) + `"}` for i := range 2000 { 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 + `}}`)}) } if d.retained > maxRetained || len(d.calls) > maxCalls { t.Fatalf("retained %d bytes in %d calls", d.retained, len(d.calls)) } } // §16.5: the session's model is fixed. A config_option_update naming // another model fails the turn (never completed) and marks the session; // one naming the fixed model changes nothing. A model the provider does // not have is the model's failure, not the key's. func TestDecodeModelFixed(t *testing.T) { d := &Decoder{Model: "glm-5.3", Session: "ses_1"} d.Start("equipo-2") update := func(value string) Message { return Message{Method: methodUpdate, Params: json.RawMessage(`{"sessionId":"ses_1","update":{"sessionUpdate":"config_option_update","configOptions":[{"id":"mode","currentValue":"build"},{"id":"model","currentValue":"` + value + `"}]}}`)} } d.Decode(update(provider.OpenCodeModel("glm-5.3"))) if d.ModelChanged() { t.Fatal("the fixed model taken as a change") } d.Decode(update(provider.OpenCodeModel("kimi-k3"))) if !d.ModelChanged() { t.Fatal("a changed model not seen") } evs := d.Decode(Message{ID: json.RawMessage(`"equipo-2"`), Result: json.RawMessage(`{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":1,"totalTokens":2}}`)}) var done pi.Done for _, e := range evs { if e.Kind == KindDone { json.Unmarshal(e.Payload, &done) } } if done.Status != pi.StatusFailed { t.Fatalf("a turn after the model changed: %+v", done) } for name, want := range map[string]string{"provider.model-not-found": pi.FailModel, "provider.rate-limit": pi.FailQuota, "provider.other": pi.FailProvider} { e := &RPCError{Code: -32603, Message: "x"} e.Data.ErrorName = name if got := failure(e); got != want { t.Fatalf("%s: %s, want %s", name, got, want) } } }