package opencode import ( "encoding/json" "math" "strings" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/pi" ) // Equipo's kinds and payloads for an OpenCode run are a metered // harness's (connectors spec §3, "Mapping"), the same as Pi's, so one run // loop serves both: delta, tool_call, tool_result, ask, usage and done. const ( KindDelta = pi.KindDelta KindToolCall = pi.KindToolCall KindToolResult = pi.KindToolResult KindAsk = pi.KindAsk KindUsage = pi.KindUsage KindDone = pi.KindDone ) // The ACP methods the decoder reads. const ( methodUpdate = "session/update" methodPermission = "session/request_permission" ) // known are session/update kinds that carry nothing Equipo reads; they // are dropped without being counted as unknown. usage_update is the // session's context size and its cumulative cost (zero within Go's // plan): the turn's usage comes with the prompt's answer. var known = map[string]bool{ "user_message_chunk": true, "agent_thought_chunk": true, "plan": true, "plan_update": true, "plan_removed": true, "available_commands_update": true, "current_mode_update": true, "config_option_update": true, "session_info_update": true, "usage_update": true, "compaction_update": true, "compaction_summary_chunk": true, "notice": true, "session_message": true, "session_message_chunk": true, } // Decoder turns OpenCode's ACP messages for one session into Equipo's // events. It reads updates only while a turn runs (a session/load // replays the session's history as updates first, which are not this // turn's), and the prompt's answer ends the turn. Unknown messages are // counted by name and dropped; nothing else of them is kept. type Decoder struct { Unknown map[string]int // Model is the model the session runs (its usage's). Model string // Session is the session's id: updates about any other are dropped. Session string // CostBase is the session's reported cost before this process (0 for // a new session; for a resumed one, the cost recorded when it was // kept): usage_update says the session's cost so far. CostBase float64 prompt string active bool calls map[string]*call // cost is the session's reported cost so far, turnBase its value when // the turn started; costBad: a report this turn could not be read. cost, turnBase float64 costSet, costBad bool // retained is the bytes of arguments kept in calls. retained int // modelChanged: OpenCode reported the session's model option as // another model than Model (connectors spec §16.5): the turn fails and // no further prompt is sent. modelChanged bool } // ModelChanged reports whether OpenCode said the session's model is no // longer the one Equipo fixed. func (d *Decoder) ModelChanged() bool { return d.modelChanged } // SessionCost is the session's reported cost so far (what to record when // the session is kept). func (d *Decoder) SessionCost() float64 { if !d.costSet { return d.CostBase } return d.cost } type call struct { tool string args json.RawMessage sent bool } // The bounds on what the decoder keeps between updates (security round // finding 5): a tool call's id, the calls not yet run, and their // arguments in total. const ( maxToolID = 256 maxCalls = 1024 maxRetained = 4 << 20 ) // Start marks a turn running: its prompt request's id ends it. func (d *Decoder) Start(promptID string) { d.prompt, d.active, d.calls, d.retained = promptID, true, map[string]*call{}, 0 d.turnBase, d.costBad = d.SessionCost(), false } // observeCost reads a usage_update's cost: the session's so far, in USD, // finite, never below what was already reported (security round finding // 4). Anything else makes the turn's reported cost unreadable. func (d *Decoder) observeCost(raw json.RawMessage) { var c struct { Amount *float64 `json:"amount"` Currency string `json:"currency"` } if len(raw) == 0 { return } if json.Unmarshal(raw, &c) != nil || c.Amount == nil || c.Currency != "USD" || math.IsNaN(*c.Amount) || math.IsInf(*c.Amount, 0) || *c.Amount < 0 || *c.Amount < d.SessionCost() || *c.Amount > 1e9 { d.costBad = true return } d.cost, d.costSet = *c.Amount, true } // Active reports whether a turn runs. func (d *Decoder) Active() bool { return d.active } func (d *Decoder) unknown(name string) { if d.Unknown == nil { d.Unknown = map[string]int{} } d.Unknown[clipText(name, 64)]++ } func payload(v any) json.RawMessage { raw, _ := json.Marshal(v); return raw } // maxEventArgs bounds a tool call's arguments in an event: the runner // reads them only for the activity line. const maxEventArgs = 64 << 10 func clipArgs(raw json.RawMessage) json.RawMessage { if len(raw) > maxEventArgs { return nil } return raw } func clipText(s string, n int) string { if len(s) <= n { return s } return s[:n] } // rawID is a JSON-RPC id as text (a number or a string). func rawID(id json.RawMessage) string { var s string if json.Unmarshal(id, &s) == nil { return s } return string(id) } type toolUpdate struct { ToolCallID string `json:"toolCallId"` Name string `json:"name"` Title string `json:"title"` Status string `json:"status"` RawInput json.RawMessage `json:"rawInput"` } // Decode reads one message. func (d *Decoder) Decode(m Message) []provider.Event { switch { case m.Response(): if !d.active || rawID(m.ID) != d.prompt { return nil } d.active = false return d.end(m) case m.Request() && m.Method == methodPermission: var p struct { SessionID string `json:"sessionId"` ToolCall toolUpdate `json:"toolCall"` } _ = json.Unmarshal(m.Params, &p) tool := p.ToolCall.Name if tool == "" { tool = p.ToolCall.Title } return []provider.Event{{Kind: KindAsk, RequestID: rawID(m.ID), Payload: payload(pi.Ask{ID: rawID(m.ID), Method: methodPermission, Call: pi.ToolCall{ID: p.ToolCall.ToolCallID, Tool: clipText(tool, 128), Args: clipArgs(p.ToolCall.RawInput)}})}} case m.Method == methodUpdate: var p struct { SessionID string `json:"sessionId"` Update struct { Kind string `json:"sessionUpdate"` // Content is a text block for a message chunk, a list for // a tool call's update. Content json.RawMessage `json:"content"` Cost json.RawMessage `json:"cost"` // ConfigOptions are the session's options after a change // (config_option_update), the model among them. ConfigOptions []struct { ID string `json:"id"` CurrentValue string `json:"currentValue"` } `json:"configOptions"` toolUpdate } `json:"update"` } if json.Unmarshal(m.Params, &p) != nil { d.unknown(methodUpdate) return nil } if d.Session != "" && p.SessionID != d.Session { return nil } u := p.Update if u.Kind == "config_option_update" { for _, o := range u.ConfigOptions { if o.ID == "model" && o.CurrentValue != provider.OpenCodeModel(d.Model) { d.modelChanged = true } } return nil } if u.Kind == "usage_update" { // The session's cost so far, kept between turns too. d.observeCost(u.Cost) return nil } if !d.active { return nil } switch u.Kind { case "agent_message_chunk": var c struct{ Type, Text string } if json.Unmarshal(u.Content, &c) != nil || c.Type != "text" || c.Text == "" { return nil } return []provider.Event{{Kind: KindDelta, Payload: payload(pi.Delta{Text: c.Text})}} case "tool_call", "tool_call_update": return d.tool(u.toolUpdate, u.Kind == "tool_call") } if !known[u.Kind] { d.unknown(methodUpdate + ":" + u.Kind) } return nil case m.Method != "": d.unknown(m.Method) } return nil } // tool follows one tool call through its updates: OpenCode announces it // before its arguments are known, so the call is Equipo's tool_call at // its first update that runs it, and its end is the tool_result. func (d *Decoder) tool(u toolUpdate, announced bool) []provider.Event { if u.ToolCallID == "" { return nil } if len(u.ToolCallID) > maxToolID { d.unknown("tool id too long") return nil } if d.calls == nil { d.calls = map[string]*call{} } c := d.calls[u.ToolCallID] if c == nil { if len(d.calls) >= maxCalls { d.unknown("tool calls over the bound") return nil } c = &call{} d.calls[u.ToolCallID] = c } if u.Name != "" { c.tool = clipText(u.Name, 128) } else if c.tool == "" && u.Title != "" { c.tool = clipText(u.Title, 128) } if len(u.RawInput) > 0 && string(u.RawInput) != "{}" && string(u.RawInput) != "null" { args := clipArgs(u.RawInput) if d.retained-len(c.args)+len(args) > maxRetained { // Over the total: the call keeps no arguments (its activity // line has no subject). args = nil } d.retained += len(args) - len(c.args) c.args = args } var out []provider.Event ends := u.Status == "completed" || u.Status == "failed" if !c.sent && !announced && (u.Status == "in_progress" || ends) { c.sent = true out = append(out, provider.Event{Kind: KindToolCall, Payload: payload(pi.ToolCall{ID: u.ToolCallID, Tool: c.tool, Args: c.args})}) } if ends && c.sent { out = append(out, provider.Event{Kind: KindToolResult, Payload: payload(pi.ToolResult{ID: u.ToolCallID, Tool: c.tool, IsError: u.Status == "failed"})}) d.retained -= len(c.args) delete(d.calls, u.ToolCallID) } return out } // acpUsage is a prompt answer's usage: input is the uncached part, // output excludes reasoning (OpenCode's visible output), reasoning is // thoughtTokens. type acpUsage struct { Input *int64 `json:"inputTokens"` Output *int64 `json:"outputTokens"` Thought *int64 `json:"thoughtTokens"` CacheRead *int64 `json:"cachedReadTokens"` CacheWrite *int64 `json:"cachedWriteTokens"` } // usageOf reads the turn's usage and whether it can be counted. OpenCode // gives zero for any figure a provider did not report, so a turn whose // input is zero (no request reads no prompt) is not counted: its spend is // unknown, never zero. Output is the visible output and the reasoning // together, as Go bills reasoning as output. func (d *Decoder) usageOf(raw json.RawMessage) pi.Usage { out := pi.Usage{Model: d.Model} var u acpUsage 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 } in, visible, thought, read, write := *u.Input, *u.Output, figure(u.Thought), figure(u.CacheRead), figure(u.CacheWrite) if in < 0 || visible < 0 || thought < 0 || read < 0 || write < 0 || thought > math.MaxInt64-visible { return out } if in > math.MaxInt64-read || in+read > math.MaxInt64-write || in+read+write == 0 { return out } out.Input, out.Output, out.Reasoning, out.CacheRead, out.CacheWrite, out.Valid = in, visible+thought, thought, read, write, true if d.costBad { return pi.Usage{Model: d.Model} } if added := d.SessionCost() - d.turnBase; added > 0 { out.Cost, out.Priced = added, true } return out } // Failure classes of a turn that failed (pi's): OpenCode says a refused // key as an authentication error, and a provider's rate limit or a Go // plan's limit by its error name. func failure(e *RPCError) string { switch { case e == nil: return pi.FailProvider case e.Code == -32000 || strings.HasPrefix(e.Message, "Authentication required"): return pi.FailAuth case e.Data.ErrorName == "provider.rate-limit" || e.Data.ErrorName == "provider.budget-limit" || e.Data.ErrorName == "provider.model-budget-limit": return pi.FailQuota case e.Data.ErrorName == "provider.model-not-found" || strings.Contains(e.Message, "model_not_found"): // Not probed on the real binary (no real provider): the error name // is OpenCode's provider error pattern for a missing model. return pi.FailModel } return pi.FailProvider } // end is the prompt's answer: the turn's usage (always, so a turn // without a figure counts as one that cannot be priced), then its end. func (d *Decoder) end(m Message) []provider.Event { var r struct { StopReason string `json:"stopReason"` Usage json.RawMessage `json:"usage"` } done := pi.Done{Status: pi.StatusFailed, Failure: pi.FailProvider} if d.modelChanged { // Another model may have answered: never a completed turn. done.Error = "the session's model changed" } else if m.Error != nil { done.Failure, done.Error = failure(m.Error), clipText(m.Error.Message, 512) } else if json.Unmarshal(m.Result, &r) == nil { switch r.StopReason { case "end_turn": done = pi.Done{Status: pi.StatusCompleted} case "cancelled": done = pi.Done{Status: pi.StatusInterrupted} default: done.Error = "the turn ended: " + clipText(r.StopReason, 64) } } return []provider.Event{ {Kind: KindUsage, Payload: payload(d.usageOf(r.Usage))}, {Kind: KindDone, Payload: payload(done)}, } } // Family is the model family of an OpenCode Go model id (spec §3, // "Families"): its name before the version, glm-5.3 is glm, // kimi-k3.1-pro is kimi, hy4 is hunyuan. func Family(model string) string { name := strings.ToLower(model) if _, after, ok := strings.Cut(name, "/"); ok { name = after } for _, f := range []struct{ prefix, family string }{ {"glm", "glm"}, {"kimi", "kimi"}, {"deepseek", "deepseek"}, {"qwen", "qwen"}, {"minimax", "minimax"}, {"mimo", "mimo"}, {"longcat", "longcat"}, {"hy", "hunyuan"}, {"step", "step"}, } { if strings.HasPrefix(name, f.prefix) { return f.family } } family, _, _ := strings.Cut(name, "-") return strings.TrimRight(family, "0123456789.") } // Tally is an attempt's usage: the turn's figure from the prompt's // answer, complete once that answer came (spec §2.3; probe OC-P4: the // figure is the turn's own, summed over its requests, not the session's // running total). type Tally = pi.Tally