Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): report Copilot token usage from --usage-output-file (#10519)
xiaoke12345678a583a15091b1
diff --git a/server/pkg/agent/copilot.go b/server/pkg/agent/copilot.goindex 8c4957fa5c..261f15350d 100644--- a/server/pkg/agent/copilot.go+++ b/server/pkg/agent/copilot.go@@ -6,7 +6,9 @@ import ("fmt""io""log/slog"+ "os""os/exec"+ "path/filepath""strings""sync""time"@@ -47,17 +49,19 @@ type copilotEventState struct {// consumed the whole stdin prompt and ran to completion.sawResult bool- // Token usage arrives on up to three different events, so each source is- // accumulated separately and resolved once at the end by resolveUsage.+ // Token usage arrives from up to four sources, so each is accumulated+ // separately and resolved once at the end by resolveUsage.//- // session.shutdown per-model session totals, full breakdown- // assistant.usage per model call, full breakdown- // assistant.message outputTokens only — legacy, older CLIs+ // session.shutdown per-model session totals, full breakdown+ // --usage-output-file the same session totals, written on exit+ // assistant.usage per model call, full breakdown+ // assistant.message outputTokens only — legacy, older CLIs//- // They must never be summed together: all three describe the same tokens.+ // They must never be summed together: all four describe the same tokens.callUsage map[string]TokenUsagemsgUsage map[string]TokenUsageshutdownUsage map[string]TokenUsage+ fileUsage map[string]TokenUsage// resumed marks a run that continued an existing Copilot session, which is// what disqualifies the session.shutdown totals — see resolveUsage.resumed bool@@ -74,6 +78,10 @@ type copilotEventState struct {// tokens, and reporting that on a follow-up would bill the same tokens once per// turn. Under-reporting beats double-billing, so a resumed run falls through.//+// The --usage-output-file summary is the source modern CLIs actually deliver,+// since they filter session.shutdown out of the JSON stream. It holds the same+// session totals, so it follows the same rule and is skipped on resume.+//// assistant.usage is per model call, so it measures exactly this run either// way. assistant.message is last: it only ever carries output tokens, so// letting it win over a source with the full breakdown would silently drop the@@ -82,6 +90,9 @@ func (st *copilotEventState) resolveUsage() map[string]TokenUsage {if !st.resumed && hasTokens(st.shutdownUsage) {return st.shutdownUsage}+ if !st.resumed && hasTokens(st.fileUsage) {+ return st.fileUsage+ }if hasTokens(st.callUsage) {return st.callUsage}@@ -151,10 +162,30 @@ func newCopilotEventState(seedModel string, resumed bool) *copilotEventState {callUsage: make(map[string]TokenUsage),msgUsage: make(map[string]TokenUsage),shutdownUsage: make(map[string]TokenUsage),+ fileUsage: make(map[string]TokenUsage),resumed: resumed,}}+// applyUsageFile folds the JSON summary Copilot writes to --usage-output-file+// into fileUsage. Only modelMetrics is read: agentMetrics breaks the same+// totals down by sub-agent, so adding it would count every token twice. A+// missing or malformed file leaves fileUsage empty, and the run stays+// unreported rather than recording zero.+func (st *copilotEventState) applyUsageFile(raw []byte) error {+ var summary copilotShutdownData+ if err := json.Unmarshal(raw, &summary); err != nil {+ return err+ }+ for model, m := range summary.ModelMetrics {+ if model == "" {+ model = st.activeModel+ }+ addUsage(st.fileUsage, model, m.Usage.InputTokens, m.Usage.OutputTokens, m.Usage.CacheReadTokens, m.Usage.CacheWriteTokens)+ }+ return nil+}+// handleCopilotEvent processes a single parsed copilotEvent, updates state,// and returns zero or more Messages to emit. Extracted so tests can call the// exact same logic without duplicating the switch body.@@ -362,6 +393,24 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOp// The task prompt is delivered on stdin, never argv (see buildCopilotArgs).args := buildCopilotArgs(opts, b.cfg.Logger)++ // Modern CLIs keep token counts out of the JSON stream and only write them+ // to --usage-output-file on exit, so give each run its own file to read.+ // Without it the run still works; it just reports no usage, as before.+ usageFile := ""+ if copilotUsageFileSupported(b.cfg) {+ if dir, err := os.MkdirTemp("", "multica-copilot-usage-"); err != nil {+ b.cfg.Logger.Warn("copilot usage file unavailable", "error", err)+ } else {+ usageFile = filepath.Join(dir, "usage.json")+ args = append(args, "--usage-output-file", usageFile)+ }+ }+ removeUsageFile := func() {+ if usageFile != "" {+ _ = os.RemoveAll(filepath.Dir(usageFile))+ }+ }cmd, _, _ := b.cfg.commandAt(execName).execVia(runCtx, chooseCopilotInvocation, lookedUp, args, b.cfg.Logger)hideAgentWindow(cmd)b.cfg.logAgentCommandWithPrompt(cmd, newAgentCommandLogArgs(args), len(prompt))@@ -374,11 +423,13 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOpstdout, err := cmd.StdoutPipe()if err != nil {cancel()+ removeUsageFile()return nil, fmt.Errorf("copilot stdout pipe: %w", err)}stdin, err := cmd.StdinPipe()if err != nil {cancel()+ removeUsageFile()return nil, fmt.Errorf("copilot stdin pipe: %w", err)}var closeStdinOnce sync.Once@@ -389,6 +440,7 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOpif err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {closeStdin()cancel()+ removeUsageFile()return nil, fmt.Errorf("start copilot: %w", err)}@@ -412,6 +464,7 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOpdefer cancel()defer close(msgCh)defer close(resCh)+ defer removeUsageFile()startTime := time.Now()seedModel := opts.Model@@ -451,6 +504,18 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOpexitErr := cmd.Wait()releaseProcessGroup(cmd)+ if usageFile != "" {+ // Written on exit, so it is complete once Wait returns. A process+ // that was killed or crashed may leave none; that run stays unreported.+ if raw, err := os.ReadFile(usageFile); err == nil {+ if err := st.applyUsageFile(raw); err != nil {+ b.cfg.Logger.Warn("copilot usage file unreadable", "error", err)+ }+ } else if !os.IsNotExist(err) {+ b.cfg.Logger.Warn("copilot usage file unreadable", "error", err)+ }+ removeUsageFile()+ }duration := time.Since(startTime)// Wait closes the process pipes, so a prompt write still blocked when@@ -489,14 +554,24 @@ func (b *copilotBackend) Execute(ctx context.Context, prompt string, opts ExecOpusage := st.resolveUsage()// A run that produced output but no tokens is a silent billing hole:// the daemon skips reporting empty usage, so nothing surfaces anywhere- // downstream. This is the current state on Copilot CLI 1.0.77 (see- // copilotUsageData), and it went unnoticed until a user reported it —- // log it so the next regression is visible from the daemon log alone.+ // downstream. The JSON stream has carried no usable tokens since Copilot+ // CLI 1.0.77 (see copilotUsageData), which went unnoticed until a user+ // reported it — log it so the next regression is visible from the+ // daemon log alone.if len(usage) == 0 && st.finalStatus == "completed" {+ hint := "Copilot CLI filters assistant.usage and session.shutdown out of --output-format json; token counts come only from --usage-output-file"+ switch {+ case usageFile == "":+ hint += ", which is passed to the built-in Copilot CLI " + copilotUsageFileMinVersion + " or newer"+ case st.resumed:+ hint += ", which holds session totals and is not reported on a resumed session"+ default:+ hint += ", which this run did not write"+ }b.cfg.Logger.Warn("copilot reported no token usage","session", st.sessionID,"model", st.activeModel,- "hint", "Copilot CLI filters assistant.usage and session.shutdown out of --output-format json; only assistant.message.outputTokens remains, and newer CLIs no longer populate it")+ "hint", hint)}resCh <- Result{@@ -663,16 +738,36 @@ type copilotCodeChanges struct {// copilotBlockedArgs are flags hardcoded by the daemon that must not be// overridden by user-configured custom_args.var copilotBlockedArgs = map[string]blockedArgMode{- "-p": blockedWithValue,- "--output-format": blockedWithValue,- "--allow-all": blockedStandalone, // tools + paths + URLs- "--allow-all-tools": blockedStandalone,- "--allow-all-paths": blockedStandalone,- "--allow-all-urls": blockedStandalone,- "--yolo": blockedStandalone,- "--no-ask-user": blockedStandalone,- "--resume": blockedWithValue, // managed via ExecOptions.ResumeSessionID- "--acp": blockedStandalone, // prevent switching to ACP mode+ "-p": blockedWithValue,+ "--output-format": blockedWithValue,+ "--allow-all": blockedStandalone, // tools + paths + URLs+ "--allow-all-tools": blockedStandalone,+ "--allow-all-paths": blockedStandalone,+ "--allow-all-urls": blockedStandalone,+ "--yolo": blockedStandalone,+ "--no-ask-user": blockedStandalone,+ "--resume": blockedWithValue, // managed via ExecOptions.ResumeSessionID+ "--acp": blockedStandalone, // prevent switching to ACP mode+ "--usage-output-file": blockedWithValue, // the daemon reads its own per-run file+}++// copilotUsageFileMinVersion is the oldest Copilot CLI whose changelog+// documents --usage-output-file (1.0.81 extended it with per-agent metrics).+// An older CLI may reject the unknown flag and fail every run, so it keeps+// today's argv.+const copilotUsageFileMinVersion = "1.0.81"++// copilotUsageFileSupported reports whether this run may pass+// --usage-output-file: only to GitHub's own Copilot binary, at a detected+// version known to accept the flag. A custom runtime profile that speaks the+// Copilot protocol is a different program and keeps the standard argv.+func copilotUsageFileSupported(cfg Config) bool {+ if !cfg.BuiltinRuntime {+ return false+ }+ version, err := parseSemver(cfg.CLIVersion)+ floor, _ := parseSemver(copilotUsageFileMinVersion)+ return err == nil && !version.lessThan(floor)}// buildCopilotArgs assembles the argv for a one-shot copilot invocation.diff --git a/server/pkg/agent/copilot_usage_file_test.go b/server/pkg/agent/copilot_usage_file_test.gonew file mode 100644index 0000000000..88addcdbc2--- /dev/null+++ b/server/pkg/agent/copilot_usage_file_test.go@@ -0,0 +1,129 @@+package agent++import (+ "log/slog"+ "slices"+ "testing"+)++// fixtureUsageFile is the --usage-output-file summary from #10501 (Copilot CLI+// 1.0.109). inputTokens already includes the cache tiers (17820 = 3 uncached ++// 17817 cache write), and agentMetrics repeats the same totals per sub-agent.+const fixtureUsageFile = `{+ "totalPremiumRequestCost": 1,+ "totalNanoAiu": 4459850000,+ "modelMetrics": {+ "gpt-6.1-sol": {+ "requests": { "count": 1, "cost": 1 },+ "usage": { "inputTokens": 17820, "outputTokens": 5, "cacheReadTokens": 0, "cacheWriteTokens": 17817, "reasoningTokens": 2 }+ }+ },+ "agentMetrics": {+ "main": {+ "modelMetrics": {+ "gpt-6.1-sol": {+ "requests": { "count": 1, "cost": 1 },+ "usage": { "inputTokens": 17820, "outputTokens": 5, "cacheReadTokens": 0, "cacheWriteTokens": 17817, "reasoningTokens": 2 }+ }+ }+ }+ }+}`++func TestCopilotUsageFileReportsModelMetricsOnce(t *testing.T) {+ t.Parallel()+ // The modern stream: no assistant.usage and no session.shutdown reach+ // --output-format json, so the usage file is the only source of tokens.+ _, st := runCopilotEventLoop(t, []string{fixtureSessionStart, fixtureTurnStart, fixtureResult}, "copilot", false)++ if err := st.applyUsageFile([]byte(fixtureUsageFile)); err != nil {+ t.Fatalf("applyUsageFile: %v", err)+ }++ usage := st.resolveUsage()+ if len(usage) != 1 {+ t.Fatalf("expected one model, got %#v", usage)+ }+ // Cache write is taken out of input, reasoning stays inside output, and+ // agentMetrics is not added on top of modelMetrics.+ want := TokenUsage{InputTokens: 3, OutputTokens: 5, CacheWriteTokens: 17817}+ if got := usage["gpt-6.1-sol"]; got != want {+ t.Fatalf("usage = %#v, want %#v", got, want)+ }+}++func TestCopilotUsageFileSkippedOnResume(t *testing.T) {+ t.Parallel()+ // Like session.shutdown, the file holds session totals; on a resumed+ // session that would bill every earlier turn again.+ _, st := runCopilotEventLoop(t, []string{fixtureSessionStart, fixtureTurnStart, fixtureResult}, "copilot", true)++ if err := st.applyUsageFile([]byte(fixtureUsageFile)); err != nil {+ t.Fatalf("applyUsageFile: %v", err)+ }+ if usage := st.resolveUsage(); len(usage) != 0 {+ t.Fatalf("expected no usage on a resumed run, got %#v", usage)+ }+}++func TestCopilotUsageFileDoesNotDisplaceStreamTotals(t *testing.T) {+ t.Parallel()+ // An older CLI that still streams session.shutdown keeps reporting exactly+ // what it does today; the file never adds to it.+ _, st := runCopilotEventLoop(t, []string{fixtureSessionStart, fixtureTurnStart, fixtureShutdown, fixtureResult}, "copilot", false)++ if err := st.applyUsageFile([]byte(fixtureUsageFile)); err != nil {+ t.Fatalf("applyUsageFile: %v", err)+ }+ usage := st.resolveUsage()+ if _, ok := usage["gpt-6.1-sol"]; ok || usage["claude-sonnet-4.5"].OutputTokens != 900 {+ t.Fatalf("expected the session.shutdown totals alone, got %#v", usage)+ }+}++func TestCopilotUsageFileMalformedLeavesRunUnreported(t *testing.T) {+ t.Parallel()++ for _, raw := range []string{"", "{", `{"modelMetrics":{"gpt-6.1-sol":{"usage":{}}}}`} {+ _, st := runCopilotEventLoop(t, []string{fixtureSessionStart, fixtureTurnStart, fixtureResult}, "copilot", false)+ _ = st.applyUsageFile([]byte(raw))+ if usage := st.resolveUsage(); len(usage) != 0 {+ t.Fatalf("usage file %q: expected unreported, got %#v", raw, usage)+ }+ }+}++func TestCopilotUsageFileSupported(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ cfg Config+ want bool+ }{+ {"built-in at the floor", Config{BuiltinRuntime: true, CLIVersion: "1.0.81"}, true},+ {"built-in newer", Config{BuiltinRuntime: true, CLIVersion: "GitHub Copilot CLI 1.0.109."}, true},+ {"built-in older", Config{BuiltinRuntime: true, CLIVersion: "1.0.80"}, false},+ {"built-in, version unknown", Config{BuiltinRuntime: true}, false},+ {"custom runtime profile", Config{BuiltinRuntime: false, CLIVersion: "1.0.109"}, false},+ }+ for _, tc := range cases {+ if got := copilotUsageFileSupported(tc.cfg); got != tc.want {+ t.Errorf("%s: copilotUsageFileSupported = %v, want %v", tc.name, got, tc.want)+ }+ }+}++func TestBuildCopilotArgsBlocksCustomUsageFile(t *testing.T) {+ t.Parallel()+ // The daemon passes its own per-run file; a user-supplied one would either+ // collide with it or redirect the summary somewhere the daemon never reads.+ args := buildCopilotArgs(ExecOptions{CustomArgs: []string{"--usage-output-file", "/tmp/mine.json", "--model-hint"}}, slog.Default())++ if slices.Contains(args, "--usage-output-file") || slices.Contains(args, "/tmp/mine.json") {+ t.Fatalf("expected --usage-output-file to be filtered from custom args, got %v", args)+ }+ if !slices.Contains(args, "--model-hint") {+ t.Fatalf("expected unrelated custom args to survive, got %v", args)+ }+}diff --git a/server/pkg/agent/copilot_usage_file_unix_test.go b/server/pkg/agent/copilot_usage_file_unix_test.gonew file mode 100644index 0000000000..4da64a5f36--- /dev/null+++ b/server/pkg/agent/copilot_usage_file_unix_test.go@@ -0,0 +1,128 @@+//go:build unix++package agent++import (+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// copilotUsageFileScript is a fake Copilot CLI that records its argv and, like+// the real one, writes the usage summary to --usage-output-file on exit.+func copilotUsageFileScript(argvPath string) string {+ return fmt.Sprintf(`#!/bin/sh+: > %[1]q+out=""+prev=""+for a in "$@"; do+ printf '%%s\n' "$a" >> %[1]q+ if [ "$prev" = "--usage-output-file" ]; then out="$a"; fi+ prev="$a"+done+cat > /dev/null+if [ -n "$out" ]; then+ cat > "$out" <<'JSON'+%[2]s+JSON+fi+`, argvPath, fixtureUsageFile) + copilotStreamTail+}++func runCopilotFakeWithConfig(t *testing.T, script string, cfg Config, opts ExecOptions) Result {+ t.Helper()++ fakePath := filepath.Join(t.TempDir(), "copilot")+ writeTestExecutable(t, fakePath, []byte(script))+ cfg.ExecutablePath = fakePath+ cfg.Logger = slog.Default()++ backend, err := New("copilot", cfg)+ if err != nil {+ t.Fatalf("New(copilot): %v", err)+ }+ opts.Timeout = 30 * time.Second+ session, err := backend.Execute(t.Context(), "Reply with just OK", opts)+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ select {+ case result := <-session.Result:+ return result+ case <-time.After(30 * time.Second):+ t.Fatal("copilot run never produced a result")+ return Result{}+ }+}++func readArgv(t *testing.T, path string) []string {+ t.Helper()+ raw, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read recorded argv: %v", err)+ }+ return strings.Split(strings.TrimSpace(string(raw)), "\n")+}++// TestCopilotExecuteReportsUsageFromUsageFile is the regression for #10501:+// a completed run on a modern CLI reported no tokens, because the JSON stream+// carries none and the --usage-output-file summary was never requested.+func TestCopilotExecuteReportsUsageFromUsageFile(t *testing.T) {+ t.Parallel()++ argvPath := filepath.Join(t.TempDir(), "argv.txt")+ result := runCopilotFakeWithConfig(t, copilotUsageFileScript(argvPath),+ Config{BuiltinRuntime: true, CLIVersion: "1.0.109"}, ExecOptions{})++ if result.Status != "completed" {+ t.Fatalf("status = %q (%s), want completed", result.Status, result.Error)+ }+ want := TokenUsage{InputTokens: 3, OutputTokens: 5, CacheWriteTokens: 17817}+ if got := result.Usage["gpt-6.1-sol"]; got != want {+ t.Fatalf("usage = %#v, want %#v", result.Usage, want)+ }++ argv := readArgv(t, argvPath)+ var usageFile string+ for i, a := range argv {+ if a == "--usage-output-file" && i+1 < len(argv) {+ usageFile = argv[i+1]+ }+ }+ if usageFile == "" {+ t.Fatalf("expected --usage-output-file in argv, got %v", argv)+ }+ // The per-run file and its directory are gone once the run reports.+ if _, err := os.Stat(filepath.Dir(usageFile)); !os.IsNotExist(err) {+ t.Fatalf("expected the usage file directory to be removed, stat err = %v", err)+ }+}++func TestCopilotExecuteKeepsArgvForOlderCLI(t *testing.T) {+ t.Parallel()+ // A CLI that may not know the flag gets today's argv, and the run simply+ // stays unreported as before rather than failing on an unknown option.+ argvPath := filepath.Join(t.TempDir(), "argv.txt")+ result := runCopilotFakeWithConfig(t, copilotUsageFileScript(argvPath),+ Config{BuiltinRuntime: true, CLIVersion: "1.0.77"}, ExecOptions{})++ if result.Status != "completed" {+ t.Fatalf("status = %q (%s), want completed", result.Status, result.Error)+ }+ for _, a := range readArgv(t, argvPath) {+ if a == "--usage-output-file" {+ t.Fatalf("expected no --usage-output-file for CLI 1.0.77")+ }+ }+ if len(result.Usage) != 0 {+ t.Fatalf("expected no usage, got %#v", result.Usage)+ }+}