package pi import ( "bufio" "encoding/json" "os" "slices" "strings" "testing" "amadan.net/oficina/equipo/internal/runner/provider" ) func replay(t *testing.T, name string) (*Decoder, []provider.Event) { t.Helper() f, err := os.Open("testdata/" + name + ".jsonl") if err != nil { t.Fatal(err) } defer f.Close() d := &Decoder{} var out []provider.Event s := bufio.NewScanner(f) s.Buffer(make([]byte, 0, 1<<20), 1<<22) for s.Scan() { evs, err := d.Decode(s.Bytes()) if err != nil { t.Fatalf("%s: %v", s.Bytes(), err) } out = append(out, evs...) } return d, out } func kinds(evs []provider.Event) []string { var out []string for _, e := range evs { out = append(out, e.Kind) } return out } // Pi's RPC events map to Equipo's kinds (connectors spec §3, "Mapping"): // text deltas, tool calls and results by their call id, the extension's // question as an ask, each assistant message's usage, and done once Pi // will not retry. Command responses are not events. func TestDecodeRecordedRuns(t *testing.T) { _, evs := replay(t, "text") if got := kinds(evs); !slices.Equal(got, []string{KindDelta, KindDelta, KindUsage, KindDone}) { t.Fatalf("text run: %v", got) } var delta struct{ Text string } json.Unmarshal(evs[0].Payload, &delta) if delta.Text != "ok " { t.Fatalf("delta %s", evs[0].Payload) } var done Done json.Unmarshal(evs[3].Payload, &done) if done.Status != StatusCompleted || done.Failure != "" { t.Fatalf("done %+v", done) } _, evs = replay(t, "mcp-tool") if got := kinds(evs); !slices.Equal(got, []string{KindUsage, KindToolCall, KindToolResult, KindDelta, KindDelta, KindUsage, KindDone}) { t.Fatalf("tool run: %v", got) } var call ToolCall json.Unmarshal(evs[1].Payload, &call) if call.ID != "call_1" || call.Tool != "mcp__equipo__submit_review" || string(call.Args) != `{"verdict":"approve"}` { t.Fatalf("call %+v", call) } var result ToolResult json.Unmarshal(evs[2].Payload, &result) if result.ID != "call_1" || result.IsError { t.Fatalf("result %+v", result) } _, evs = replay(t, "blocked-tool") i := slices.Index(kinds(evs), KindAsk) if i < 0 { t.Fatalf("no ask: %v", kinds(evs)) } var ask Ask json.Unmarshal(evs[i].Payload, &ask) if ask.ID == "" || ask.Method != "confirm" || ask.Call.Tool != "read" || ask.Call.ID != "call_1" { t.Fatalf("ask %+v", ask) } json.Unmarshal(evs[i+1].Payload, &result) if evs[i+1].Kind != KindToolResult || !result.IsError { t.Fatalf("blocked result %s %s", evs[i+1].Kind, evs[i+1].Payload) } } // How a run ends: aborted is interrupted; a refused key and an // exhausted rate limit are failures of their classes, and a retry Pi // will make is not an end. func TestDecodeEndings(t *testing.T) { for _, tc := range []struct { name, status, failure string }{ {"abort", StatusInterrupted, ""}, {"key-refused", StatusFailed, FailAuth}, {"rate-limited", StatusFailed, FailQuota}, } { t.Run(tc.name, func(t *testing.T) { _, evs := replay(t, tc.name) var ends []Done for _, e := range evs { if e.Kind == KindDone { var d Done json.Unmarshal(e.Payload, &d) ends = append(ends, d) } } if len(ends) != 1 || ends[0].Status != tc.status || ends[0].Failure != tc.failure { t.Fatalf("ends %+v", ends) } }) } d := &Decoder{} evs, _ := d.Decode([]byte(`{"type":"message_end","message":{"role":"assistant","stopReason":"error","errorMessage":"Connection error.: connect ECONNREFUSED 127.0.0.1:18080","model":"m","usage":{"input":0,"output":0}}}`)) evs2, _ := d.Decode([]byte(`{"type":"agent_end","willRetry":false}`)) var done Done json.Unmarshal(evs2[0].Payload, &done) if len(evs) != 1 || done.Status != StatusFailed || done.Failure != FailProvider { t.Fatalf("connection error: %v %+v", kinds(evs), done) } // §16.4: a model the provider does not have is the model's fault. for msg, want := range map[string]string{`404: {"error":{"code":"model_not_found"}}`: FailModel, `400: {"error":{"code":"model_not_found"}}`: FailModel, `400: {"error":"bad request"}`: FailProvider, `500: model_not_found`: FailProvider} { if got := failure(msg); got != want { t.Fatalf("%s: %s, want %s", msg, got, want) } } } // Unknown events are counted by type name and dropped: nothing else of // them is kept. func TestDecodeUnknownEvents(t *testing.T) { d := &Decoder{} for _, line := range []string{`{"type":"brand_new","secret":"tx-abc"}`, `{"type":"brand_new"}`, `{"type":"agent_start"}`, `{"type":"auto_retry_start","attempt":1}`, `{"type":"extension_ui_request","id":"x","method":"notify","message":"hi"}`} { evs, err := d.Decode([]byte(line)) if err != nil || len(evs) != 0 { t.Fatalf("%s: %v %v", line, evs, err) } } if len(d.Unknown) != 1 || d.Unknown["brand_new"] != 2 { t.Fatalf("unknown %v", d.Unknown) } raw, _ := json.Marshal(d.Unknown) if strings.Contains(string(raw), "tx-abc") { t.Fatal("an unknown event's content was kept") } if _, err := d.Decode([]byte(`not json`)); err == nil { t.Fatal("a broken record accepted") } } // An attempt's usage is the sum over its assistant messages' usage, with // Pi's input already uncached; it is complete only once the run ended. // Pi's own cost is the reported cost, in micro-units, when Pi priced it. func TestTallyUsage(t *testing.T) { tally := &Tally{} _, evs := replay(t, "mcp-tool") for i, e := range evs { if e.Kind == KindDone { if row := tally.Row(); row.Complete { t.Fatal("complete before the end") } } tally.Add(e) _ = i } row := tally.Row() if !row.Complete || row.Model != "z-ai/glm-5.3" || *row.InputTokens != 120 || *row.CachedInputTokens != 80 || *row.OutputTokens != 14 || *row.CacheWriteTokens != 0 || row.CostReportedMicros != nil { t.Fatalf("row %+v", row) } if *row.Turns != 2 { t.Fatalf("turns %d", *row.Turns) } priced := &Tally{} priced.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":true,"model":"m","input":10,"output":2,"cost":0.0123456,"priced":true}`)}) priced.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":true,"model":"m","input":10,"output":2,"cost":0.0000001,"priced":true}`)}) priced.Add(provider.Event{Kind: KindDone, Payload: json.RawMessage(`{"status":"completed"}`)}) if r := priced.Row(); r.CostReportedMicros == nil || *r.CostReportedMicros != 12346 { t.Fatalf("reported %v", r.CostReportedMicros) } // A run that ended without its end seen is incomplete. cut := &Tally{} cut.Add(evs[0]) if cut.Row().Complete { t.Fatal("complete without an end") } } func TestFamilyFromModel(t *testing.T) { for model, want := range map[string]string{"z-ai/glm-5.3": "glm", "z-ai/glm-5.3-flash": "glm", "moonshotai/kimi-k3.1-pro": "kimi", "deepseek/deepseek-v4-pro-0813": "deepseek", "minimax/minimax-m3.1-flash": "minimax", "qwen/qwen3.8-27b": "qwen", "other/thing": "other", "": ""} { if got := Family(model); got != want { t.Errorf("%s: %q want %q", model, got, want) } } } // Usage Pi did not give, or gave in a shape that cannot be counted, // stays unknown even when the run ends properly: no message's usage at // all, a message without its usage or without input or output, a // negative figure, a sum that overflows. Unknown is never zero. func TestTallyUnknownUsage(t *testing.T) { end := `{"type":"agent_end","willRetry":false}` msg := func(usage string) string { return `{"type":"message_end","message":{"role":"assistant","model":"m","stopReason":"stop"` + usage + `}}` } for _, tc := range []struct { name string lines []string }{ {"no message at all", []string{end}}, {"a message without usage", []string{msg(``), end}}, {"usage without input", []string{msg(`,"usage":{"output":3}`), end}}, {"usage without output", []string{msg(`,"usage":{"input":3}`), end}}, {"a negative figure", []string{msg(`,"usage":{"input":-1,"output":3}`), end}}, {"usage that is not an object", []string{msg(`,"usage":"lots"`), end}}, {"one good message, one without usage", []string{msg(`,"usage":{"input":3,"output":3}`), msg(``), end}}, {"a sum that overflows", []string{msg(`,"usage":{"input":9223372036854775807,"output":1}`), msg(`,"usage":{"input":1,"output":1}`), end}}, } { t.Run(tc.name, func(t *testing.T) { d, tally := &Decoder{}, &Tally{} for _, line := range tc.lines { evs, err := d.Decode([]byte(line)) if err != nil { t.Fatal(err) } for _, e := range evs { tally.Add(e) } } row := tally.Row() if row.InputTokens != nil || row.OutputTokens != nil { t.Fatalf("unknown usage counted: in %v out %v complete %v", row.InputTokens, row.OutputTokens, row.Complete) } }) } // Zero usage Pi reported (a refused request) is a known zero. d, tally := &Decoder{}, &Tally{} for _, line := range []string{msg(`,"usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0}`), end} { evs, _ := d.Decode([]byte(line)) for _, e := range evs { tally.Add(e) } } if row := tally.Row(); row.InputTokens == nil || *row.InputTokens != 0 || !row.Complete { t.Fatalf("a reported zero: %+v", row) } } // Security round #1 (§16.5): an attempt whose requests were answered by // more than one model reports one row per reported model, each with its // own figures and reported cost; the request count rides the first row // only; a message that cannot be counted leaves every row unknown. func TestTallyRowsPerModel(t *testing.T) { tally := &Tally{} for _, raw := range []string{ `{"valid":true,"model":"z-ai/glm-5.3","input":10,"output":2,"cache_read":4}`, `{"valid":true,"model":"vendor/other","input":7,"output":3,"cost":0.5,"priced":true}`, `{"valid":true,"model":"z-ai/glm-5.3","input":5,"output":1}`, } { tally.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(raw)}) } tally.Add(provider.Event{Kind: KindDone, Payload: json.RawMessage(`{"status":"completed"}`)}) rows := tally.Rows() if len(rows) != 2 || rows[0].Model != "z-ai/glm-5.3" || rows[1].Model != "vendor/other" { t.Fatalf("rows %+v", rows) } a, b := rows[0], rows[1] if *a.InputTokens != 15 || *a.OutputTokens != 3 || *a.CachedInputTokens != 4 || a.CostReportedMicros != nil || *a.Turns != 3 || !a.Complete { t.Fatalf("first model %+v", a) } if *b.InputTokens != 7 || *b.OutputTokens != 3 || b.CostReportedMicros == nil || *b.CostReportedMicros != 500000 || b.Turns != nil || !b.Complete { t.Fatalf("second model %+v", b) } if tally.Model() != "z-ai/glm-5.3" { t.Fatalf("the model that ran first %q", tally.Model()) } bad := &Tally{} bad.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":true,"model":"a","input":1,"output":1}`)}) bad.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":false,"model":"b"}`)}) for _, r := range bad.Rows() { if r.InputTokens != nil || r.OutputTokens != nil { t.Fatalf("an uncountable message left a row counted: %+v", r) } } }