Skip to content

Commit 2748eb0

Browse files
Claude Agentclaude
andcommitted
feat(opencode): thread turn-budget pool and ask origin metadata through prompt/tools
Nested-subagent prompt/tools package (design-final §4.3 Ü3 + §4.6): - prompt(): new non-serializable PromptOptions = PromptInput & { turnBudgetPool?: TurnBudget.Pool } (LoopOptions pattern, never rides a schema). A provided pool is reused BY REFERENCE instead of creating a new one, so every nesting level charges the root turn's budget. - handleSubtask: closes the budget gap — the loop's pool now rides the input and ctx.extra (was { bypassAgentCheck, promptOps } only), and the loop callsite threads permissionSessionID + turnBudget, so the @agent/subtask path can no longer silently bypass routing or budget gates. - ctx.ask wiring (SessionTools.resolve + handleSubtask): when an ask is routed away from the asking session, attach originSessionID/originAgent/ originDepth (one Session.lineage walk per resolve; roots skip the walk; a failed walk only omits originDepth — asks never fail on attribution). Unrouted asks stay byte-identical. Tests: new test/session/nested-budget.test.ts pins the resolve ask wiring (stubs, incl. lineage-failure defensive case); prompt.test.ts gains pool reuse/identity captures, an e2e pool-charging case, the subtask pool threading pin, and routed/unrouted subtask ask origin cases. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 0a08e77 commit 2748eb0

5 files changed

Lines changed: 532 additions & 9 deletions

