oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package opencode
2
3import (
4 "encoding/json"
5 "math"
6 "strings"
7
8 "amadan.net/oficina/equipo/internal/runner/provider"
9 "amadan.net/oficina/equipo/internal/runner/provider/pi"
10)
11
12// Equipo's kinds and payloads for an OpenCode run are a metered
13// harness's (connectors spec §3, "Mapping"), the same as Pi's, so one run
14// loop serves both: delta, tool_call, tool_result, ask, usage and done.
15const (
16 KindDelta = pi.KindDelta
17 KindToolCall = pi.KindToolCall
18 KindToolResult = pi.KindToolResult
19 KindAsk = pi.KindAsk
20 KindUsage = pi.KindUsage
21 KindDone = pi.KindDone
22)
23
24// The ACP methods the decoder reads.
25const (
26 methodUpdate = "session/update"
27 methodPermission = "session/request_permission"
28)
29
30// known are session/update kinds that carry nothing Equipo reads; they
31// are dropped without being counted as unknown. usage_update is the
32// session's context size and its cumulative cost (zero within Go's
33// plan): the turn's usage comes with the prompt's answer.
34var known = map[string]bool{
35 "user_message_chunk": true, "agent_thought_chunk": true, "plan": true, "plan_update": true,
36 "plan_removed": true, "available_commands_update": true, "current_mode_update": true,
37 "config_option_update": true, "session_info_update": true, "usage_update": true,
38 "compaction_update": true, "compaction_summary_chunk": true, "notice": true,
39 "session_message": true, "session_message_chunk": true,
40}
41
42// Decoder turns OpenCode's ACP messages for one session into Equipo's
43// events. It reads updates only while a turn runs (a session/load
44// replays the session's history as updates first, which are not this
45// turn's), and the prompt's answer ends the turn. Unknown messages are
46// counted by name and dropped; nothing else of them is kept.
47type Decoder struct {
48 Unknown map[string]int
49 // Model is the model the session runs (its usage's).
50 Model string
51 // Session is the session's id: updates about any other are dropped.
52 Session string
53 // CostBase is the session's reported cost before this process (0 for
54 // a new session; for a resumed one, the cost recorded when it was
55 // kept): usage_update says the session's cost so far.
56 CostBase float64
57 prompt string
58 active bool
59 calls map[string]*call
60 // cost is the session's reported cost so far, turnBase its value when
61 // the turn started; costBad: a report this turn could not be read.
62 cost, turnBase float64
63 costSet, costBad bool
64 // retained is the bytes of arguments kept in calls.
65 retained int
66 // modelChanged: OpenCode reported the session's model option as
67 // another model than Model (connectors spec §16.5): the turn fails and
68 // no further prompt is sent.
69 modelChanged bool
70}
71
72// ModelChanged reports whether OpenCode said the session's model is no
73// longer the one Equipo fixed.
74func (d *Decoder) ModelChanged() bool { return d.modelChanged }
75
76// SessionCost is the session's reported cost so far (what to record when
77// the session is kept).
78func (d *Decoder) SessionCost() float64 {
79 if !d.costSet {
80 return d.CostBase
81 }
82 return d.cost
83}
84
85type call struct {
86 tool string
87 args json.RawMessage
88 sent bool
89}
90
91// The bounds on what the decoder keeps between updates (security round
92// finding 5): a tool call's id, the calls not yet run, and their
93// arguments in total.
94const (
95 maxToolID = 256
96 maxCalls = 1024
97 maxRetained = 4 << 20
98)
99
100// Start marks a turn running: its prompt request's id ends it.
101func (d *Decoder) Start(promptID string) {
102 d.prompt, d.active, d.calls, d.retained = promptID, true, map[string]*call{}, 0
103 d.turnBase, d.costBad = d.SessionCost(), false
104}
105
106// observeCost reads a usage_update's cost: the session's so far, in USD,
107// finite, never below what was already reported (security round finding
108// 4). Anything else makes the turn's reported cost unreadable.
109func (d *Decoder) observeCost(raw json.RawMessage) {
110 var c struct {
111 Amount *float64 `json:"amount"`
112 Currency string `json:"currency"`
113 }
114 if len(raw) == 0 {
115 return
116 }
117 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 {
118 d.costBad = true
119 return
120 }
121 d.cost, d.costSet = *c.Amount, true
122}
123
124// Active reports whether a turn runs.
125func (d *Decoder) Active() bool { return d.active }
126
127func (d *Decoder) unknown(name string) {
128 if d.Unknown == nil {
129 d.Unknown = map[string]int{}
130 }
131 d.Unknown[clipText(name, 64)]++
132}
133
134func payload(v any) json.RawMessage { raw, _ := json.Marshal(v); return raw }
135
136// maxEventArgs bounds a tool call's arguments in an event: the runner
137// reads them only for the activity line.
138const maxEventArgs = 64 << 10
139
140func clipArgs(raw json.RawMessage) json.RawMessage {
141 if len(raw) > maxEventArgs {
142 return nil
143 }
144 return raw
145}
146
147func clipText(s string, n int) string {
148 if len(s) <= n {
149 return s
150 }
151 return s[:n]
152}
153
154// rawID is a JSON-RPC id as text (a number or a string).
155func rawID(id json.RawMessage) string {
156 var s string
157 if json.Unmarshal(id, &s) == nil {
158 return s
159 }
160 return string(id)
161}
162
163type toolUpdate struct {
164 ToolCallID string `json:"toolCallId"`
165 Name string `json:"name"`
166 Title string `json:"title"`
167 Status string `json:"status"`
168 RawInput json.RawMessage `json:"rawInput"`
169}
170
171// Decode reads one message.
172func (d *Decoder) Decode(m Message) []provider.Event {
173 switch {
174 case m.Response():
175 if !d.active || rawID(m.ID) != d.prompt {
176 return nil
177 }
178 d.active = false
179 return d.end(m)
180 case m.Request() && m.Method == methodPermission:
181 var p struct {
182 SessionID string `json:"sessionId"`
183 ToolCall toolUpdate `json:"toolCall"`
184 }
185 _ = json.Unmarshal(m.Params, &p)
186 tool := p.ToolCall.Name
187 if tool == "" {
188 tool = p.ToolCall.Title
189 }
190 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)}})}}
191 case m.Method == methodUpdate:
192 var p struct {
193 SessionID string `json:"sessionId"`
194 Update struct {
195 Kind string `json:"sessionUpdate"`
196 // Content is a text block for a message chunk, a list for
197 // a tool call's update.
198 Content json.RawMessage `json:"content"`
199 Cost json.RawMessage `json:"cost"`
200 // ConfigOptions are the session's options after a change
201 // (config_option_update), the model among them.
202 ConfigOptions []struct {
203 ID string `json:"id"`
204 CurrentValue string `json:"currentValue"`
205 } `json:"configOptions"`
206 toolUpdate
207 } `json:"update"`
208 }
209 if json.Unmarshal(m.Params, &p) != nil {
210 d.unknown(methodUpdate)
211 return nil
212 }
213 if d.Session != "" && p.SessionID != d.Session {
214 return nil
215 }
216 u := p.Update
217 if u.Kind == "config_option_update" {
218 for _, o := range u.ConfigOptions {
219 if o.ID == "model" && o.CurrentValue != provider.OpenCodeModel(d.Model) {
220 d.modelChanged = true
221 }
222 }
223 return nil
224 }
225 if u.Kind == "usage_update" {
226 // The session's cost so far, kept between turns too.
227 d.observeCost(u.Cost)
228 return nil
229 }
230 if !d.active {
231 return nil
232 }
233 switch u.Kind {
234 case "agent_message_chunk":
235 var c struct{ Type, Text string }
236 if json.Unmarshal(u.Content, &c) != nil || c.Type != "text" || c.Text == "" {
237 return nil
238 }
239 return []provider.Event{{Kind: KindDelta, Payload: payload(pi.Delta{Text: c.Text})}}
240 case "tool_call", "tool_call_update":
241 return d.tool(u.toolUpdate, u.Kind == "tool_call")
242 }
243 if !known[u.Kind] {
244 d.unknown(methodUpdate + ":" + u.Kind)
245 }
246 return nil
247 case m.Method != "":
248 d.unknown(m.Method)
249 }
250 return nil
251}
252
253// tool follows one tool call through its updates: OpenCode announces it
254// before its arguments are known, so the call is Equipo's tool_call at
255// its first update that runs it, and its end is the tool_result.
256func (d *Decoder) tool(u toolUpdate, announced bool) []provider.Event {
257 if u.ToolCallID == "" {
258 return nil
259 }
260 if len(u.ToolCallID) > maxToolID {
261 d.unknown("tool id too long")
262 return nil
263 }
264 if d.calls == nil {
265 d.calls = map[string]*call{}
266 }
267 c := d.calls[u.ToolCallID]
268 if c == nil {
269 if len(d.calls) >= maxCalls {
270 d.unknown("tool calls over the bound")
271 return nil
272 }
273 c = &call{}
274 d.calls[u.ToolCallID] = c
275 }
276 if u.Name != "" {
277 c.tool = clipText(u.Name, 128)
278 } else if c.tool == "" && u.Title != "" {
279 c.tool = clipText(u.Title, 128)
280 }
281 if len(u.RawInput) > 0 && string(u.RawInput) != "{}" && string(u.RawInput) != "null" {
282 args := clipArgs(u.RawInput)
283 if d.retained-len(c.args)+len(args) > maxRetained {
284 // Over the total: the call keeps no arguments (its activity
285 // line has no subject).
286 args = nil
287 }
288 d.retained += len(args) - len(c.args)
289 c.args = args
290 }
291 var out []provider.Event
292 ends := u.Status == "completed" || u.Status == "failed"
293 if !c.sent && !announced && (u.Status == "in_progress" || ends) {
294 c.sent = true
295 out = append(out, provider.Event{Kind: KindToolCall, Payload: payload(pi.ToolCall{ID: u.ToolCallID, Tool: c.tool, Args: c.args})})
296 }
297 if ends && c.sent {
298 out = append(out, provider.Event{Kind: KindToolResult, Payload: payload(pi.ToolResult{ID: u.ToolCallID, Tool: c.tool, IsError: u.Status == "failed"})})
299 d.retained -= len(c.args)
300 delete(d.calls, u.ToolCallID)
301 }
302 return out
303}
304
305// acpUsage is a prompt answer's usage: input is the uncached part,
306// output excludes reasoning (OpenCode's visible output), reasoning is
307// thoughtTokens.
308type acpUsage struct {
309 Input *int64 `json:"inputTokens"`
310 Output *int64 `json:"outputTokens"`
311 Thought *int64 `json:"thoughtTokens"`
312 CacheRead *int64 `json:"cachedReadTokens"`
313 CacheWrite *int64 `json:"cachedWriteTokens"`
314}
315
316// usageOf reads the turn's usage and whether it can be counted. OpenCode
317// gives zero for any figure a provider did not report, so a turn whose
318// input is zero (no request reads no prompt) is not counted: its spend is
319// unknown, never zero. Output is the visible output and the reasoning
320// together, as Go bills reasoning as output.
321func (d *Decoder) usageOf(raw json.RawMessage) pi.Usage {
322 out := pi.Usage{Model: d.Model}
323 var u acpUsage
324 if len(raw) == 0 || json.Unmarshal(raw, &u) != nil || u.Input == nil || u.Output == nil {
325 return out
326 }
327 figure := func(v *int64) int64 {
328 if v == nil {
329 return 0
330 }
331 return *v
332 }
333 in, visible, thought, read, write := *u.Input, *u.Output, figure(u.Thought), figure(u.CacheRead), figure(u.CacheWrite)
334 if in < 0 || visible < 0 || thought < 0 || read < 0 || write < 0 || thought > math.MaxInt64-visible {
335 return out
336 }
337 if in > math.MaxInt64-read || in+read > math.MaxInt64-write || in+read+write == 0 {
338 return out
339 }
340 out.Input, out.Output, out.Reasoning, out.CacheRead, out.CacheWrite, out.Valid = in, visible+thought, thought, read, write, true
341 if d.costBad {
342 return pi.Usage{Model: d.Model}
343 }
344 if added := d.SessionCost() - d.turnBase; added > 0 {
345 out.Cost, out.Priced = added, true
346 }
347 return out
348}
349
350// Failure classes of a turn that failed (pi's): OpenCode says a refused
351// key as an authentication error, and a provider's rate limit or a Go
352// plan's limit by its error name.
353func failure(e *RPCError) string {
354 switch {
355 case e == nil:
356 return pi.FailProvider
357 case e.Code == -32000 || strings.HasPrefix(e.Message, "Authentication required"):
358 return pi.FailAuth
359 case e.Data.ErrorName == "provider.rate-limit" || e.Data.ErrorName == "provider.budget-limit" || e.Data.ErrorName == "provider.model-budget-limit":
360 return pi.FailQuota
361 case e.Data.ErrorName == "provider.model-not-found" || strings.Contains(e.Message, "model_not_found"):
362 // Not probed on the real binary (no real provider): the error name
363 // is OpenCode's provider error pattern for a missing model.
364 return pi.FailModel
365 }
366 return pi.FailProvider
367}
368
369// end is the prompt's answer: the turn's usage (always, so a turn
370// without a figure counts as one that cannot be priced), then its end.
371func (d *Decoder) end(m Message) []provider.Event {
372 var r struct {
373 StopReason string `json:"stopReason"`
374 Usage json.RawMessage `json:"usage"`
375 }
376 done := pi.Done{Status: pi.StatusFailed, Failure: pi.FailProvider}
377 if d.modelChanged {
378 // Another model may have answered: never a completed turn.
379 done.Error = "the session's model changed"
380 } else if m.Error != nil {
381 done.Failure, done.Error = failure(m.Error), clipText(m.Error.Message, 512)
382 } else if json.Unmarshal(m.Result, &r) == nil {
383 switch r.StopReason {
384 case "end_turn":
385 done = pi.Done{Status: pi.StatusCompleted}
386 case "cancelled":
387 done = pi.Done{Status: pi.StatusInterrupted}
388 default:
389 done.Error = "the turn ended: " + clipText(r.StopReason, 64)
390 }
391 }
392 return []provider.Event{
393 {Kind: KindUsage, Payload: payload(d.usageOf(r.Usage))},
394 {Kind: KindDone, Payload: payload(done)},
395 }
396}
397
398// Family is the model family of an OpenCode Go model id (spec §3,
399// "Families"): its name before the version, glm-5.3 is glm,
400// kimi-k3.1-pro is kimi, hy4 is hunyuan.
401func Family(model string) string {
402 name := strings.ToLower(model)
403 if _, after, ok := strings.Cut(name, "/"); ok {
404 name = after
405 }
406 for _, f := range []struct{ prefix, family string }{
407 {"glm", "glm"}, {"kimi", "kimi"}, {"deepseek", "deepseek"}, {"qwen", "qwen"}, {"minimax", "minimax"},
408 {"mimo", "mimo"}, {"longcat", "longcat"}, {"hy", "hunyuan"}, {"step", "step"},
409 } {
410 if strings.HasPrefix(name, f.prefix) {
411 return f.family
412 }
413 }
414 family, _, _ := strings.Cut(name, "-")
415 return strings.TrimRight(family, "0123456789.")
416}
417
418// Tally is an attempt's usage: the turn's figure from the prompt's
419// answer, complete once that answer came (spec §2.3; probe OC-P4: the
420// figure is the turn's own, summed over its requests, not the session's
421// running total).
422type Tally = pi.Tally
423