Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(opencode): include separate reasoning in output usage (#8431)
importcppc4c8bab56c38
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex dbe52f282e..bb788786a0 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -294,7 +294,7 @@ type Result struct {// Config configures a Backend instance.type Config struct {ExecutablePath string // path to CLI binary (claude, codebuddy, codex, copilot, opencode, codearts, openclaw, hermes, pi, cursor, kimi, reasonix, dsh, kiro-cli, agy, qodercli, qoderclicn, traecli, grok, qwen, qwenpaw, mcode, dim, zeroclaw)- CLIVersion string // detected version paired with ExecutablePath; observation only, never used to choose behavior+ CLIVersion string // detected version paired with ExecutablePath; vendor-specific usage semantics also require BuiltinRuntimeEnv map[string]string // extra environment variablesLogger *slog.LoggerTaskID stringdiff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.goindex 10483db3e8..70279c62f3 100644--- a/server/pkg/agent/opencode.go+++ b/server/pkg/agent/opencode.go@@ -46,6 +46,24 @@ type opencodeBackend struct {cfg Config}+// opencodeSeparatesReasoning recognizes the released OpenCode 1.x wire contract.+// v1.3.15 included reasoning in output; v1.3.16 separated it in upstream #21047:+// https://github.com/anomalyco/opencode/pull/21047+// Use the daemon's already-resolved version, never an extra per-run probe.+// Unknown/dev versions and custom commands keep the existing output count:+// their version string does not establish which usage convention they speak.+func opencodeSeparatesReasoning(cfg Config) bool {+ if !cfg.BuiltinRuntime {+ return false+ }+ raw := strings.TrimSpace(cfg.CLIVersion)+ if raw == "" || versionRe.FindString(raw) != raw {+ return false+ }+ version, err := parseSemver(raw)+ return err == nil && version.Major == 1 && !version.lessThan(semver{Major: 1, Minor: 3, Patch: 16})+}+func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {execPath := b.cfg.ExecutablePathif execPath == "" {@@ -345,6 +363,7 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventResvar output strings.Buildervar sessionID stringvar usage TokenUsage+ separateReasoning := opencodeSeparatesReasoning(b.cfg)finalStatus := "completed"var finalError string@@ -436,6 +455,9 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventResif t := event.Part.Tokens; t != nil {usage.InputTokens += t.Inputusage.OutputTokens += t.Output+ if separateReasoning && t.Reasoning > 0 {+ usage.OutputTokens += t.Reasoning+ }if t.Cache != nil {usage.CacheReadTokens += t.Cache.Readusage.CacheWriteTokens += t.Cache.Write@@ -503,10 +525,9 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes// the protocol reports counts. Only an across-the-board zero means no model// call happened.//-// The reasoning and total counters are read as evidence only, deliberately not-// folded into TokenUsage: total is derived (adding it would double-count) and-// TokenUsage has no reasoning bucket, so recording either here would change-// billing figures rather than fix this bug.+// This predicate only checks for evidence of a provider round-trip.+// processEvents separately normalizes reasoning into output for releases whose+// output excludes it; the aggregate total is never added to the usage buckets.func stepReportedUsage(part *opencodeEventPart) bool {if part.Cost > 0 {return true@@ -704,10 +725,9 @@ type opencodePartMetadata struct {ProviderExecuted bool `json:"providerExecuted,omitempty"`}-// opencodeTokens represents token usage in a step_finish event. Reasoning and-// Total are separate counters in the protocol, not components of Input/Output,-// so a step can report either while both of those are zero; they are parsed so-// stepReportedUsage can see them.+// opencodeTokens represents token usage in a step_finish event. OpenCode 1.x+// since v1.3.16 separates Reasoning from Output; older releases include it.+// Total is an aggregate, and both fields also provide step-liveness evidence.type opencodeTokens struct {Input int64 `json:"input"`Output int64 `json:"output"`diff --git a/server/pkg/agent/opencode_stdin_helper_test.go b/server/pkg/agent/opencode_stdin_helper_test.goindex 5960f59abf..aecfbf08a3 100644--- a/server/pkg/agent/opencode_stdin_helper_test.go+++ b/server/pkg/agent/opencode_stdin_helper_test.go@@ -12,9 +12,10 @@ import (// (the Chocolatey shim in #6538 is a real PE binary, not a .cmd wrapper), so// the backend's argv reaches CreateProcess unmediated.const (- opencodeStdinHelperEnv = "MULTICA_OPENCODE_STDIN_HELPER"- opencodeStdinHelperArgvFile = "MULTICA_OPENCODE_STDIN_HELPER_ARGV_FILE"- opencodeStdinHelperInFile = "MULTICA_OPENCODE_STDIN_HELPER_STDIN_FILE"+ opencodeStdinHelperEnv = "MULTICA_OPENCODE_STDIN_HELPER"+ opencodeStdinHelperArgvFile = "MULTICA_OPENCODE_STDIN_HELPER_ARGV_FILE"+ opencodeStdinHelperInFile = "MULTICA_OPENCODE_STDIN_HELPER_STDIN_FILE"+ opencodeStdinHelperUsageOnly = "MULTICA_OPENCODE_STDIN_HELPER_USAGE_ONLY")const (@@ -69,6 +70,10 @@ func runFakeOpencodeStdinHelper() {}fmt.Println(`{"type":"step_start","timestamp":1,"sessionID":"ses_fake","part":{"type":"step-start"}}`)+ if os.Getenv(opencodeStdinHelperUsageOnly) == "1" {+ fmt.Println(`{"type":"step_finish","timestamp":2,"sessionID":"ses_fake","part":{"type":"step-finish","reason":"stop","tokens":{"input":0,"output":0,"reasoning":20}}}`)+ return+ }fmt.Println(`{"type":"text","timestamp":2,"sessionID":"ses_fake","part":{"type":"text","text":"ok"}}`)fmt.Println(`{"type":"step_finish","timestamp":3,"sessionID":"ses_fake","part":{"type":"step-finish"}}`)}diff --git a/server/pkg/agent/opencode_usage_test.go b/server/pkg/agent/opencode_usage_test.gonew file mode 100644index 0000000000..715cb9444e--- /dev/null+++ b/server/pkg/agent/opencode_usage_test.go@@ -0,0 +1,123 @@+package agent++import (+ "context"+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestOpencodeProcessEventsTokenUsage(t *testing.T) {+ t.Parallel()++ // OpenCode getUsage keeps reasoning inside output through v1.3.15 and+ // emits it separately from v1.3.16. The mixed case replays v1.18.31 usage.+ // https://github.com/anomalyco/opencode/pull/21047+ // https://github.com/anomalyco/opencode/blob/v1.18.31/packages/opencode/src/session/session.ts#L338+ const mixed = `{"total":1050,"input":200,"output":30,"reasoning":20,"cache":{"read":600,"write":200}}`+ const legacy = `{"total":14674,"input":14585,"output":89,"reasoning":82,"cache":{"read":0,"write":0}}`+ for _, tc := range []struct {+ name string+ version string+ custom bool+ tokens []string+ want TokenUsage+ }{+ {"first_separate_release", "1.3.16", false, []string{mixed}, TokenUsage{InputTokens: 200, OutputTokens: 50, CacheReadTokens: 600, CacheWriteTokens: 200}},+ {"current_release", "1.18.31", false, []string{mixed}, TokenUsage{InputTokens: 200, OutputTokens: 50, CacheReadTokens: 600, CacheWriteTokens: 200}},+ {"v_prefix_and_whitespace", " v1.17.7\n", false, []string{mixed}, TokenUsage{InputTokens: 200, OutputTokens: 50, CacheReadTokens: 600, CacheWriteTokens: 200}},+ {"multiple_steps", "1.18.31", false, []string{mixed, mixed}, TokenUsage{InputTokens: 400, OutputTokens: 100, CacheReadTokens: 1200, CacheWriteTokens: 400}},+ {"missing_total", "1.18.31", false, []string{`{"input":200,"output":30,"reasoning":20,"cache":{"read":600,"write":200}}`}, TokenUsage{InputTokens: 200, OutputTokens: 50, CacheReadTokens: 600, CacheWriteTokens: 200}},+ {"total_does_not_choose_output_convention", "1.18.31", false, []string{`{"total":1030,"input":200,"output":30,"reasoning":20,"cache":{"read":600,"write":200}}`}, TokenUsage{InputTokens: 200, OutputTokens: 50, CacheReadTokens: 600, CacheWriteTokens: 200}},+ {"all_output_is_reasoning", "1.18.31", false, []string{`{"input":0,"output":0,"reasoning":20}`}, TokenUsage{OutputTokens: 20}},+ {"cache_only", "1.18.31", false, []string{`{"input":0,"output":0,"cache":{"read":600,"write":200}}`}, TokenUsage{CacheReadTokens: 600, CacheWriteTokens: 200}},+ {"no_reasoning_breakdown", "1.18.31", false, []string{`{"input":200,"output":50}`}, TokenUsage{InputTokens: 200, OutputTokens: 50}},+ {"negative_reasoning_does_not_reduce_output", "1.18.31", false, []string{`{"input":200,"output":50,"reasoning":-20}`}, TokenUsage{InputTokens: 200, OutputTokens: 50}},+ {"last_inclusive_release", "1.3.15", false, []string{legacy}, TokenUsage{InputTokens: 14585, OutputTokens: 89}},+ {"legacy_without_total", "1.3.15", false, []string{`{"input":200,"output":50,"reasoning":20}`}, TokenUsage{InputTokens: 200, OutputTokens: 50}},+ {"missing_version", "", false, []string{legacy}, TokenUsage{InputTokens: 14585, OutputTokens: 89}},+ {"unrecognized_version", "unknown", false, []string{legacy}, TokenUsage{InputTokens: 14585, OutputTokens: 89}},+ {"prerelease_is_not_release_evidence", "1.18.31-beta.1", false, []string{legacy}, TokenUsage{InputTokens: 14585, OutputTokens: 89}},+ {"development_build_is_not_release_evidence", "v1.3.15-7-gabcdef", false, []string{legacy}, TokenUsage{InputTokens: 14585, OutputTokens: 89}},+ {"banner_is_not_release_evidence", "wrapper 1.18.31", false, []string{legacy}, TokenUsage{InputTokens: 14585, OutputTokens: 89}},+ {"unverified_major_version", "2.0.0", false, []string{legacy}, TokenUsage{InputTokens: 14585, OutputTokens: 89}},+ {"custom_command_version_is_not_opencode_version", "1.18.31", true, []string{legacy}, TokenUsage{InputTokens: 14585, OutputTokens: 89}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ b := &opencodeBackend{cfg: Config{Logger: slog.Default(), CLIVersion: tc.version, BuiltinRuntime: !tc.custom}}+ var stream strings.Builder+ for i, tokens := range tc.tokens {+ stream.WriteString(`{"type":"step_start","sessionID":"ses_usage","part":{"type":"step-start"}}` + "\n")+ reason := "tool-calls"+ if i == len(tc.tokens)-1 {+ reason = "stop"+ }+ fmt.Fprintf(&stream, "{\"type\":\"step_finish\",\"sessionID\":\"ses_usage\",\"part\":{\"type\":\"step-finish\",\"reason\":%q,\"tokens\":%s}}\n", reason, tokens)+ }+ ch := make(chan Message, 32)+ result := b.processEvents(strings.NewReader(stream.String()), ch)+ close(ch)+ if result.status != "completed" || result.errMsg != "" {+ t.Fatalf("status=%q error=%q", result.status, result.errMsg)+ }+ if result.usage != tc.want {+ t.Fatalf("usage=%+v want=%+v", result.usage, tc.want)+ }+ })+ }+}++func TestOpencodeExecuteRetainsReasoningOnlyUsage(t *testing.T) {+ t.Parallel()+ // A reasoning-only stream used to pass the step-liveness guard but lose+ // its entire usage entry because all four normalized counters were zero.+ self, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ dir := t.TempDir()+ backend, err := New("opencode", Config{+ ExecutablePath: self,+ CLIVersion: "1.18.31",+ BuiltinRuntime: true,+ Logger: slog.Default(),+ Env: map[string]string{+ opencodeStdinHelperEnv: "1",+ opencodeStdinHelperArgvFile: filepath.Join(dir, "argv.txt"),+ opencodeStdinHelperInFile: filepath.Join(dir, "stdin.txt"),+ opencodeStdinHelperUsageOnly: "1",+ },+ })+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "test prompt", ExecOptions{Cwd: t.TempDir(), Model: "test/model"})+ if err != nil {+ t.Fatal(err)+ }+ drained := make(chan struct{})+ go func() {+ for range session.Messages {+ }+ close(drained)+ }()+ select {+ case result := <-session.Result:+ if result.Status != "completed" || result.Error != "" {+ t.Fatalf("status=%q error=%q", result.Status, result.Error)+ }+ if got, want := result.Usage["test/model"], (TokenUsage{OutputTokens: 20}); got != want {+ t.Fatalf("reported usage=%+v want=%+v", got, want)+ }+ case <-ctx.Done():+ t.Fatal(ctx.Err())+ }+ <-drained+}