Skip to content

acp: usage_update cost leaves out subagent sessions #65616

Description

@BambinoSK

Description

Over ACP, the cost in usage_update is only the root session's own cost. Each subagent session records its spend on its own session and nothing adds those up, so ACP clients under-report the session's cost whenever subagents run. The TUI footer and sidebar already add up the session and its subagents (packages/client/src/solid/data.ts), so ACP and the TUI show different totals for the same session.

Plugins

No response

OpenCode version

2.3.2 (also on dev at 8ba4445)

Steps to reproduce

  1. Connect an ACP client with opencode acp.
  2. Send a prompt that starts a subagent.
  3. Compare the usage_update cost with the TUI's cost for the same session.

Screenshot

No response

Operating System

Windows 11

Terminal

No response

Activity

  1. added
    area/ide-acp
    type/bug
    version/v2
    on Nov 22, 2026
  2. opencodejr commented on Nov 22, 2026

    @opencodejr
    Contributor

    Seen with a simulated model or a mock server, not a real provider; a maintainer should confirm.

    Thanks for the clear report. I reproduced this on 2.3.2, and it still happens on the latest dev (8ba4445).

    What I did:

    • I drove opencode acp with a mock OpenAI-compatible provider standing in for a paid model. Its price is set in opencode.jsonc, and OpenCode computes the costs itself.
    • I sent one prompt that starts a subagent.

    What I saw:

    • The subagent's session recorded $100 and the root session $4.
    • The single usage_update reported "cost":{"amount":4,"currency":"USD"}, the root session's own cost only.
    • The TUI's total for the same session would be $104, since it adds the root and its subagents together.

    The script below reproduces it. It starts the mock provider itself, prints the usage_update and then the cost each session recorded.

    Reproduction script (acp.ts)
    // Drives `opencode acp` over stdio: one prompt that starts a subagent, then prints every usage_update.
    // A mock OpenAI-compatible provider stands in for a paid model; the config prices it at $1000 per 1M input tokens.
    // Run: bun acp.ts   (OC_DEV=/path/to/checkout runs from source instead of `opencode` on PATH)
    import { spawn } from "node:child_process"
    import { mkdirSync, writeFileSync } from "node:fs"
    
    // ---- mock provider ----
    let n = 0
    const sse = (chunks: any[]) =>
      new Response(chunks.map((c) => `data: ${JSON.stringify(c)}\n\n`).join("") + "data: [DONE]\n\n", {
        headers: { "content-type": "text/event-stream" },
      })
    const base = { id: "c", object: "chat.completion.chunk", created: 0, model: "m" }
    // Root-session requests use 1,000 input tokens ($1 at the configured price); the subagent's use 100,000 ($100).
    const usage = { prompt_tokens: 1000, completion_tokens: 10, total_tokens: 1010 }
    const childUsage = { prompt_tokens: 100000, completion_tokens: 10, total_tokens: 100010 }
    const server = Bun.serve({
      port: 0,
      async fetch(req) {
        const body: any = await req.json()
        const msgs = body.messages ?? []
        const text = JSON.stringify(msgs)
        const last = msgs[msgs.length - 1]
        n++
        console.log(`req ${n} tools=${(body.tools ?? []).map((t: any) => t.function.name).join(",")} last=${last?.role}`)
        const isChild = text.includes("CHILD_TASK") && !text.includes("SPAWN_PLEASE")
        const finish = (delta: any, reason: string) =>
          sse([
            { ...base, choices: [{ index: 0, delta, finish_reason: null }] },
            { ...base, choices: [{ index: 0, delta: {}, finish_reason: reason }] },
            { ...base, choices: [], usage: isChild ? childUsage : usage },
          ])
        const tools = (body.tools ?? []).map((t: any) => t.function.name)
        if (isChild) return finish({ role: "assistant", content: "child done" }, "stop")
        if (tools.includes("subagent") && last?.role === "user" && text.includes("SPAWN_PLEASE") && !text.includes("tool_call_id")) {
          return finish({ role: "assistant", tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "subagent", arguments: JSON.stringify({ agent: "general", description: "child work", prompt: "CHILD_TASK do it" }) } }] }, "tool_calls")
        }
        return finish({ role: "assistant", content: "parent done" }, "stop")
      },
    })
    
    // ---- project ----
    const cwd = `/tmp/opencode/acp-project-${Date.now()}`
    mkdirSync(cwd, { recursive: true })
    writeFileSync(`${cwd}/opencode.jsonc`, JSON.stringify({
      model: "mock/paid",
      providers: { mock: {
        package: "@opencode/ai/providers/openai-compatible",
        settings: { baseURL: `http://127.0.0.1:${server.port}/v1`, apiKey: "x" },
        models: { paid: { cost: { input: 1000, output: 0 }, limit: { context: 200000, output: 8000 } } },
      } },
    }))
    const cmd = process.env.OC_DEV
      ? ["bun", ["--conditions=browser", `--preload=${process.env.OC_DEV}/packages/tui/node_modules/@opentui/solid/scripts/preload.js`, `${process.env.OC_DEV}/packages/cli/src/index.ts`, "acp"]]
      : ["opencode", ["acp"]]
    const home = `/tmp/opencode/acp-home-${Date.now()}`
    const p = spawn(cmd[0] as string, cmd[1] as string[], {
      cwd,
      env: {
        ...process.env,
        // From source the CLI re-spawns itself for its server without bun's flags, so pass them via BUN_OPTIONS too.
        ...(process.env.OC_DEV ? { BUN_OPTIONS: `--conditions=browser --preload=${process.env.OC_DEV}/packages/tui/node_modules/@opentui/solid/scripts/preload.js` } : {}),
        HOME: home, XDG_DATA_HOME: `${home}/data`, XDG_CONFIG_HOME: `${home}/config`, XDG_STATE_HOME: `${home}/state`, XDG_CACHE_HOME: `${home}/cache` },
      stdio: ["pipe", "pipe", "inherit"],
    })
    let id = 0
    const pending = new Map<number, (v: any) => void>()
    const send = (o: any) => p.stdin.write(JSON.stringify(o) + "\n")
    const call = (method: string, params: any) => new Promise<any>((r) => { const i = ++id; pending.set(i, r); send({ jsonrpc: "2.0", id: i, method, params }) })
    let buf = ""
    const sessions = new Set<string>()
    p.stdout.on("data", (d) => {
      buf += d
      let i
      while ((i = buf.indexOf("\n")) >= 0) {
        const line = buf.slice(0, i); buf = buf.slice(i + 1)
        if (!line.trim()) continue
        const m = JSON.parse(line)
        if (m.id !== undefined && pending.has(m.id) && !m.method) { pending.get(m.id)!(m); pending.delete(m.id); continue }
        if (m.method === "session/request_permission") {
          const opt = m.params.options.find((o: any) => o.kind?.startsWith("allow")) ?? m.params.options[0]
          send({ jsonrpc: "2.0", id: m.id, result: { outcome: { outcome: "selected", optionId: opt.optionId } } })
          continue
        }
        if (m.method === "session/update") {
          const u = m.params.update
          if (u.sessionUpdate === "usage_update") console.log("USAGE_UPDATE", JSON.stringify(u))
          else if (u.sessionUpdate === "tool_call") console.log("TOOL_CALL", u.title, JSON.stringify(u.rawOutput ?? "").slice(0, 120))
          const m2 = JSON.stringify(m).match(/ses_[A-Za-z0-9]+/g); m2?.forEach((s) => sessions.add(s))
        }
      }
    })
    const init = await call("initialize", { protocolVersion: 1, clientCapabilities: {} })
    console.log("agent:", JSON.stringify(init.result?.agentInfo))
    const s = await call("session/new", { cwd, mcpServers: [] })
    const sid = s.result.sessionId
    console.log("root session", sid)
    const r = await call("session/prompt", { sessionId: sid, prompt: [{ type: "text", text: "SPAWN_PLEASE start one subagent" }] })
    console.log("prompt result", JSON.stringify(r.result ?? r.error))
    await Bun.sleep(8000) // let the background subagent finish and the parent react to its result
    console.log("sessions seen in updates:", [...sessions].join(", "))
    p.kill()
    await Bun.sleep(500)
    // What each session recorded (what the TUI footer/sidebar add up for the root session).
    const { Database } = await import("bun:sqlite")
    const { existsSync } = await import("node:fs")
    const dbPath = [`${home}/data/opencode/opencode.db`, `${home}/data/opencode/opencode-local.db`].find((f) => existsSync(f))!
    const db = new Database(dbPath, { readonly: true })
    const rows = db.query("select id, parent_id, cost from session_v2").all() as any[]
    console.log("session costs:", JSON.stringify(rows))
    console.log("root + subagents total:", rows.reduce((t, r) => t + r.cost, 0))
    process.exit(0)

    Run it: bun acp.ts

  3. added
    status/repro-simulated
    on Nov 22, 2026
  4. added a commit that references this issue on Nov 22, 2026
    ea36ab4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/ide-acpplatform/windowsstatus/repro-simulatedtype/bugversion/v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions