Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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.
8 changes: 6 additions & 2 deletions packages/opencode/src/cli/cmd/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,11 @@ export async function aggregateSessionStats(days?: number, projectFilter?: strin

for (const message of messages) {
if (message.info.role === "assistant") {
sessionCost += message.info.cost || 0
// kilocode_change start - count propagated subagent cost once but keep child model stats (#6321)
const parts = message.parts.filter((part) => part.type === "step-finish")
const cost = parts.length ? parts.reduce((sum, part) => sum + part.cost, 0) : message.info.cost || 0
if (!session.parentID) sessionCost += message.info.cost || 0
// kilocode_change end

const modelKey = `${message.info.providerID}/${message.info.modelID}`
if (!sessionModelUsage[modelKey]) {
Expand All @@ -204,7 +208,7 @@ export async function aggregateSessionStats(days?: number, projectFilter?: strin
}
}
sessionModelUsage[modelKey].messages++
sessionModelUsage[modelKey].cost += message.info.cost || 0
sessionModelUsage[modelKey].cost += cost // kilocode_change

if (message.info.tokens) {
sessionTokens.input += message.info.tokens.input || 0
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()),
)
})
}
23 changes: 23 additions & 0 deletions packages/opencode/src/session/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type { Provider } from "@/provider"
import { Question } from "@/question"
import { KiloSessionProcessor } from "@/kilocode/session/processor" // kilocode_change
import { Suggestion } from "@/kilocode/suggestion" // kilocode_change
import { NotFoundError } from "@/storage" // kilocode_change
import { errorMessage } from "@/util/error"
import { Log } from "@/util"
import { isRecord } from "@/util/record"
Expand Down Expand Up @@ -157,6 +158,22 @@ export const layer: Layer.Layer<
return { call, part }
})

// kilocode_change start - tolerate deleted sessions during subagent cost reconciliation (#6321)
const reconcile = Effect.fn("SessionProcessor.reconcileCost")(function* () {
const fresh = yield* Effect.sync(() => {
try {
return MessageV2.get({ sessionID: ctx.assistantMessage.sessionID, messageID: ctx.assistantMessage.id })
} catch (err) {
if (NotFoundError.isInstance(err)) return
throw err
}
})
if (fresh?.info.role !== "assistant") return
if (fresh.info.cost <= ctx.assistantMessage.cost) return
ctx.assistantMessage.cost = fresh.info.cost
})
// kilocode_change end

const updateToolCall = Effect.fn("SessionProcessor.updateToolCall")(function* (
toolCallID: string,
update: (part: MessageV2.ToolPart) => MessageV2.ToolPart,
Expand Down Expand Up @@ -410,6 +427,9 @@ 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)
yield* reconcile()
// kilocode_change end
ctx.assistantMessage.cost += usage.cost
ctx.assistantMessage.tokens = usage.tokens
yield* session.updatePart({
Expand Down Expand Up @@ -567,6 +587,9 @@ 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)
yield* reconcile()
// 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 @@ -141,9 +142,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 @@ -180,10 +184,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)
}),
),
)
})
Loading
Loading