Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-subagent-cost-propagation.md
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.
7 changes: 5 additions & 2 deletions packages/opencode/src/cli/cmd/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Argv } from "yargs"
import { cmd } from "./cmd"
import { Session } from "../../session"
import { bootstrap } from "../bootstrap"
import { Database } from "../../storage"
import { Database, isNull } from "../../storage" // kilocode_change - isNull for root session filter
import { SessionTable } from "../../session/session.sql"
import { Project } from "../../project"
import { Instance } from "../../project/instance"
Expand Down Expand Up @@ -89,7 +89,10 @@ async function getCurrentProject(): Promise<Project.Info> {
}

async function getAllSessions(): Promise<Session.Info[]> {
const rows = Database.use((db) => db.select().from(SessionTable).all())
// kilocode_change start - exclude subagent (child) sessions; their cost is already propagated into the
// parent's tool-wrapper assistant message, so summing both would double-count (#6321)
const rows = Database.use((db) => db.select().from(SessionTable).where(isNull(SessionTable.parent_id)).all())
Comment thread
alex-alecu marked this conversation as resolved.
Outdated
// kilocode_change end
return rows.map((row) => Session.fromRow(row))
}

Expand Down
69 changes: 69 additions & 0 deletions packages/opencode/src/kilocode/session/cost-propagation.ts
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()),
)
})
}
16 changes: 16 additions & 0 deletions packages/opencode/src/session/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,14 @@ export const layer: Layer.Layer<
})
// kilocode_change end
ctx.assistantMessage.finish = value.finishReason
// kilocode_change start - capture any subagent cost propagated by tool calls during this step (#6321)
const fresh = yield* Effect.sync(() =>
MessageV2.get({ sessionID: ctx.assistantMessage.sessionID, messageID: ctx.assistantMessage.id }),
Comment thread
alex-alecu marked this conversation as resolved.
Outdated
)
if (fresh.info.role === "assistant" && fresh.info.cost > ctx.assistantMessage.cost) {
ctx.assistantMessage.cost = fresh.info.cost
}
// kilocode_change end
ctx.assistantMessage.cost += usage.cost
ctx.assistantMessage.tokens = usage.tokens
yield* session.updatePart({
Expand Down Expand Up @@ -567,6 +575,14 @@ export const layer: Layer.Layer<
ctx.toolcalls = {}
KiloSessionProcessor.guardEmptyToolCalls(ctx.assistantMessage, MessageV2.parts(ctx.assistantMessage.id)) // kilocode_change
ctx.assistantMessage.time.completed = Date.now()
// kilocode_change start - reconcile cost with any subagent propagation written during tool calls (#6321)
const fresh = yield* Effect.sync(() =>
MessageV2.get({ sessionID: ctx.assistantMessage.sessionID, messageID: ctx.assistantMessage.id }),
)
if (fresh.info.role === "assistant" && fresh.info.cost > ctx.assistantMessage.cost) {
ctx.assistantMessage.cost = fresh.info.cost
}
// kilocode_change end
yield* session.updateMessage(ctx.assistantMessage)
})

Expand Down
19 changes: 19 additions & 0 deletions packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import fs from "fs/promises"
import { KiloSessionPrompt } from "@/kilocode/session/prompt" // kilocode_change
import { KiloSessionPromptQueue } from "@/kilocode/session/prompt-queue" // kilocode_change
import { KiloSession } from "@/kilocode/session" // kilocode_change
import { KiloCostPropagation } from "@/kilocode/session/cost-propagation" // kilocode_change
import { Suggestion } from "@/kilocode/suggestion" // kilocode_change
import { Question } from "@/question" // kilocode_change
import z from "zod"
Expand Down Expand Up @@ -598,6 +599,12 @@ NOTE: At any point in time through this workflow you should feel free to ask the

let error: Error | undefined
const taskAbort = new AbortController()
// kilocode_change start - shared reader for the child session id written by task.ts ctx.metadata (#6321)
const childID = () => {
const meta = part.state.status !== "pending" ? part.state.metadata : undefined
return (meta as { sessionId?: string } | undefined)?.sessionId
}
// kilocode_change end
const result = yield* taskTool
.execute(taskArgs, {
agent: task.agent,
Expand Down Expand Up @@ -636,6 +643,12 @@ NOTE: At any point in time through this workflow you should feel free to ask the
taskAbort.abort()
assistantMessage.finish = "tool-calls"
assistantMessage.time.completed = Date.now()
// kilocode_change start - propagate partial subagent cost on cancel (#6321)
const cid = childID()
if (cid) {
assistantMessage.cost = yield* KiloCostPropagation.childCost(sessions, SessionID.make(cid))
}
// kilocode_change end
yield* sessions.updateMessage(assistantMessage)
if (part.state.status === "running") {
yield* sessions.updatePart({
Expand Down Expand Up @@ -668,6 +681,12 @@ NOTE: At any point in time through this workflow you should feel free to ask the

assistantMessage.finish = "tool-calls"
assistantMessage.time.completed = Date.now()
// kilocode_change start - include subagent total cost on the wrapper message (#6321)
const cid = result?.metadata?.sessionId ?? childID()
if (cid) {
assistantMessage.cost = yield* KiloCostPropagation.childCost(sessions, SessionID.make(cid))
}
// kilocode_change end
yield* sessions.updateMessage(assistantMessage)

if (result && part.state.status === "running") {
Expand Down
14 changes: 11 additions & 3 deletions packages/opencode/src/tool/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { SessionPrompt } from "../session/prompt"
import { Config } from "../config"
import { Effect } from "effect"
import { KiloTask } from "../kilocode/tool/task" // kilocode_change
import { KiloCostPropagation } from "../kilocode/session/cost-propagation" // kilocode_change

export interface TaskPromptOps {
cancel(sessionID: SessionID): void
Expand Down Expand Up @@ -135,9 +136,12 @@ export const TaskTool = Tool.define(
}

return yield* Effect.acquireUseRelease(
Effect.sync(() => {
// kilocode_change start - snapshot child cost so we propagate only the delta on resume (#6321)
Effect.gen(function* () {
ctx.abort.addEventListener("abort", cancel)
return yield* KiloCostPropagation.childCost(sessions, nextSession.id)
}),
// kilocode_change end
() =>
Effect.gen(function* () {
const parts = yield* ops.resolvePromptParts(params.prompt)
Expand Down Expand Up @@ -172,10 +176,14 @@ export const TaskTool = Tool.define(
].join("\n"),
}
}),
() =>
Effect.sync(() => {
// kilocode_change start - propagate subagent cost delta to parent on every exit path (#6321)
(costBefore) =>
Effect.gen(function* () {
ctx.abort.removeEventListener("abort", cancel)
const costAfter = yield* KiloCostPropagation.childCost(sessions, nextSession.id)
yield* KiloCostPropagation.propagate(sessions, ctx.sessionID, ctx.messageID, costAfter - costBefore)
Comment thread
alex-alecu marked this conversation as resolved.
}),
// kilocode_change end
)
})

Expand Down
94 changes: 94 additions & 0 deletions packages/opencode/test/kilocode/cost-propagation.test.ts
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 packages/opencode/test/kilocode/stats-subagent-cost.test.ts
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)
},
})
})
})
Loading
Loading