package pi import ( "bytes" "encoding/json" "errors" "math" "strings" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" ) // Equipo's event kinds for a Pi run (connectors spec §3, "Mapping"). const ( KindDelta = "delta" KindToolCall = "tool_call" KindToolResult = "tool_result" KindAsk = "ask" KindUsage = "usage" KindDone = "done" ) // How a run ended, and the failure classes of a failed one. const ( StatusCompleted = "completed" StatusFailed = "failed" StatusInterrupted = "interrupted" // FailAuth: the provider refused the key (HTTP 401 or 403). For // TensorX that is also a balance under $0.05 (spec §4.1). FailAuth = "auth" // FailQuota: the provider's rate limit, after Pi's own retries. FailQuota = "quota" // FailProvider: anything else the provider or the network did. FailProvider = "provider" // FailModel: the provider does not have the model (HTTP 404, or its // model_not_found error): the model, not the key, is at fault // (connectors spec §16.4). FailModel = "model" ) // Payloads of the kinds. type ( Delta struct { Text string `json:"text"` } ToolCall struct { ID string `json:"id"` Tool string `json:"tool"` Args json.RawMessage `json:"args,omitempty"` } ToolResult struct { ID string `json:"id"` Tool string `json:"tool"` IsError bool `json:"is_error"` } // Ask is the extension asking Equipo whether a call may run (an // extension_ui_request dialog). Call is the call it asks about, as // Equipo's extension words it. Ask struct { ID string `json:"id"` Method string `json:"method"` Call ToolCall `json:"call"` } // Usage is one assistant message's usage as Pi reported it: input is // already the uncached part. Cost is Pi's own figure in dollars, and // Priced says Pi had one (from the provider or a configured price). // Valid is false when Pi gave no usage, or none that can be counted // (no input or output, a negative figure): the attempt's usage is // then unknown, never zero. Usage struct { Valid bool `json:"valid"` Model string `json:"model"` Input int64 `json:"input"` Output int64 `json:"output"` CacheRead int64 `json:"cache_read"` CacheWrite int64 `json:"cache_write"` Reasoning int64 `json:"reasoning"` Cost float64 `json:"cost"` Priced bool `json:"priced"` } // Done is how the run ended. Error is Pi's message for a failure, // clipped, for the step's log; it is never sent to the instance. Done struct { Status string `json:"status"` Failure string `json:"failure,omitempty"` Error string `json:"error,omitempty"` } ) // known are Pi's event types that carry nothing Equipo reads; they are // dropped without being counted as unknown. var known = map[string]bool{ "agent_start": true, "turn_start": true, "turn_end": true, "message_start": true, "tool_execution_update": true, "queue_update": true, "entry_appended": true, "session_info_changed": true, "thinking_level_changed": true, "compaction_start": true, "compaction_end": true, "auto_retry_start": true, "auto_retry_end": true, "summarization_retry_scheduled": true, "summarization_retry_attempt_start": true, "summarization_retry_finished": true, "agent_settled": true, "extension_error": true, "bash_execution_update": true, "response": true, } // Decoder turns Pi's RPC records into Equipo's events. Unknown records // are counted by type name and dropped; nothing else of them is kept. type Decoder struct { Unknown map[string]int // last is the newest assistant message's ending. lastStop, lastError string } var errRecord = errors.New("pi: not an RPC record") func payload(v any) json.RawMessage { raw, _ := json.Marshal(v); return raw } // Decode reads one record. func (d *Decoder) Decode(line []byte) ([]provider.Event, error) { line = bytes.TrimSuffix(line, []byte("\r")) var r struct { Type string `json:"type"` ID string `json:"id"` Method string `json:"method"` Message json.RawMessage `json:"message"` Title string `json:"title"` WillRetry bool `json:"willRetry"` ToolCallID string `json:"toolCallId"` ToolName string `json:"toolName"` Args json.RawMessage `json:"args"` IsError bool `json:"isError"` AssistantMessageEvent struct { Type string `json:"type"` Delta string `json:"delta"` } `json:"assistantMessageEvent"` } if err := json.Unmarshal(line, &r); err != nil || r.Type == "" { return nil, errRecord } event := func(kind string, v any) []provider.Event { return []provider.Event{{Kind: kind, Payload: payload(v)}} } switch r.Type { case "message_update": if r.AssistantMessageEvent.Type == "text_delta" && r.AssistantMessageEvent.Delta != "" { return event(KindDelta, Delta{Text: r.AssistantMessageEvent.Delta}), nil } return nil, nil case "message_end": var m struct { Role, Model, StopReason, ErrorMessage string Usage json.RawMessage } if json.Unmarshal(r.Message, &m) != nil || m.Role != "assistant" { return nil, nil } d.lastStop, d.lastError = m.StopReason, m.ErrorMessage return event(KindUsage, usageOf(m.Model, m.Usage)), nil case "tool_execution_start": return event(KindToolCall, ToolCall{ID: r.ToolCallID, Tool: r.ToolName, Args: clipArgs(r.Args)}), nil case "tool_execution_end": return event(KindToolResult, ToolResult{ID: r.ToolCallID, Tool: r.ToolName, IsError: r.IsError}), nil case "extension_ui_request": switch r.Method { case "confirm", "select", "input", "editor": a := Ask{ID: r.ID, Method: r.Method} var raw struct { Message string `json:"message"` } if json.Unmarshal(line, &raw) == nil && r.Title == askTitle { _ = json.Unmarshal([]byte(raw.Message), &a.Call) a.Call.Args = clipArgs(a.Call.Args) } return event(KindAsk, a), nil } // Notifications and status lines need no answer. return nil, nil case "agent_end": if r.WillRetry { return nil, nil } done := Done{Status: StatusCompleted} switch d.lastStop { case "aborted": done.Status = StatusInterrupted case "error": done.Status, done.Failure, done.Error = StatusFailed, failure(d.lastError), clipText(d.lastError, 300) } return event(KindDone, done), nil } if !known[r.Type] { if d.Unknown == nil { d.Unknown = map[string]int{} } if len(d.Unknown) < 64 && len(r.Type) <= 64 { d.Unknown[r.Type]++ } } return nil, nil } // usageOf reads one message's usage: every figure Pi gave, and whether // it can be counted. func usageOf(model string, raw json.RawMessage) Usage { var u struct { Input, Output, CacheRead, CacheWrite, Reasoning *int64 Cost struct { Total float64 TotalFromProvider bool } } out := Usage{Model: model} if len(raw) == 0 || json.Unmarshal(raw, &u) != nil || u.Input == nil || u.Output == nil { return out } figure := func(v *int64) int64 { if v == nil { return 0 } return *v } out.Input, out.Output, out.CacheRead, out.CacheWrite, out.Reasoning = *u.Input, *u.Output, figure(u.CacheRead), figure(u.CacheWrite), figure(u.Reasoning) if out.Input < 0 || out.Output < 0 || out.CacheRead < 0 || out.CacheWrite < 0 || out.Reasoning < 0 || u.Cost.Total < 0 || math.IsNaN(u.Cost.Total) || math.IsInf(u.Cost.Total, 0) { return Usage{Model: model} } out.Cost, out.Priced, out.Valid = u.Cost.Total, u.Cost.TotalFromProvider || u.Cost.Total > 0, true return out } // maxEventArgs bounds a tool call's arguments in an event: the runner // reads them only for the activity line. const maxEventArgs = 64 << 10 // clipArgs drops arguments over maxEventArgs. func clipArgs(raw json.RawMessage) json.RawMessage { if len(raw) > maxEventArgs { return nil } return raw } // askTitle is the title Equipo's extension gives its question. const askTitle = "equipo:tool_call" // failure classes a provider error by the HTTP status Pi puts first. func failure(message string) string { status, _, _ := strings.Cut(message, ":") switch status { case "401", "403": return FailAuth case "429": return FailQuota case "404": return FailModel } if strings.HasPrefix(status, "4") && strings.Contains(message, "model_not_found") { return FailModel } return FailProvider } // Family is the model family of a model id behind Pi (spec §4.1), from // its vendor: z-ai/glm-5.3 is glm, moonshotai/kimi-k3.1-pro is kimi. func Family(model string) string { vendor, _, ok := strings.Cut(model, "/") if !ok { return "" } switch vendor { case "z-ai", "zai", "zhipu": return "glm" case "moonshotai", "moonshot": return "kimi" case "qwen", "alibaba": return "qwen" } return vendor } // Tally sums an attempt's usage over its assistant messages (spec §2.3: // Pi's message_end usage is per request), apart for each model a // request reports (§16.5): a later request answered by another model // is that model's row, so its mismatch is seen and it is priced as // itself. Every row is complete once the run's end was seen; every // row's figures are unknown (null) when there was no message, a // message's usage could not be counted, or a sum overflowed. type Tally struct { models []*modelSum invalid bool turns int64 complete bool } // modelSum is one reported model's part of an attempt. type modelSum struct { model string input, output, cacheRead, cacheWrite, thinking int64 reported float64 priced bool } // add is a + b, or false when it overflows. func add(a, b int64) (int64, bool) { if b > 0 && a > math.MaxInt64-b { return 0, false } return a + b, true } // Add takes one decoded event; only usage and done count. func (t *Tally) Add(e provider.Event) { switch e.Kind { case KindUsage: t.turns++ var u Usage if json.Unmarshal(e.Payload, &u) != nil || !u.Valid { t.invalid = true return } var m *modelSum for _, x := range t.models { if x.model == u.Model { m = x } } if m == nil { m = &modelSum{model: u.Model} t.models = append(t.models, m) } for _, p := range []struct { sum *int64 v int64 }{{&m.input, u.Input}, {&m.output, u.Output}, {&m.cacheRead, u.CacheRead}, {&m.cacheWrite, u.CacheWrite}, {&m.thinking, u.Reasoning}} { v, ok := add(*p.sum, p.v) if !ok { t.invalid = true } *p.sum = v } m.reported += u.Cost m.priced = m.priced || u.Priced case KindDone: t.complete = true } } // Model is the model that answered first. func (t *Tally) Model() string { if len(t.models) == 0 { return "" } return t.models[0].model } // Rows are the attempt's usage rows, one per reported model in the order // they first answered (provider, connection and attempt are the // caller's); the request count rides the first row only. func (t *Tally) Rows() []wire.Usage { v := func(n int64) *int64 { return &n } if len(t.models) == 0 { return []wire.Usage{{Complete: t.complete, Turns: v(t.turns)}} } out := make([]wire.Usage, 0, len(t.models)) for i, m := range t.models { row := wire.Usage{Model: m.model, Complete: t.complete} if i == 0 { row.Turns = v(t.turns) } if !t.invalid { row.InputTokens, row.OutputTokens, row.CachedInputTokens, row.CacheWriteTokens, row.ReasoningOutputTokens = v(m.input), v(m.output), v(m.cacheRead), v(m.cacheWrite), v(m.thinking) if m.priced && m.reported >= 0 && m.reported < math.MaxInt64/1e6 { row.CostReportedMicros = v(int64(math.Ceil(m.reported*1e6 - 1e-9))) } } out = append(out, row) } return out } // Row is the attempt's first row (an attempt on one model has only it). func (t *Tally) Row() wire.Usage { return t.Rows()[0] } func clipText(s string, n int) string { if len(s) <= n { return s } return s[:n] }