Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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.
40 changes: 40 additions & 0 deletions packages/opencode/src/kilocode/session/cost-propagation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// 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 {
/**
* 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.
*
* Caller must guarantee serial access to the parent message — concurrent
* calls against the same `(sid, mid)` are not atomic (read-modify-write).
*/
export const propagate = Effect.fn("KiloCostPropagation.propagate")(function* (
sessions: Session.Interface,
sid: SessionID,
mid: MessageID,
amount: number,
) {
if (!(amount > 0)) return
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)
})
}
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.
Resolved
}),
// kilocode_change end
)
})

Expand Down
59 changes: 59 additions & 0 deletions packages/opencode/test/session/prompt-effect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,65 @@ it.live(
30_000,
)

// kilocode_change start - handleSubtask propagates child session cost to wrapper (#6321)
it.live(
"handleSubtask propagates subagent cost to wrapper message",
() =>
provideTmpdirServer(
Effect.fnUntraced(function* ({ llm }) {
const prompt = yield* SessionPrompt.Service
const sessions = yield* Session.Service
const registry = yield* ToolRegistry.Service
const { task } = yield* registry.named()
const original = task.execute
// Simulate task tool: create a child session, persist an assistant with cost, return metadata.
task.execute = (_args, ctx) =>
Effect.gen(function* () {
const child = yield* sessions.create({ parentID: ctx.sessionID, title: "subagent" })
const childAssistant: MessageV2.Assistant = {
id: MessageID.ascending(),
role: "assistant",
parentID: ctx.messageID,
sessionID: child.id,
mode: "general",
agent: "general",
cost: 0.42,
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(), completed: Date.now() },
finish: "stop",
}
yield* sessions.updateMessage(childAssistant)
yield* ctx.metadata({
title: "done",
metadata: { sessionId: child.id, model: ref },
})
return { title: "done", metadata: { sessionId: child.id, model: ref }, output: "done" }
})
yield* Effect.addFinalizer(() => Effect.sync(() => void (task.execute = original)))

const chat = yield* sessions.create({ title: "Pinned" })
const msg = yield* user(chat.id, "hello")
yield* addSubtask(chat.id, msg.id)
// The loop continues past handleSubtask into a normal LLM step; provide one response to exit.
yield* llm.text("wrapped")

yield* prompt.loop({ sessionID: chat.id })

const msgs = yield* MessageV2.filterCompactedEffect(chat.id)
const wrapper = msgs.find((item) => item.info.role === "assistant" && item.info.agent === "general")
expect(wrapper?.info.role).toBe("assistant")
if (!wrapper || wrapper.info.role !== "assistant") return
expect(wrapper.info.cost).toBeCloseTo(0.42, 6)
}),
{ git: true, config: providerCfg },
),
30_000,
)
// kilocode_change end

it.live(
"cancel with queued callers resolves all cleanly",
() =>
Expand Down
Loading
Loading