Skip to content

Commit b7c67d3

Browse files
Claude Agentclaude
andcommitted
feat(session): display-only subtree cost rollup for subagent tasks (nested-agents Issue 6)
Aggregate a finished foreground subagent's whole subtree spend (the spawned session plus every transitive descendant) into the completed task-part metadata as an additive `costRollup` field. This is display-only: each session keeps billing its own cost/tokens via the projector, so the rollup read never double-charges the real accounting (design-final §4.6). - subagent-limits.ts: new `aggregateCost` helper (single source of truth) plus `CostRollup`/`CostRollupNode` shapes, typed structurally to avoid a cycle back into session.ts. - task.ts: roll up over `Session.descendants` on task completion, best-effort (a lookup failure omits the field rather than failing the task). - Tests: 2-3-level tree proves the subtree sum and that the spawner's own per-session accounting is untouched. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 81ea40c commit b7c67d3

3 files changed

Lines changed: 226 additions & 2 deletions

File tree

‎packages/opencode/src/session/subagent-limits.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,57 @@ export function depthHint(depth: number, max: number): string {
5959
return `You are a sub-agent at delegation depth ${depth} of ${max}. You may delegate to deeper sub-agents; prefer doing small tasks yourself.`
6060
}
6161

62+
/** Per-session token aggregate, shaped like `Session.Info.tokens`. */
63+
export interface CostRollupTokens {
64+
input: number
65+
output: number
66+
reasoning: number
67+
cache: { read: number; write: number }
68+
}
69+
70+
/** Aggregated subtree spend — cost in USD plus every token bucket. */
71+
export interface CostRollup {
72+
cost: number
73+
tokens: CostRollupTokens
74+
}
75+
76+
/**
77+
* Structural slice of `Session.Info` the rollup reads. Typed against the shape
78+
* (not the session module) on purpose so this stays a plain, import-light
79+
* module — session.ts already depends on subagent-limits, and importing
80+
* `Session.Info` back would be a cycle.
81+
*/
82+
export interface CostRollupNode {
83+
cost?: number
84+
tokens?: Partial<CostRollupTokens> & { cache?: { read?: number; write?: number } }
85+
}
86+
87+
/**
88+
* Sums cost and tokens across a set of sessions — the single source of truth
89+
* for the subtree cost rollup (design-final §4.6 / Phase-2 Issue 6). Pure
90+
* DISPLAY aggregation over `Session.descendants`: it never writes anything and
91+
* the per-session accounting each node carries is untouched, so there is no
92+
* double-billing. Missing cost/tokens count as zero, matching how the projector
93+
* defaults an un-charged session.
94+
*/
95+
export function aggregateCost(nodes: ReadonlyArray<CostRollupNode>): CostRollup {
96+
const rollup: CostRollup = {
97+
cost: 0,
98+
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
99+
}
100+
for (const node of nodes) {
101+
rollup.cost += node.cost ?? 0
102+
const tokens = node.tokens
103+
if (tokens === undefined) continue
104+
rollup.tokens.input += tokens.input ?? 0
105+
rollup.tokens.output += tokens.output ?? 0
106+
rollup.tokens.reasoning += tokens.reasoning ?? 0
107+
rollup.tokens.cache.read += tokens.cache?.read ?? 0
108+
rollup.tokens.cache.write += tokens.cache?.write ?? 0
109+
}
110+
return rollup
111+
}
112+
62113
/**
63114
* Raised when a session at the maximum nesting depth attempts to spawn another
64115
* subagent (or, as the config-free hard cap in `Session.createNext`, when a

‎packages/opencode/src/tool/task.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import type { SessionPrompt } from "../session/prompt"
1212
import { SubagentLimits } from "../session/subagent-limits"
1313
import { TurnBudget } from "../session/turn-budget"
1414
import { Config } from "@/config/config"
15-
import { Effect, Exit, Schema, Scope } from "effect"
15+
import { Effect, Exit, Option, Schema, Scope } from "effect"
1616
import { EffectBridge } from "@/effect/bridge"
1717
import { RuntimeFlags } from "@/effect/runtime-flags"
1818
import { Database } from "@opencode-ai/core/database/database"
@@ -114,6 +114,16 @@ export const TaskTool = Tool.define(
114114
// resumes/extends do not count and workflow dispatches keep their own cap.
115115
const treeSpawnCounts = new Map<SessionID, number>()
116116

117+
// Aggregates the cost/tokens of a finished subagent's whole subtree (the
118+
// session itself + every transitive child) for the completed task part's
119+
// metadata. Pure read over Session.descendants — design-final §4.6 /
120+
// Phase-2 Issue 6 — no write, no effect on the per-session bill.
121+
const rollupSubtreeCost = Effect.fn("TaskTool.rollupSubtreeCost")(function* (sessionID: SessionID) {
122+
const root = yield* sessions.get(sessionID)
123+
const descendants = yield* sessions.descendants(sessionID)
124+
return SubagentLimits.aggregateCost([root, ...descendants])
125+
})
126+
117127
const run = Effect.fn("TaskTool.execute")(function* (
118128
params: Schema.Schema.Type<typeof Parameters>,
119129
ctx: Tool.Context,
@@ -421,9 +431,16 @@ export const TaskTool = Tool.define(
421431
if (result?.metadata?.background === true) return backgroundResult()
422432
if (result?.status === "error") return yield* Effect.fail(new Error(result.error ?? "Task failed"))
423433
if (result?.status === "cancelled") return yield* Effect.fail(new Error("Task cancelled"))
434+
// Display-only subtree cost rollup (design-final §4.6 / Phase-2
435+
// Issue 6): the spawned session plus its descendants. Each session
436+
// still bills its own spend separately — this aggregate never
437+
// double-charges, it only surfaces the teardown's total. Best-effort:
438+
// a descendants/get failure must not fail an otherwise-completed task,
439+
// so the rollup is simply omitted from the metadata.
440+
const costRollup = Option.getOrUndefined(yield* Effect.option(rollupSubtreeCost(nextSession.id)))
424441
return {
425442
title: params.description,
426-
metadata,
443+
metadata: costRollup ? { ...metadata, costRollup } : metadata,
427444
output: renderOutput({ sessionID: nextSession.id, state: "completed", text: result?.output ?? "" }),
428445
}
429446
}),
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
import { describe, expect } from "bun:test"
2+
import { Effect, Layer } from "effect"
3+
import { eq } from "drizzle-orm"
4+
import { Database } from "@opencode-ai/core/database/database"
5+
import { SessionProjector } from "@opencode-ai/core/session/projector"
6+
import { SessionTable } from "@opencode-ai/core/session/sql"
7+
import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
8+
import { Session as SessionNs } from "@/session/session"
9+
import { SubagentLimits } from "@/session/subagent-limits"
10+
import { Storage } from "@/storage/storage"
11+
import { RuntimeFlags } from "@/effect/runtime-flags"
12+
import { BackgroundJob } from "@/background/job"
13+
import { EventV2Bridge } from "@/event-v2-bridge"
14+
import type { SessionID } from "@/session/schema"
15+
import { testInstanceStoreLayer } from "../fixture/fixture"
16+
import { testEffect } from "../lib/effect"
17+
18+
const it = testEffect(
19+
Layer.mergeAll(
20+
SessionNs.layer.pipe(
21+
Layer.provide(Storage.defaultLayer),
22+
Layer.provide(Database.defaultLayer),
23+
Layer.provideMerge(EventV2Bridge.defaultLayer),
24+
Layer.provide(SessionProjector.defaultLayer),
25+
Layer.provide(RuntimeFlags.layer({ experimentalWorkspaces: false })),
26+
Layer.provide(BackgroundJob.defaultLayer),
27+
),
28+
Database.defaultLayer,
29+
CrossSpawnSpawner.defaultLayer,
30+
testInstanceStoreLayer,
31+
),
32+
)
33+
34+
/**
35+
* Seeds the per-session cost/token aggregate directly in the database — the
36+
* same DB-seam pattern session-lineage.test.ts uses to corrupt parent rows.
37+
* Mirrors what the projector accumulates from step-finish parts, without
38+
* having to drive a full prompt loop.
39+
*/
40+
const seedUsage = (
41+
sessionID: SessionID,
42+
usage: { cost: number; input?: number; output?: number; reasoning?: number; cacheRead?: number; cacheWrite?: number },
43+
) =>
44+
Database.Service.use(({ db }) =>
45+
db
46+
.update(SessionTable)
47+
.set({
48+
cost: usage.cost,
49+
tokens_input: usage.input ?? 0,
50+
tokens_output: usage.output ?? 0,
51+
tokens_reasoning: usage.reasoning ?? 0,
52+
tokens_cache_read: usage.cacheRead ?? 0,
53+
tokens_cache_write: usage.cacheWrite ?? 0,
54+
})
55+
.where(eq(SessionTable.id, sessionID))
56+
.run()
57+
.pipe(Effect.orDie),
58+
)
59+
60+
describe("SubagentLimits.aggregateCost", () => {
61+
it.effect("sums cost and every token bucket across the subtree", () => {
62+
const rollup = SubagentLimits.aggregateCost([
63+
{
64+
cost: 1.5,
65+
tokens: { input: 10, output: 20, reasoning: 5, cache: { read: 3, write: 1 } },
66+
},
67+
{
68+
cost: 0.25,
69+
tokens: { input: 4, output: 6, reasoning: 0, cache: { read: 2, write: 7 } },
70+
},
71+
])
72+
expect(rollup).toEqual({
73+
cost: 1.75,
74+
tokens: { input: 14, output: 26, reasoning: 5, cache: { read: 5, write: 8 } },
75+
})
76+
return Effect.void
77+
})
78+
79+
it.effect("treats missing cost/tokens as zero", () => {
80+
const rollup = SubagentLimits.aggregateCost([{}, { cost: 2 }, { tokens: undefined }])
81+
expect(rollup).toEqual({
82+
cost: 2,
83+
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
84+
})
85+
return Effect.void
86+
})
87+
88+
it.effect("is an empty zero rollup for no nodes", () => {
89+
expect(SubagentLimits.aggregateCost([])).toEqual({
90+
cost: 0,
91+
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
92+
})
93+
return Effect.void
94+
})
95+
})
96+
97+
describe("Session-tree cost rollup", () => {
98+
it.instance("rolls a child's own usage plus its 2-level descendant subtree", () =>
99+
Effect.gen(function* () {
100+
const sessions = yield* SessionNs.Service
101+
// Tree: root → child → grandchild (a 3-level chain, the subagent task is
102+
// the `child`, so the rollup covers child + grandchild).
103+
const root = yield* sessions.create({})
104+
const child = yield* sessions.create({ parentID: root.id })
105+
const grandchild = yield* sessions.create({ parentID: child.id })
106+
107+
yield* seedUsage(root.id, { cost: 10, input: 100 })
108+
yield* seedUsage(child.id, { cost: 2, input: 20, output: 5, cacheRead: 3 })
109+
yield* seedUsage(grandchild.id, { cost: 0.5, input: 7, reasoning: 4, cacheWrite: 9 })
110+
111+
// The rollup of the task that spawned `child`: the child itself plus its
112+
// descendants — root (the spawner) is deliberately excluded.
113+
const subtree = yield* sessions.descendants(child.id)
114+
const childInfo = yield* sessions.get(child.id)
115+
const rollup = SubagentLimits.aggregateCost([childInfo, ...subtree])
116+
117+
expect(rollup.cost).toBeCloseTo(2.5, 10)
118+
expect(rollup.tokens).toEqual({
119+
input: 27,
120+
output: 5,
121+
reasoning: 4,
122+
cache: { read: 3, write: 9 },
123+
})
124+
}),
125+
)
126+
127+
it.instance("rolls a fan-out subtree (root → A,B → A1) without double counting the spawner", () =>
128+
Effect.gen(function* () {
129+
const sessions = yield* SessionNs.Service
130+
const root = yield* sessions.create({})
131+
const a = yield* sessions.create({ parentID: root.id })
132+
const b = yield* sessions.create({ parentID: root.id })
133+
const a1 = yield* sessions.create({ parentID: a.id })
134+
135+
yield* seedUsage(root.id, { cost: 99, input: 999 })
136+
yield* seedUsage(a.id, { cost: 1, input: 1 })
137+
yield* seedUsage(b.id, { cost: 2, input: 2 })
138+
yield* seedUsage(a1.id, { cost: 4, input: 4 })
139+
140+
// Rollup for the task that spawned the whole subtree from `root`: every
141+
// descendant, but NOT root's own spend (the parent session still bills
142+
// its own cost separately — this is display-only, no double counting).
143+
const subtree = yield* sessions.descendants(root.id)
144+
const rollup = SubagentLimits.aggregateCost(subtree)
145+
146+
expect(rollup.cost).toBe(7)
147+
expect(rollup.tokens.input).toBe(7)
148+
149+
// The root session's own per-session accounting is unchanged by the
150+
// rollup read — the real bill is not touched.
151+
const rootInfo = yield* sessions.get(root.id)
152+
expect(rootInfo.cost).toBe(99)
153+
expect(rootInfo.tokens?.input).toBe(999)
154+
}),
155+
)
156+
})

0 commit comments

Comments
 (0)