Skip to content

Commit 70edb69

Browse files
feat(util,app): add sub-agent cost breakdown with recursive session walker
Adds a costs() utility that recursively walks sub-agent sessions to compute own vs total cost. Updates UI/TUI to display the breakdown. Fixes anomalyco#11027
1 parent d30e917 commit 70edb69

27 files changed

Lines changed: 375 additions & 20 deletions

File tree

‎packages/app/src/components/session-context-usage.tsx‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,13 @@ export function SessionContextUsage(props: SessionContextUsageProps) {
4444
}),
4545
)
4646

47-
const metrics = createMemo(() => getSessionContextMetrics(messages(), sync.data.provider.all))
47+
const metrics = createMemo(() => getSessionContextMetrics(messages(), sync.data.provider.all, sync.data))
4848
const context = createMemo(() => metrics().context)
4949
const cost = createMemo(() => {
50-
return usd().format(metrics().totalCost)
50+
const agent = usd().format(metrics().ownCost)
51+
const total = usd().format(metrics().totalCost)
52+
const value = `(current agent ${agent}; total ${total})`
53+
return metrics().missing.length > 0 ? `${value}${language.t("context.stats.loaded")}` : value
5154
})
5255

5356
const openContext = () => {

‎packages/app/src/components/session/session-context-metrics.test.ts‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@ const assistant = (
88
cost: number,
99
providerID = "openai",
1010
modelID = "gpt-4.1",
11+
sessionID = "s1",
1112
) => {
1213
return {
1314
id,
15+
sessionID,
1416
role: "assistant",
1517
providerID,
1618
modelID,
@@ -28,9 +30,10 @@ const assistant = (
2830
} as unknown as Message
2931
}
3032

31-
const user = (id: string) => {
33+
const user = (id: string, sessionID = "s1") => {
3234
return {
3335
id,
36+
sessionID,
3437
role: "user",
3538
cost: 0,
3639
time: { created: 1 },
@@ -98,4 +101,44 @@ describe("getSessionContextMetrics", () => {
98101
expect(metrics.totalCost).toBe(0)
99102
expect(metrics.context).toBeUndefined()
100103
})
104+
105+
test("computes costs with store including sub-agents", () => {
106+
const messages = [
107+
assistant("a1", { input: 10, output: 10, reasoning: 0, read: 0, write: 0 }, 0.5, "openai", "gpt-4.1", "s1"),
108+
]
109+
const store = {
110+
message: {
111+
s1: [{ id: "a1", role: "assistant", cost: 0.5 }],
112+
s2: [{ id: "a2", role: "assistant", cost: 1.0 }],
113+
},
114+
part: {
115+
a1: [{ type: "tool", tool: "task", state: { metadata: { sessionId: "s2" } } }],
116+
},
117+
}
118+
119+
const metrics = getSessionContextMetrics(messages, [], store)
120+
121+
expect(metrics.totalCost).toBe(1.5)
122+
expect(metrics.ownCost).toBe(0.5)
123+
expect(metrics.missing).toEqual([])
124+
})
125+
126+
test("identifies missing child sessions in store", () => {
127+
const messages = [
128+
assistant("a1", { input: 10, output: 10, reasoning: 0, read: 0, write: 0 }, 0.5, "openai", "gpt-4.1", "s1"),
129+
]
130+
const store = {
131+
message: {
132+
s1: [{ id: "a1", role: "assistant", cost: 0.5 }],
133+
},
134+
part: {
135+
a1: [{ type: "tool", tool: "task", state: { metadata: { sessionId: "s2" } } }],
136+
},
137+
}
138+
139+
const metrics = getSessionContextMetrics(messages, [], store)
140+
141+
expect(metrics.totalCost).toBe(0.5)
142+
expect(metrics.missing).toEqual(["s2"])
143+
})
101144
})

‎packages/app/src/components/session/session-context-metrics.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { costs } from "@opencode-ai/util/cost"
12
import type { AssistantMessage, Message } from "@opencode-ai/sdk/v2/client"
23

34
type Provider = {
@@ -31,6 +32,8 @@ type Context = {
3132

3233
type Metrics = {
3334
totalCost: number
35+
ownCost: number
36+
missing: string[]
3437
context: Context | undefined
3538
}
3639

@@ -47,10 +50,22 @@ const lastAssistantWithTokens = (messages: Message[]) => {
4750
}
4851
}
4952

50-
const build = (messages: Message[] = [], providers: Provider[] = []): Metrics => {
51-
const totalCost = messages.reduce((sum, msg) => sum + (msg.role === "assistant" ? msg.cost : 0), 0)
53+
const build = (
54+
messages: Message[] = [],
55+
providers: Provider[] = [],
56+
store?: { message: Record<string, any[]>; part: Record<string, any[]> },
57+
): Metrics => {
58+
const id = messages[0]?.sessionID
59+
const result = store && id ? costs(id, store as any) : undefined
60+
61+
const totalCost = result
62+
? result.total
63+
: messages.reduce((sum, msg) => sum + (msg.role === "assistant" ? msg.cost : 0), 0)
64+
const ownCost = result ? result.own : totalCost
65+
const missing = result ? result.missing : []
66+
5267
const message = lastAssistantWithTokens(messages)
53-
if (!message) return { totalCost, context: undefined }
68+
if (!message) return { totalCost, ownCost, missing, context: undefined }
5469

5570
const provider = providers.find((item) => item.id === message.providerID)
5671
const model = provider?.models[message.modelID]
@@ -59,6 +74,8 @@ const build = (messages: Message[] = [], providers: Provider[] = []): Metrics =>
5974

6075
return {
6176
totalCost,
77+
ownCost,
78+
missing,
6279
context: {
6380
message,
6481
provider,
@@ -77,6 +94,10 @@ const build = (messages: Message[] = [], providers: Provider[] = []): Metrics =>
7794
}
7895
}
7996

80-
export function getSessionContextMetrics(messages: Message[] = [], providers: Provider[] = []) {
81-
return build(messages, providers)
97+
export function getSessionContextMetrics(
98+
messages: Message[] = [],
99+
providers: Provider[] = [],
100+
store?: { message: Record<string, any[]>; part: Record<string, any[]> },
101+
) {
102+
return build(messages, providers, store)
82103
}

‎packages/app/src/components/session/session-context-tab.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,13 @@ export function SessionContextTab(props: SessionContextTabProps) {
104104
}),
105105
)
106106

107-
const metrics = createMemo(() => getSessionContextMetrics(props.messages(), sync.data.provider.all))
107+
const metrics = createMemo(() => getSessionContextMetrics(props.messages(), sync.data.provider.all, sync.data))
108108
const ctx = createMemo(() => metrics().context)
109109
const formatter = createMemo(() => createSessionContextFormatter(language.locale()))
110110

111111
const cost = createMemo(() => {
112-
return usd().format(metrics().totalCost)
112+
const value = usd().format(metrics().totalCost)
113+
return metrics().missing.length > 0 ? `${value}${language.t("context.stats.loaded")}` : value
113114
})
114115

115116
const counts = createMemo(() => {
@@ -185,6 +186,7 @@ export function SessionContextTab(props: SessionContextTabProps) {
185186
},
186187
{ label: "context.stats.userMessages", value: () => counts().user.toLocaleString(language.locale()) },
187188
{ label: "context.stats.assistantMessages", value: () => counts().assistant.toLocaleString(language.locale()) },
189+
{ label: "context.stats.ownCost", value: () => formatter().currency(metrics().ownCost) },
188190
{ label: "context.stats.totalCost", value: cost },
189191
{ label: "context.stats.sessionCreated", value: () => formatter().time(props.info()?.time.created) },
190192
{ label: "context.stats.lastActivity", value: () => formatter().time(ctx()?.message.time.created) },

‎packages/app/src/i18n/ar.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,10 @@ export const dict = {
328328
"context.stats.cacheTokens": "رموز التخزين المؤقت (قراءة/كتابة)",
329329
"context.stats.userMessages": "رسائل المستخدم",
330330
"context.stats.assistantMessages": "رسائل المساعد",
331+
"context.stats.ownCost": "تكلفة الجلسة",
331332
"context.stats.totalCost": "التكلفة الإجمالية",
333+
"context.stats.costBreakdown": "(agent {{agentCost}}; total {{totalCost}})",
334+
"context.stats.loaded": " (تم التحميل)",
332335
"context.stats.sessionCreated": "تم إنشاء الجلسة",
333336
"context.stats.lastActivity": "آخر نشاط",
334337
"context.usage.tokens": "رموز",

‎packages/app/src/i18n/br.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,10 @@ export const dict = {
329329
"context.stats.cacheTokens": "Tokens de Cache (leitura/escrita)",
330330
"context.stats.userMessages": "Mensagens de Usuário",
331331
"context.stats.assistantMessages": "Mensagens do Assistente",
332+
"context.stats.ownCost": "Custo da sessão",
332333
"context.stats.totalCost": "Custo Total",
334+
"context.stats.costBreakdown": "(agent {{agentCost}}; total {{totalCost}})",
335+
"context.stats.loaded": " (carregado)",
333336
"context.stats.sessionCreated": "Sessão Criada",
334337
"context.stats.lastActivity": "Última Atividade",
335338
"context.usage.tokens": "Tokens",

‎packages/app/src/i18n/bs.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,10 @@ export const dict = {
361361
"context.stats.cacheTokens": "Cache tokeni (čitanje/pisanje)",
362362
"context.stats.userMessages": "Korisničke poruke",
363363
"context.stats.assistantMessages": "Poruke asistenta",
364+
"context.stats.ownCost": "Trošak sesije",
364365
"context.stats.totalCost": "Ukupni trošak",
366+
"context.stats.costBreakdown": "(agent {{agentCost}}; total {{totalCost}})",
367+
"context.stats.loaded": " (učitano)",
365368
"context.stats.sessionCreated": "Sesija kreirana",
366369
"context.stats.lastActivity": "Posljednja aktivnost",
367370

‎packages/app/src/i18n/da.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,13 @@ export const dict = {
359359
"context.stats.cacheTokens": "Cache Tokens (læs/skriv)",
360360
"context.stats.userMessages": "Brugerbeskeder",
361361
"context.stats.assistantMessages": "Assistentbeskeder",
362+
"context.stats.ownCost": "Sessionsomkostninger",
363+
"context.stats.ownCost": "Sessionsomkostninger",
362364
"context.stats.totalCost": "Samlede omkostninger",
365+
"context.stats.costBreakdown": "(agent {{agentCost}}; total {{totalCost}})",
366+
"context.stats.loaded": " (indlæst)",
367+
"context.stats.costBreakdown": "(agent {{agentCost}}; total {{totalCost}})",
368+
"context.stats.loaded": " (indlæst)",
363369
"context.stats.sessionCreated": "Session oprettet",
364370
"context.stats.lastActivity": "Seneste aktivitet",
365371

‎packages/app/src/i18n/de.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,10 @@ export const dict = {
336336
"context.stats.cacheTokens": "Cache-Token (lesen/schreiben)",
337337
"context.stats.userMessages": "Benutzernachrichten",
338338
"context.stats.assistantMessages": "Assistentennachrichten",
339+
"context.stats.ownCost": "Sitzungskosten",
339340
"context.stats.totalCost": "Gesamtkosten",
341+
"context.stats.costBreakdown": "(agent {{agentCost}}; total {{totalCost}})",
342+
"context.stats.loaded": " (geladen)",
340343
"context.stats.sessionCreated": "Sitzung erstellt",
341344
"context.stats.lastActivity": "Letzte Aktivität",
342345
"context.usage.tokens": "Token",

‎packages/app/src/i18n/en.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,10 @@ export const dict = {
360360
"context.stats.cacheTokens": "Cache Tokens (read/write)",
361361
"context.stats.userMessages": "User Messages",
362362
"context.stats.assistantMessages": "Assistant Messages",
363+
"context.stats.ownCost": "Session Cost",
363364
"context.stats.totalCost": "Total Cost",
365+
"context.stats.costBreakdown": "(agent {{agentCost}}; total {{totalCost}})",
366+
"context.stats.loaded": " (loaded)",
364367
"context.stats.sessionCreated": "Session Created",
365368
"context.stats.lastActivity": "Last Activity",
366369

0 commit comments

Comments
 (0)