File tree

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 62 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ function isOrphanedInterruptedTool(part: SessionV1.ToolPart) {
8787

8888
export interface Interface {
8989
readonly cancel: (sessionID: SessionID) => Effect.Effect<void>
90-
readonly prompt: (input: PromptInput) => Effect.Effect<SessionV1.WithParts, Image.Error>
90+
readonly prompt: (input: PromptOptions) => Effect.Effect<SessionV1.WithParts, Image.Error>
9191
readonly loop: (input: LoopOptions) => Effect.Effect<SessionV1.WithParts>
9292
readonly shell: (input: ShellInput) => Effect.Effect<SessionV1.WithParts, Session.BusyError>
9393
readonly command: (input: CommandInput) => Effect.Effect<SessionV1.WithParts, Image.Error>
@@ -133,7 +133,7 @@ export const layer = Layer.effect(
133133
return {
134134
cancel: (sessionID: SessionID) => cancel(sessionID),
135135
resolvePromptParts: (template: string) => resolvePromptParts(template),
136-
prompt: (input: PromptInput) => prompt(input).pipe(Effect.catch(Effect.die)),
136+
prompt: (input: PromptOptions) => prompt(input).pipe(Effect.catch(Effect.die)),
137137
// Item 12: expose the session's resolved model through the ops seam (the
138138
// local `currentModel` below already implements the session.model → last
139139
// user-message model → provider default chain).
@@ -252,6 +252,12 @@ export const layer = Layer.effect(
252252
permissionSessionID?: SessionID
253253
session: Session.Info
254254
msgs: SessionV1.WithParts[]
255+
/**
256+
* The loop's shared turn pool (design-final §4.6). Threaded into the
257+
* task tool context (ctx.extra.turnBudget) so the @agent/subtask path
258+
* cannot silently bypass the budget gates of nested spawns.
259+
*/
260+
turnBudget?: TurnBudget.Pool
255261
}) {
256262
const { task, model, lastUser, sessionID, session, msgs } = input
257263
const ctx = yield* InstanceState.context
@@ -312,6 +318,26 @@ export const layer = Layer.effect(
312318
throw error
313319
}
314320

321+
// Mirrors the ctx.ask wiring in tools.ts (design-final §4.3, Ü3): when
322+
// this subtask's asks are routed to another session (the root), attach
323+
// the origin so UIs keep the asker. A failed lineage walk only omits
324+
// originDepth — an ask must never fail on attribution.
325+
const askOrigin = yield* Effect.gen(function* () {
326+
if (input.permissionSessionID === undefined || input.permissionSessionID === session.id) return undefined
327+
const originDepth =
328+
session.parentID === undefined
329+
? 1
330+
: yield* sessions.lineage(session.id).pipe(
331+
Effect.map((chain) => chain.length),
332+
Effect.catch(() => Effect.succeed(undefined)),
333+
)
334+
return {
335+
originSessionID: session.id,
336+
originAgent: taskAgent.name,
337+
...(originDepth !== undefined ? { originDepth } : {}),
338+
}
339+
})
340+
315341
let error: Error | undefined
316342
const taskAbort = new AbortController()
317343
const result = yield* taskTool
@@ -321,7 +347,7 @@ export const layer = Layer.effect(
321347
sessionID,
322348
abort: taskAbort.signal,
323349
callID: part.callID,
324-
extra: { bypassAgentCheck: true, promptOps },
350+
extra: { bypassAgentCheck: true, promptOps, turnBudget: input.turnBudget },
325351
messages: msgs,
326352
metadata: (val: { title?: string; metadata?: Record<string, any> }) =>
327353
Effect.gen(function* () {
@@ -335,6 +361,7 @@ export const layer = Layer.effect(
335361
permission
336362
.ask({
337363
...req,
364+
...(askOrigin ? { metadata: { ...req.metadata, ...askOrigin } } : {}),
338365
sessionID: input.permissionSessionID ?? sessionID,
339366
ruleset: Permission.merge(taskAgent.permission, session.permission ?? []),
340367
})
@@ -1111,9 +1138,9 @@ export const layer = Layer.effect(
11111138
return { info, parts }
11121139
}, Effect.scoped)
11131140

1114-
const prompt: (input: PromptInput) => Effect.Effect<SessionV1.WithParts, Image.Error> = Effect.fn(
1141+
const prompt: (input: PromptOptions) => Effect.Effect<SessionV1.WithParts, Image.Error> = Effect.fn(
11151142
"SessionPrompt.prompt",
1116-
)(function* (input: PromptInput) {
1143+
)(function* (input: PromptOptions) {
11171144
const session = yield* sessions.get(input.sessionID).pipe(Effect.orDie)
11181145
yield* revert.cleanup(session)
11191146
const message = yield* createUserMessage(input)
@@ -1132,7 +1159,12 @@ export const layer = Layer.effect(
11321159
// Item 24: ONE pool per turn. Created here (not in the loop) so re-entrant
11331160
// loop steps share it; threaded by reference into the processor (main-loop
11341161
// charging) and the tool context (workflow runs reserve against it).
1135-
const turnBudget = input.turnBudget !== undefined ? TurnBudget.make(input.turnBudget) : undefined
1162+
// Nested subagents (design-final §4.6): a caller that already holds a
1163+
// pool — the task tool hands down the root turn's — passes it as
1164+
// `turnBudgetPool` and this turn REUSES it instead of creating its own,
1165+
// so every nesting level competes for the same headroom.
1166+
const turnBudget =
1167+
input.turnBudgetPool ?? (input.turnBudget !== undefined ? TurnBudget.make(input.turnBudget) : undefined)
11361168
return yield* loop({
11371169
sessionID: input.sessionID,
11381170
permissionSessionID: input.permissionSessionID,
@@ -1216,7 +1248,19 @@ export const layer = Layer.effect(
12161248
const task = tasks.pop()
12171249

12181250
if (task?.type === "subtask") {
1219-
yield* handleSubtask({ task, model, lastUser, sessionID, session, msgs })
1251+
yield* handleSubtask({
1252+
task,
1253+
model,
1254+
lastUser,
1255+
sessionID,
1256+
session,
1257+
msgs,
1258+
// Nested subagents: the subtask path must see the SAME routing and
1259+
// budget context as a model-initiated task call — the loop's
1260+
// permission routing target and the shared turn pool.
1261+
permissionSessionID: input.permissionSessionID,
1262+
turnBudget: input.turnBudget,
1263+
})
12201264
continue
12211265
}
12221266

@@ -1322,6 +1366,9 @@ export const layer = Layer.effect(
13221366
Effect.provideService(MCP.Service, mcp),
13231367
Effect.provideService(Truncate.Service, truncate),
13241368
Effect.provideService(McpLazyActivation.Service, mcpLazy),
1369+
// Nested subagents: resolve walks the session lineage for the
1370+
// origin attribution of routed permission asks.
1371+
Effect.provideService(Session.Service, sessions),
13251372
)
13261373

13271374
if (lastUser.format?.type === "json_schema") {
@@ -1628,6 +1675,14 @@ const ModelRef = Schema.Struct({
16281675
modelID: ModelV2.ID,
16291676
})
16301677

1678+
// Nested subagents (design-final §4.6): the schema'd PromptInput plus the
1679+
// NON-serializable shared turn pool — the same intersection pattern as
1680+
// LoopOptions below (a live mutable object must never ride a schema). When
1681+
// set, prompt() reuses this pool BY REFERENCE instead of creating one from
1682+
// the schema'd `turnBudget` numbers, so a subagent turn charges its root
1683+
// turn's budget.
1684+
export type PromptOptions = PromptInput & { turnBudgetPool?: TurnBudget.Pool }
1685+
16311686
export const PromptInput = Schema.Struct({
16321687
sessionID: SessionID,
16331688
permissionSessionID: Schema.optional(SessionID),

‎packages/opencode/src/session/tools.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,29 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: {
5555
const registry = yield* ToolRegistry.Service
5656
const mcp = yield* MCP.Service
5757
const truncate = yield* Truncate.Service
58+
const sessions = yield* Session.Service
59+
60+
// Nested subagents route their permission asks to the root session
61+
// (permissionSessionID); without attribution UIs and third-party clients
62+
// would lose WHO asked. Whenever the ask is routed away from this session,
63+
// attach the origin (asking session, its agent, its depth) to the request
64+
// metadata. ONE lineage walk per resolve (roots skip it); a failed walk only
65+
// omits originDepth — an ask must never fail on attribution.
66+
const origin = yield* Effect.gen(function* () {
67+
if (input.permissionSessionID === undefined || input.permissionSessionID === input.session.id) return undefined
68+
const originDepth =
69+
input.session.parentID === undefined
70+
? 1
71+
: yield* sessions.lineage(input.session.id).pipe(
72+
Effect.map((chain) => chain.length),
73+
Effect.catch(() => Effect.succeed(undefined)),
74+
)
75+
return {
76+
originSessionID: input.session.id,
77+
originAgent: input.agent.name,
78+
...(originDepth !== undefined ? { originDepth } : {}),
79+
}
80+
})
5881

5982
const context = (args: Record<string, unknown>, options: ToolExecutionOptions): Tool.Context => ({
6083
sessionID: input.session.id,
@@ -88,6 +111,7 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: {
88111
permission
89112
.ask({
90113
...req,
114+
...(origin ? { metadata: { ...req.metadata, ...origin } } : {}),
91115
sessionID: input.permissionSessionID ?? input.session.id,
92116
tool: { messageID: input.processor.message.id, callID: options.toolCallId },
93117
ruleset: Permission.merge(input.agent.permission, input.session.permission ?? []),
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
import { describe, expect } from "bun:test"
2+
import { Effect, Layer, Schema } from "effect"
3+
import type { ToolExecutionOptions } from "ai"
4+
import type { Agent } from "@/agent/agent"
5+
import { MCP } from "@/mcp"
6+
import { Permission } from "@/permission"
7+
import { Plugin } from "@/plugin"
8+
import type { Provider } from "@/provider/provider"
9+
import { ToolRegistry } from "@/tool/registry"
10+
import { Truncate } from "@/tool/truncate"
11+
import type { Tool } from "@/tool/tool"
12+
import { PermissionV1 } from "@opencode-ai/core/v1/permission"
13+
import { Session } from "@/session/session"
14+
import type { SessionProcessor } from "@/session/processor"
15+
import type { SessionV1 } from "@opencode-ai/core/v1/session"
16+
import type { TaskPromptOps } from "@/tool/task"
17+
import { SessionTools } from "@/session/tools"
18+
import { SubagentLimits } from "@/session/subagent-limits"
19+
import { McpLazyActivation } from "@/session/mcp-lazy"
20+
import { MessageID, SessionID } from "@/session/schema"
21+
import { testEffect } from "../lib/effect"
22+
23+
// Design-final §4.3 (Ü3): permission asks of nested subagents are routed to
24+
// the root session (permissionSessionID). Without attribution, UIs and
25+
// third-party clients lose WHO asked — so the ctx.ask wiring in
26+
// SessionTools.resolve attaches origin metadata (originSessionID /
27+
// originAgent / originDepth) whenever the ask is routed away from the asking
28+
// session. These tests pin EXACTLY that wiring; the real lineage walk is
29+
// covered by session-lineage.test.ts, so Session.Service is a stub here.
30+
const it = testEffect(Layer.mergeAll(McpLazyActivation.defaultLayer))
31+
32+
const ROOT = SessionID.make("ses_origin_root")
33+
const MID = SessionID.make("ses_origin_mid")
34+
const LEAF = SessionID.make("ses_origin_leaf")
35+
36+
// A registry tool whose execute immediately asks — the seam under test.
37+
const probeTool: Tool.Def = {
38+
id: "origin_probe",
39+
description: "asks for permission and returns",
40+
parameters: Schema.Struct({}),
41+
jsonSchema: { type: "object", properties: {} },
42+
execute: (_args, ctx) =>
43+
Effect.gen(function* () {
44+
yield* ctx.ask({ permission: "origin_probe", patterns: ["p"], always: [], metadata: { base: "keep" } })
45+
return { title: "probe", metadata: {}, output: "ok" }
46+
}),
47+
}
48+
49+
const registryStub = ToolRegistry.Service.of({
50+
tools: () => Effect.succeed([probeTool]),
51+
} as unknown as ToolRegistry.Interface)
52+
53+
const pluginStub = Plugin.Service.of({
54+
trigger: (() => Effect.succeed({})) as unknown as Plugin.Interface["trigger"],
55+
} as unknown as Plugin.Interface)
56+
57+
const mcpStub = MCP.Service.of({
58+
tools: () => Effect.succeed({}),
59+
} as unknown as MCP.Interface)
60+
61+
const truncateStub = Truncate.Service.of({
62+
cleanup: () => Effect.void,
63+
write: () => Effect.succeed("/tmp/unused"),
64+
output: (text: string) => Effect.succeed({ content: text, truncated: false as const }),
65+
limits: () => Effect.succeed({ maxLines: 2000, maxBytes: 51200 }),
66+
} as unknown as Truncate.Interface)
67+
68+
function capturePermission() {
69+
const asks: PermissionV1.AskInput[] = []
70+
const stub = Permission.Service.of({
71+
ask: (input: PermissionV1.AskInput) => Effect.sync(() => void asks.push(input)),
72+
reply: () => Effect.void,
73+
list: () => Effect.succeed([]),
74+
} as unknown as Permission.Interface)
75+
return { asks, stub }
76+
}
77+
78+
/** Session.Service stub: only `lineage` is consumed by the wiring under test. */
79+
const sessionStub = (lineage?: Session.Interface["lineage"]) =>
80+
Session.Service.of({
81+
lineage:
82+
lineage ??
83+
(() => Effect.die(new Error("lineage must not be walked for this resolve"))),
84+
} as unknown as Session.Interface)
85+
86+
/** A lineage chain as `Session.lineage` returns it: self → root. */
87+
const chainOf = (...ids: SessionID[]) => ids.map((id) => ({ id }) as Session.Info)
88+
89+
const fakeModel = { providerID: "test", api: { id: "test-model" } } as Provider.Model
90+
91+
function resolveInput(session: { id: SessionID; parentID?: SessionID }, permissionSessionID?: SessionID) {
92+
return {
93+
agent: { name: "build", mode: "primary", permission: [], options: {} } as Agent.Info,
94+
model: fakeModel,
95+
session: session as Session.Info,
96+
permissionSessionID,
97+
processor: {
98+
message: { id: MessageID.make("msg_origin_test") } as SessionV1.Assistant,
99+
updateToolCall: () => Effect.succeed(undefined),
100+
completeToolCall: () => Effect.void,
101+
} as unknown as Pick<SessionProcessor.Handle, "message" | "updateToolCall" | "completeToolCall">,
102+
bypassAgentCheck: false,
103+
messages: [] as SessionV1.WithParts[],
104+
promptOps: {} as TaskPromptOps,
105+
}
106+
}
107+
108+
const provideStubs =
109+
(permission: Permission.Service["Service"], session: Session.Service["Service"]) =>
110+
<A, E, R>(self: Effect.Effect<A, E, R>) =>
111+
self.pipe(
112+
Effect.provideService(Plugin.Service, pluginStub),
113+
Effect.provideService(Permission.Service, permission),
114+
Effect.provideService(ToolRegistry.Service, registryStub),
115+
Effect.provideService(MCP.Service, mcpStub),
116+
Effect.provideService(Truncate.Service, truncateStub),
117+
Effect.provideService(Session.Service, session),
118+
)
119+
120+
const callOptions = { toolCallId: "call_origin_test", messages: [] } as unknown as ToolExecutionOptions
121+
122+
const runProbe = (
123+
input: ReturnType<typeof resolveInput>,
124+
permission: Permission.Service["Service"],
125+
session: Session.Service["Service"],
126+
) =>
127+
Effect.gen(function* () {
128+
const tools = yield* SessionTools.resolve(input)
129+
expect(tools["origin_probe"]).toBeDefined()
130+
yield* Effect.promise(() => Promise.resolve(tools["origin_probe"].execute!({}, callOptions)))
131+
}).pipe(provideStubs(permission, session))
132+
133+
describe("SessionTools.resolve ask origin metadata", () => {
134+
it.instance("routed ask from depth 3 carries originSessionID/originAgent/originDepth", () =>
135+
Effect.gen(function* () {
136+
const { asks, stub } = capturePermission()
137+
const session = sessionStub(() => Effect.succeed(chainOf(LEAF, MID, ROOT)))
138+
yield* runProbe(resolveInput({ id: LEAF, parentID: MID }, ROOT), stub, session)
139+
expect(asks).toHaveLength(1)
140+
const ask = asks[0]!
141+
expect(ask.sessionID).toBe(ROOT)
142+
// base request metadata is preserved, origin fields are added
143+
expect(ask.metadata.base).toBe("keep")
144+
expect(ask.metadata.originSessionID).toBe(LEAF)
145+
expect(ask.metadata.originAgent).toBe("build")
146+
expect(ask.metadata.originDepth).toBe(3)
147+
}),
148+
)
149+
150+
it.instance("unrouted ask (no permissionSessionID) stays byte-identical: no origin fields, no walk", () =>
151+
Effect.gen(function* () {
152+
const { asks, stub } = capturePermission()
153+
yield* runProbe(resolveInput({ id: LEAF, parentID: MID }), stub, sessionStub())
154+
expect(asks).toHaveLength(1)
155+
const ask = asks[0]!
156+
expect(ask.sessionID).toBe(LEAF)
157+
expect(ask.metadata).toEqual({ base: "keep" })
158+
}),
159+
)
160+
161+
it.instance("permissionSessionID equal to the session id adds no origin fields", () =>
162+
Effect.gen(function* () {
163+
const { asks, stub } = capturePermission()
164+
yield* runProbe(resolveInput({ id: LEAF, parentID: MID }, LEAF), stub, sessionStub())
165+
expect(asks).toHaveLength(1)
166+
expect(asks[0]!.sessionID).toBe(LEAF)
167+
expect(asks[0]!.metadata).toEqual({ base: "keep" })
168+
}),
169+
)
170+
171+
it.instance("routed ask from a root session reports depth 1 without a lineage walk", () =>
172+
Effect.gen(function* () {
173+
const { asks, stub } = capturePermission()
174+
// parentID undefined ⇒ depth 1 by definition; the stub dies if walked.
175+
yield* runProbe(resolveInput({ id: LEAF }, ROOT), stub, sessionStub())
176+
expect(asks).toHaveLength(1)
177+
expect(asks[0]!.metadata.originSessionID).toBe(LEAF)
178+
expect(asks[0]!.metadata.originDepth).toBe(1)
179+
}),
180+
)
181+
182+
it.instance("a failed lineage walk omits originDepth but never fails the ask", () =>
183+
Effect.gen(function* () {
184+
const { asks, stub } = capturePermission()
185+
const session = sessionStub(() => Effect.fail(SubagentLimits.lineageError({ sessionID: LEAF })))
186+
yield* runProbe(resolveInput({ id: LEAF, parentID: MID }, ROOT), stub, session)
187+
expect(asks).toHaveLength(1)
188+
const ask = asks[0]!
189+
expect(ask.sessionID).toBe(ROOT)
190+
expect(ask.metadata.originSessionID).toBe(LEAF)
191+
expect(ask.metadata.originAgent).toBe("build")
192+
expect("originDepth" in ask.metadata).toBe(false)
193+
}),
194+
)
195+
})

0 commit comments

Comments
 (0)