Repository navigation
fix(cli): include subagent costs in session total #9448
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
73ab363
fix(cli): include subagent costs in session total (#6321)
alex-alecu ae0c437
fix(cli): serialize concurrent subagent cost propagation
alex-alecu 418fe78
fix(cli): sync processor cost after subagent propagation
alex-alecu 195ef4e
fix(cli): exclude subagent sessions from stats aggregate
alex-alecu 1230a3a
fix(cli): ignore deleted cost sync
alex-alecu bc90a50
fix(cli): count subagent stats
alex-alecu 7a9da3f
chore(cli): mark stats cost line
alex-alecu 1eaf409
refactor(cli): simplify stats cost
alex-alecu 87ba16c
Merge branch 'main' into fix/costs-of-subagents
alex-alecu 67993d0
Merge remote-tracking branch 'origin/main' into fix/costs-of-subagents
alex-alecu 16abe96
chore(cli): fix type error after main merge
alex-alecu e101781
Merge branch 'fix/costs-of-subagents' of https://github.com/Kilo-Org/…
alex-alecu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@kilocode/cli": patch | ||
| --- | ||
|
|
||
| Fix session cost display missing subagent costs. The TUI footer, sidebar, web context panel, and ACP usage reports now include the cost of every subagent the session spawned, including nested ones. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
packages/opencode/src/kilocode/session/cost-propagation.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| // kilocode_change - new file | ||
| import { Effect } from "effect" | ||
| import { Session } from "@/session" | ||
| import { MessageV2 } from "@/session/message-v2" | ||
| import { SessionID, MessageID } from "@/session/schema" | ||
|
|
||
| export namespace KiloCostPropagation { | ||
| /** | ||
| * Per-key promise chain that serializes concurrent `propagate` calls against | ||
| * the same parent message. Prevents lost updates when the LLM launches | ||
| * several `task` tool calls in parallel (each release stage races to | ||
| * read-modify-write the same parent cost field). | ||
| */ | ||
| const locks = new Map<string, Promise<void>>() | ||
|
|
||
| function acquire(key: string): Promise<() => void> { | ||
| const prev = locks.get(key) ?? Promise.resolve() | ||
| let release!: () => void | ||
| const current = new Promise<void>((r) => (release = r)) | ||
| const chain = prev.catch(() => {}).then(() => current) | ||
| locks.set(key, chain) | ||
| return prev | ||
| .catch(() => {}) | ||
| .then(() => () => { | ||
| release() | ||
| if (locks.get(key) === chain) locks.delete(key) | ||
| }) | ||
| } | ||
|
|
||
| /** | ||
| * Total assistant-message cost in a session. Because each subagent propagates | ||
| * its own total into the parent assistant message when it finishes, this sum | ||
| * already reflects descendant sessions recursively — no tree walk needed. | ||
| */ | ||
| export const childCost = Effect.fn("KiloCostPropagation.childCost")(function* ( | ||
| sessions: Session.Interface, | ||
| id: SessionID, | ||
| ) { | ||
| const msgs = yield* sessions.messages({ sessionID: id }) | ||
| return msgs.reduce((sum, m) => sum + (m.info.role === "assistant" ? m.info.cost : 0), 0) | ||
| }) | ||
|
|
||
| /** | ||
| * Add `amount` to the given parent assistant message's cost. No-op when | ||
| * `amount` is non-positive or the target is not an assistant message. | ||
| * | ||
| * Concurrent calls against the same parent are serialized internally so the | ||
| * read-modify-write cannot lose updates when subagents complete in parallel. | ||
| */ | ||
| export const propagate = Effect.fn("KiloCostPropagation.propagate")(function* ( | ||
| sessions: Session.Interface, | ||
| sid: SessionID, | ||
| mid: MessageID, | ||
| amount: number, | ||
| ) { | ||
| if (!(amount > 0)) return | ||
| yield* Effect.acquireUseRelease( | ||
| Effect.promise(() => acquire(`${sid}:${mid}`)), | ||
| () => | ||
| Effect.gen(function* () { | ||
| const parent = yield* Effect.sync(() => MessageV2.get({ sessionID: sid, messageID: mid })) | ||
| if (parent.info.role !== "assistant") return | ||
| parent.info.cost += amount | ||
| yield* sessions.updateMessage(parent.info) | ||
| }), | ||
| (release) => Effect.sync(() => release()), | ||
| ) | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| // Verifies KiloCostPropagation.propagate() serializes concurrent writes to | ||
| // the same parent assistant message. Without the internal lock, parallel | ||
| // subagent completions race on read-modify-write and lose deltas (#6321). | ||
|
|
||
| import { afterEach, describe, expect } from "bun:test" | ||
| import { Effect, Layer } from "effect" | ||
| import { Bus } from "../../src/bus" | ||
| import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner" | ||
| import { KiloCostPropagation } from "../../src/kilocode/session/cost-propagation" | ||
| import { Instance } from "../../src/project/instance" | ||
| import { ProviderID, ModelID } from "../../src/provider/schema" | ||
| import { Session } from "../../src/session" | ||
| import { MessageV2 } from "../../src/session/message-v2" | ||
| import { MessageID } from "../../src/session/schema" | ||
| import { Log } from "../../src/util" | ||
| import { provideTmpdirInstance } from "../fixture/fixture" | ||
| import { testEffect } from "../lib/effect" | ||
|
|
||
| Log.init({ print: false }) | ||
|
|
||
| afterEach(async () => { | ||
| await Instance.disposeAll() | ||
| }) | ||
|
|
||
| const ref = { | ||
| providerID: ProviderID.make("test"), | ||
| modelID: ModelID.make("test-model"), | ||
| } | ||
|
|
||
| const it = testEffect(Layer.mergeAll(Session.defaultLayer, Bus.layer, CrossSpawnSpawner.defaultLayer)) | ||
|
|
||
| const seed = Effect.fn("CostPropagationTest.seed")(function* () { | ||
| const sessions = yield* Session.Service | ||
| const chat = yield* sessions.create({ title: "parent" }) | ||
| const user = yield* sessions.updateMessage({ | ||
| id: MessageID.ascending(), | ||
| role: "user", | ||
| sessionID: chat.id, | ||
| agent: "build", | ||
| model: ref, | ||
| time: { created: Date.now() }, | ||
| }) | ||
| const assistant: MessageV2.Assistant = { | ||
| id: MessageID.ascending(), | ||
| role: "assistant", | ||
| parentID: user.id, | ||
| sessionID: chat.id, | ||
| mode: "build", | ||
| agent: "build", | ||
| cost: 0, | ||
| path: { cwd: "/tmp", root: "/tmp" }, | ||
| tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, | ||
| modelID: ref.modelID, | ||
| providerID: ref.providerID, | ||
| time: { created: Date.now() }, | ||
| } | ||
| yield* sessions.updateMessage(assistant) | ||
| return { chat, assistant } | ||
| }) | ||
|
|
||
| describe("KiloCostPropagation.propagate", () => { | ||
| it.live("sums deltas correctly under parallel execution", () => | ||
| provideTmpdirInstance(() => | ||
| Effect.gen(function* () { | ||
| const sessions = yield* Session.Service | ||
| const { chat, assistant } = yield* seed() | ||
| const deltas = [0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28] | ||
| yield* Effect.all( | ||
| deltas.map((d) => KiloCostPropagation.propagate(sessions, chat.id, assistant.id, d)), | ||
| { concurrency: "unbounded" }, | ||
| ) | ||
| const parent = yield* Effect.sync(() => MessageV2.get({ sessionID: chat.id, messageID: assistant.id })) | ||
| expect(parent.info.role).toBe("assistant") | ||
| if (parent.info.role !== "assistant") return | ||
| const total = deltas.reduce((a, b) => a + b, 0) | ||
| expect(parent.info.cost).toBeCloseTo(total, 6) | ||
| }), | ||
| ), | ||
| ) | ||
|
|
||
| it.live("is a no-op when amount is non-positive", () => | ||
| provideTmpdirInstance(() => | ||
| Effect.gen(function* () { | ||
| const sessions = yield* Session.Service | ||
| const { chat, assistant } = yield* seed() | ||
| yield* KiloCostPropagation.propagate(sessions, chat.id, assistant.id, 0) | ||
| yield* KiloCostPropagation.propagate(sessions, chat.id, assistant.id, -1.5) | ||
| const parent = yield* Effect.sync(() => MessageV2.get({ sessionID: chat.id, messageID: assistant.id })) | ||
| if (parent.info.role !== "assistant") return | ||
| expect(parent.info.cost).toBe(0) | ||
| }), | ||
| ), | ||
| ) | ||
| }) |
84 changes: 84 additions & 0 deletions
84
packages/opencode/test/kilocode/stats-subagent-cost.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| // Verifies `kilo stats` does not double-count subagent cost. The task tool | ||
| // propagates each child session's total cost up to the parent's tool-wrapper | ||
| // assistant message. If stats summed every session indiscriminately, that | ||
| // propagated cost would appear in both the parent wrapper and the child's | ||
| // own messages. The aggregator is now filtered to root sessions (#6321). | ||
|
|
||
| import { afterEach, describe, expect, test } from "bun:test" | ||
| import { aggregateSessionStats } from "../../src/cli/cmd/stats" | ||
| import { MessageV2 } from "../../src/session/message-v2" | ||
| import { Instance } from "../../src/project/instance" | ||
| import { ProviderID, ModelID } from "../../src/provider/schema" | ||
| import { Session } from "../../src/session" | ||
| import { MessageID } from "../../src/session/schema" | ||
| import { Log } from "../../src/util" | ||
| import { tmpdir } from "../fixture/fixture" | ||
|
|
||
| Log.init({ print: false }) | ||
|
|
||
| afterEach(async () => { | ||
| await Instance.disposeAll() | ||
| }) | ||
|
|
||
| const ref = { | ||
| providerID: ProviderID.make("test"), | ||
| modelID: ModelID.make("test-model"), | ||
| } | ||
|
|
||
| function assistant(sessionID: string, parentID: string, cost: number): MessageV2.Assistant { | ||
| return { | ||
| id: MessageID.ascending(), | ||
| role: "assistant", | ||
| parentID: parentID as any, | ||
| sessionID: sessionID as any, | ||
| mode: "build", | ||
| agent: "build", | ||
| cost, | ||
| path: { cwd: "/tmp", root: "/tmp" }, | ||
| tokens: { input: 10, output: 5, reasoning: 0, cache: { read: 0, write: 0 } }, | ||
| modelID: ref.modelID, | ||
| providerID: ref.providerID, | ||
| time: { created: Date.now() }, | ||
| } | ||
| } | ||
|
|
||
| describe("stats subagent cost", () => { | ||
| test("totalCost excludes children whose cost was propagated into the parent", async () => { | ||
| await using tmp = await tmpdir({ git: true }) | ||
| await Instance.provide({ | ||
| directory: tmp.path, | ||
| fn: async () => { | ||
| const parent = await Session.create({ title: "root" }) | ||
| const child = await Session.create({ parentID: parent.id, title: "subagent" }) | ||
|
|
||
| // The parent's tool-wrapper assistant message shows the propagated total (own LLM + child). | ||
| const userMsg = await Session.updateMessage({ | ||
| id: MessageID.ascending(), | ||
| role: "user", | ||
| sessionID: parent.id, | ||
| agent: "build", | ||
| model: ref, | ||
| time: { created: Date.now() }, | ||
| } as any) | ||
| await Session.updateMessage(assistant(parent.id, userMsg.id, 1.5)) | ||
| // The child session independently records its own LLM cost. | ||
| const childUser = await Session.updateMessage({ | ||
| id: MessageID.ascending(), | ||
| role: "user", | ||
| sessionID: child.id, | ||
| agent: "general", | ||
| model: ref, | ||
| time: { created: Date.now() }, | ||
| } as any) | ||
| await Session.updateMessage(assistant(child.id, childUser.id, 0.5)) | ||
|
|
||
| const stats = await aggregateSessionStats() | ||
| // Without the fix, totalCost would be 1.5 + 0.5 = 2.0 (child counted twice). | ||
| // With the fix, only the parent (root) session contributes: 1.5 (which already | ||
| // includes the 0.5 propagated from the child). | ||
| expect(stats.totalCost).toBeCloseTo(1.5, 6) | ||
| expect(stats.totalSessions).toBe(1) | ||
| }, | ||
| }) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.