| 1 | package pi |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "math" |
| 8 | "strings" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | ) |
| 13 | |
| 14 | // Equipo's event kinds for a Pi run (connectors spec §3, "Mapping"). |
| 15 | const ( |
| 16 | KindDelta = "delta" |
| 17 | KindToolCall = "tool_call" |
| 18 | KindToolResult = "tool_result" |
| 19 | KindAsk = "ask" |
| 20 | KindUsage = "usage" |
| 21 | KindDone = "done" |
| 22 | ) |
| 23 | |
| 24 | // How a run ended, and the failure classes of a failed one. |
| 25 | const ( |
| 26 | StatusCompleted = "completed" |
| 27 | StatusFailed = "failed" |
| 28 | StatusInterrupted = "interrupted" |
| 29 | |
| 30 | // FailAuth: the provider refused the key (HTTP 401 or 403). For |
| 31 | // TensorX that is also a balance under $0.05 (spec §4.1). |
| 32 | FailAuth = "auth" |
| 33 | // FailQuota: the provider's rate limit, after Pi's own retries. |
| 34 | FailQuota = "quota" |
| 35 | // FailProvider: anything else the provider or the network did. |
| 36 | FailProvider = "provider" |
| 37 | // FailModel: the provider does not have the model (HTTP 404, or its |
| 38 | // model_not_found error): the model, not the key, is at fault |
| 39 | // (connectors spec §16.4). |
| 40 | FailModel = "model" |
| 41 | ) |
| 42 | |
| 43 | // Payloads of the kinds. |
| 44 | type ( |
| 45 | Delta struct { |
| 46 | Text string `json:"text"` |
| 47 | } |
| 48 | ToolCall struct { |
| 49 | ID string `json:"id"` |
| 50 | Tool string `json:"tool"` |
| 51 | Args json.RawMessage `json:"args,omitempty"` |
| 52 | } |
| 53 | ToolResult struct { |
| 54 | ID string `json:"id"` |
| 55 | Tool string `json:"tool"` |
| 56 | IsError bool `json:"is_error"` |
| 57 | } |
| 58 | // Ask is the extension asking Equipo whether a call may run (an |
| 59 | // extension_ui_request dialog). Call is the call it asks about, as |
| 60 | // Equipo's extension words it. |
| 61 | Ask struct { |
| 62 | ID string `json:"id"` |
| 63 | Method string `json:"method"` |
| 64 | Call ToolCall `json:"call"` |
| 65 | } |
| 66 | // Usage is one assistant message's usage as Pi reported it: input is |
| 67 | // already the uncached part. Cost is Pi's own figure in dollars, and |
| 68 | // Priced says Pi had one (from the provider or a configured price). |
| 69 | // Valid is false when Pi gave no usage, or none that can be counted |
| 70 | // (no input or output, a negative figure): the attempt's usage is |
| 71 | // then unknown, never zero. |
| 72 | Usage struct { |
| 73 | Valid bool `json:"valid"` |
| 74 | Model string `json:"model"` |
| 75 | Input int64 `json:"input"` |
| 76 | Output int64 `json:"output"` |
| 77 | CacheRead int64 `json:"cache_read"` |
| 78 | CacheWrite int64 `json:"cache_write"` |
| 79 | Reasoning int64 `json:"reasoning"` |
| 80 | Cost float64 `json:"cost"` |
| 81 | Priced bool `json:"priced"` |
| 82 | } |
| 83 | // Done is how the run ended. Error is Pi's message for a failure, |
| 84 | // clipped, for the step's log; it is never sent to the instance. |
| 85 | Done struct { |
| 86 | Status string `json:"status"` |
| 87 | Failure string `json:"failure,omitempty"` |
| 88 | Error string `json:"error,omitempty"` |
| 89 | } |
| 90 | ) |
| 91 | |
| 92 | // known are Pi's event types that carry nothing Equipo reads; they are |
| 93 | // dropped without being counted as unknown. |
| 94 | var known = map[string]bool{ |
| 95 | "agent_start": true, "turn_start": true, "turn_end": true, "message_start": true, |
| 96 | "tool_execution_update": true, "queue_update": true, "entry_appended": true, |
| 97 | "session_info_changed": true, "thinking_level_changed": true, "compaction_start": true, |
| 98 | "compaction_end": true, "auto_retry_start": true, "auto_retry_end": true, |
| 99 | "summarization_retry_scheduled": true, "summarization_retry_attempt_start": true, |
| 100 | "summarization_retry_finished": true, "agent_settled": true, "extension_error": true, |
| 101 | "bash_execution_update": true, "response": true, |
| 102 | } |
| 103 | |
| 104 | // Decoder turns Pi's RPC records into Equipo's events. Unknown records |
| 105 | // are counted by type name and dropped; nothing else of them is kept. |
| 106 | type Decoder struct { |
| 107 | Unknown map[string]int |
| 108 | // last is the newest assistant message's ending. |
| 109 | lastStop, lastError string |
| 110 | } |
| 111 | |
| 112 | var errRecord = errors.New("pi: not an RPC record") |
| 113 | |
| 114 | func payload(v any) json.RawMessage { raw, _ := json.Marshal(v); return raw } |
| 115 | |
| 116 | // Decode reads one record. |
| 117 | func (d *Decoder) Decode(line []byte) ([]provider.Event, error) { |
| 118 | line = bytes.TrimSuffix(line, []byte("\r")) |
| 119 | var r struct { |
| 120 | Type string `json:"type"` |
| 121 | ID string `json:"id"` |
| 122 | Method string `json:"method"` |
| 123 | Message json.RawMessage `json:"message"` |
| 124 | Title string `json:"title"` |
| 125 | WillRetry bool `json:"willRetry"` |
| 126 | ToolCallID string `json:"toolCallId"` |
| 127 | ToolName string `json:"toolName"` |
| 128 | Args json.RawMessage `json:"args"` |
| 129 | IsError bool `json:"isError"` |
| 130 | AssistantMessageEvent struct { |
| 131 | Type string `json:"type"` |
| 132 | Delta string `json:"delta"` |
| 133 | } `json:"assistantMessageEvent"` |
| 134 | } |
| 135 | if err := json.Unmarshal(line, &r); err != nil || r.Type == "" { |
| 136 | return nil, errRecord |
| 137 | } |
| 138 | event := func(kind string, v any) []provider.Event { |
| 139 | return []provider.Event{{Kind: kind, Payload: payload(v)}} |
| 140 | } |
| 141 | switch r.Type { |
| 142 | case "message_update": |
| 143 | if r.AssistantMessageEvent.Type == "text_delta" && r.AssistantMessageEvent.Delta != "" { |
| 144 | return event(KindDelta, Delta{Text: r.AssistantMessageEvent.Delta}), nil |
| 145 | } |
| 146 | return nil, nil |
| 147 | case "message_end": |
| 148 | var m struct { |
| 149 | Role, Model, StopReason, ErrorMessage string |
| 150 | Usage json.RawMessage |
| 151 | } |
| 152 | if json.Unmarshal(r.Message, &m) != nil || m.Role != "assistant" { |
| 153 | return nil, nil |
| 154 | } |
| 155 | d.lastStop, d.lastError = m.StopReason, m.ErrorMessage |
| 156 | return event(KindUsage, usageOf(m.Model, m.Usage)), nil |
| 157 | case "tool_execution_start": |
| 158 | return event(KindToolCall, ToolCall{ID: r.ToolCallID, Tool: r.ToolName, Args: clipArgs(r.Args)}), nil |
| 159 | case "tool_execution_end": |
| 160 | return event(KindToolResult, ToolResult{ID: r.ToolCallID, Tool: r.ToolName, IsError: r.IsError}), nil |
| 161 | case "extension_ui_request": |
| 162 | switch r.Method { |
| 163 | case "confirm", "select", "input", "editor": |
| 164 | a := Ask{ID: r.ID, Method: r.Method} |
| 165 | var raw struct { |
| 166 | Message string `json:"message"` |
| 167 | } |
| 168 | if json.Unmarshal(line, &raw) == nil && r.Title == askTitle { |
| 169 | _ = json.Unmarshal([]byte(raw.Message), &a.Call) |
| 170 | a.Call.Args = clipArgs(a.Call.Args) |
| 171 | } |
| 172 | return event(KindAsk, a), nil |
| 173 | } |
| 174 | // Notifications and status lines need no answer. |
| 175 | return nil, nil |
| 176 | case "agent_end": |
| 177 | if r.WillRetry { |
| 178 | return nil, nil |
| 179 | } |
| 180 | done := Done{Status: StatusCompleted} |
| 181 | switch d.lastStop { |
| 182 | case "aborted": |
| 183 | done.Status = StatusInterrupted |
| 184 | case "error": |
| 185 | done.Status, done.Failure, done.Error = StatusFailed, failure(d.lastError), clipText(d.lastError, 300) |
| 186 | } |
| 187 | return event(KindDone, done), nil |
| 188 | } |
| 189 | if !known[r.Type] { |
| 190 | if d.Unknown == nil { |
| 191 | d.Unknown = map[string]int{} |
| 192 | } |
| 193 | if len(d.Unknown) < 64 && len(r.Type) <= 64 { |
| 194 | d.Unknown[r.Type]++ |
| 195 | } |
| 196 | } |
| 197 | return nil, nil |
| 198 | } |
| 199 | |
| 200 | // usageOf reads one message's usage: every figure Pi gave, and whether |
| 201 | // it can be counted. |
| 202 | func usageOf(model string, raw json.RawMessage) Usage { |
| 203 | var u struct { |
| 204 | Input, Output, CacheRead, CacheWrite, Reasoning *int64 |
| 205 | Cost struct { |
| 206 | Total float64 |
| 207 | TotalFromProvider bool |
| 208 | } |
| 209 | } |
| 210 | out := Usage{Model: model} |
| 211 | if len(raw) == 0 || json.Unmarshal(raw, &u) != nil || u.Input == nil || u.Output == nil { |
| 212 | return out |
| 213 | } |
| 214 | figure := func(v *int64) int64 { |
| 215 | if v == nil { |
| 216 | return 0 |
| 217 | } |
| 218 | return *v |
| 219 | } |
| 220 | out.Input, out.Output, out.CacheRead, out.CacheWrite, out.Reasoning = *u.Input, *u.Output, figure(u.CacheRead), figure(u.CacheWrite), figure(u.Reasoning) |
| 221 | 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) { |
| 222 | return Usage{Model: model} |
| 223 | } |
| 224 | out.Cost, out.Priced, out.Valid = u.Cost.Total, u.Cost.TotalFromProvider || u.Cost.Total > 0, true |
| 225 | return out |
| 226 | } |
| 227 | |
| 228 | // maxEventArgs bounds a tool call's arguments in an event: the runner |
| 229 | // reads them only for the activity line. |
| 230 | const maxEventArgs = 64 << 10 |
| 231 | |
| 232 | // clipArgs drops arguments over maxEventArgs. |
| 233 | func clipArgs(raw json.RawMessage) json.RawMessage { |
| 234 | if len(raw) > maxEventArgs { |
| 235 | return nil |
| 236 | } |
| 237 | return raw |
| 238 | } |
| 239 | |
| 240 | // askTitle is the title Equipo's extension gives its question. |
| 241 | const askTitle = "equipo:tool_call" |
| 242 | |
| 243 | // failure classes a provider error by the HTTP status Pi puts first. |
| 244 | func failure(message string) string { |
| 245 | status, _, _ := strings.Cut(message, ":") |
| 246 | switch status { |
| 247 | case "401", "403": |
| 248 | return FailAuth |
| 249 | case "429": |
| 250 | return FailQuota |
| 251 | case "404": |
| 252 | return FailModel |
| 253 | } |
| 254 | if strings.HasPrefix(status, "4") && strings.Contains(message, "model_not_found") { |
| 255 | return FailModel |
| 256 | } |
| 257 | return FailProvider |
| 258 | } |
| 259 | |
| 260 | // Family is the model family of a model id behind Pi (spec §4.1), from |
| 261 | // its vendor: z-ai/glm-5.3 is glm, moonshotai/kimi-k3.1-pro is kimi. |
| 262 | func Family(model string) string { |
| 263 | vendor, _, ok := strings.Cut(model, "/") |
| 264 | if !ok { |
| 265 | return "" |
| 266 | } |
| 267 | switch vendor { |
| 268 | case "z-ai", "zai", "zhipu": |
| 269 | return "glm" |
| 270 | case "moonshotai", "moonshot": |
| 271 | return "kimi" |
| 272 | case "qwen", "alibaba": |
| 273 | return "qwen" |
| 274 | } |
| 275 | return vendor |
| 276 | } |
| 277 | |
| 278 | // Tally sums an attempt's usage over its assistant messages (spec §2.3: |
| 279 | // Pi's message_end usage is per request), apart for each model a |
| 280 | // request reports (§16.5): a later request answered by another model |
| 281 | // is that model's row, so its mismatch is seen and it is priced as |
| 282 | // itself. Every row is complete once the run's end was seen; every |
| 283 | // row's figures are unknown (null) when there was no message, a |
| 284 | // message's usage could not be counted, or a sum overflowed. |
| 285 | type Tally struct { |
| 286 | models []*modelSum |
| 287 | invalid bool |
| 288 | turns int64 |
| 289 | complete bool |
| 290 | } |
| 291 | |
| 292 | // modelSum is one reported model's part of an attempt. |
| 293 | type modelSum struct { |
| 294 | model string |
| 295 | input, output, cacheRead, cacheWrite, thinking int64 |
| 296 | reported float64 |
| 297 | priced bool |
| 298 | } |
| 299 | |
| 300 | // add is a + b, or false when it overflows. |
| 301 | func add(a, b int64) (int64, bool) { |
| 302 | if b > 0 && a > math.MaxInt64-b { |
| 303 | return 0, false |
| 304 | } |
| 305 | return a + b, true |
| 306 | } |
| 307 | |
| 308 | // Add takes one decoded event; only usage and done count. |
| 309 | func (t *Tally) Add(e provider.Event) { |
| 310 | switch e.Kind { |
| 311 | case KindUsage: |
| 312 | t.turns++ |
| 313 | var u Usage |
| 314 | if json.Unmarshal(e.Payload, &u) != nil || !u.Valid { |
| 315 | t.invalid = true |
| 316 | return |
| 317 | } |
| 318 | var m *modelSum |
| 319 | for _, x := range t.models { |
| 320 | if x.model == u.Model { |
| 321 | m = x |
| 322 | } |
| 323 | } |
| 324 | if m == nil { |
| 325 | m = &modelSum{model: u.Model} |
| 326 | t.models = append(t.models, m) |
| 327 | } |
| 328 | for _, p := range []struct { |
| 329 | sum *int64 |
| 330 | v int64 |
| 331 | }{{&m.input, u.Input}, {&m.output, u.Output}, {&m.cacheRead, u.CacheRead}, {&m.cacheWrite, u.CacheWrite}, {&m.thinking, u.Reasoning}} { |
| 332 | v, ok := add(*p.sum, p.v) |
| 333 | if !ok { |
| 334 | t.invalid = true |
| 335 | } |
| 336 | *p.sum = v |
| 337 | } |
| 338 | m.reported += u.Cost |
| 339 | m.priced = m.priced || u.Priced |
| 340 | case KindDone: |
| 341 | t.complete = true |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | // Model is the model that answered first. |
| 346 | func (t *Tally) Model() string { |
| 347 | if len(t.models) == 0 { |
| 348 | return "" |
| 349 | } |
| 350 | return t.models[0].model |
| 351 | } |
| 352 | |
| 353 | // Rows are the attempt's usage rows, one per reported model in the order |
| 354 | // they first answered (provider, connection and attempt are the |
| 355 | // caller's); the request count rides the first row only. |
| 356 | func (t *Tally) Rows() []wire.Usage { |
| 357 | v := func(n int64) *int64 { return &n } |
| 358 | if len(t.models) == 0 { |
| 359 | return []wire.Usage{{Complete: t.complete, Turns: v(t.turns)}} |
| 360 | } |
| 361 | out := make([]wire.Usage, 0, len(t.models)) |
| 362 | for i, m := range t.models { |
| 363 | row := wire.Usage{Model: m.model, Complete: t.complete} |
| 364 | if i == 0 { |
| 365 | row.Turns = v(t.turns) |
| 366 | } |
| 367 | if !t.invalid { |
| 368 | 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) |
| 369 | if m.priced && m.reported >= 0 && m.reported < math.MaxInt64/1e6 { |
| 370 | row.CostReportedMicros = v(int64(math.Ceil(m.reported*1e6 - 1e-9))) |
| 371 | } |
| 372 | } |
| 373 | out = append(out, row) |
| 374 | } |
| 375 | return out |
| 376 | } |
| 377 | |
| 378 | // Row is the attempt's first row (an attempt on one model has only it). |
| 379 | func (t *Tally) Row() wire.Usage { return t.Rows()[0] } |
| 380 | |
| 381 | func clipText(s string, n int) string { |
| 382 | if len(s) <= n { |
| 383 | return s |
| 384 | } |
| 385 | return s[:n] |
| 386 | } |
| 387 | |