Skip to content

Commit bef204c

Browse files
committed
test(session): regression coverage for anomalyco#5894 (subagent tool calls now fire plugin hooks)
Adds two tests proving tool.execute.before/after fire for tool calls made from within a subagent's own session, scoped to the subagent's own sessionID — the exact scenario reported in anomalyco#5894 as broken. Both pass on current main. No source changes: the plugin hook invocation appears to already fire correctly for subagent tool calls, foreground and background, but there was no regression test locking in the behavior.
1 parent 3b18c64 commit bef204c

3 files changed

Lines changed: 208 additions & 0 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { calls } from "./tool-hook-recorder"
2+
3+
// A real v1 server plugin, loaded by opencode's actual PluginLoader through
4+
// a `file://` specifier (see test/fixture/agent-plugin.ts for the same
5+
// loading pattern). This mirrors the reproduction plugin from
6+
// https://github.com/anomalyco/opencode/issues/5894 as closely as possible:
7+
// a plugin registering `tool.execute.before` / `tool.execute.after` and
8+
// recording every tool call it sees, including ones made by a subagent.
9+
export default async () => ({
10+
"tool.execute.before": async (input: { tool: string; sessionID: string }) => {
11+
calls.push({ hook: "before", tool: input.tool, sessionID: input.sessionID })
12+
},
13+
"tool.execute.after": async (input: { tool: string; sessionID: string }) => {
14+
calls.push({ hook: "after", tool: input.tool, sessionID: input.sessionID })
15+
},
16+
})
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Shared in-process recorder used to prove that a *real* file-based plugin
2+
// (loaded through the actual PluginLoader / Plugin.node, not a Layer.mock)
3+
// sees `tool.execute.before` / `tool.execute.after` for tool calls made from
4+
// inside a subagent's own session — the exact repro from
5+
// https://github.com/anomalyco/opencode/issues/5894.
6+
//
7+
// The plugin file (`tool-hook-recorder-plugin.ts`) is loaded by the real
8+
// PluginLoader via a `file://` URL, which resolves to this same module in
9+
// the module cache (same process, same path) — so pushing into `calls` here
10+
// is visible to the test that imports this module directly.
11+
export type RecordedCall = { hook: "before" | "after"; tool: string; sessionID: string }
12+
13+
export const calls: RecordedCall[] = []
14+
15+
export function reset() {
16+
calls.length = 0
17+
}

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

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ import { EventV2Bridge } from "@/event-v2-bridge"
88
import { expect } from "bun:test"
99
import { Cause, Deferred, Duration, Effect, Exit, Fiber, Layer } from "effect"
1010
import path from "path"
11+
import { pathToFileURL } from "url"
12+
import { Global } from "@opencode-ai/core/global"
13+
import * as ToolHookRecorder from "../fixture/tool-hook-recorder"
14+
import { markPluginDependenciesReady } from "../fixture/plugin"
1115
import { fileURLToPath } from "url"
1216
import { NamedError } from "@opencode-ai/core/util/error"
1317
import { Agent as AgentSvc } from "../../src/agent/agent"
@@ -239,7 +243,45 @@ function makeHttpNoLLMServer(input?: { mcpInstructions?: MCP.ServerInstructions[
239243
return makePrompt(input)
240244
}
241245

246+
// Records every `tool.execute.before` / `tool.execute.after` invocation seen
247+
// by any session (parent or subagent) for the lifetime of a test. Regression
248+
// coverage for https://github.com/anomalyco/opencode/issues/5894 (plugin
249+
// hooks not firing for tool calls made from within a subagent) relies on
250+
// this to prove which session a given tool call's hook fired for.
251+
type RecordedHook = { hook: "before" | "after"; tool: string; sessionID: string }
252+
const pluginHookCalls: RecordedHook[] = []
253+
const pluginHooksNode = LayerNode.make({
254+
service: Plugin.Service,
255+
layer: Layer.mock(Plugin.Service, {
256+
trigger: (((name: string, input: { tool: string; sessionID: string }, output: unknown) =>
257+
Effect.sync(() => {
258+
if (name === "tool.execute.before" || name === "tool.execute.after")
259+
pluginHookCalls.push({
260+
hook: name === "tool.execute.before" ? "before" : "after",
261+
tool: input.tool,
262+
sessionID: input.sessionID,
263+
})
264+
return output
265+
})) as unknown) as Plugin.Interface["trigger"],
266+
list: () => Effect.succeed([]),
267+
init: () => Effect.void,
268+
}),
269+
deps: [],
270+
})
271+
272+
function makeHttpWithPluginHooks(input?: { mcpInstructions?: MCP.ServerInstructions[] }) {
273+
const root = LayerNode.group([promptRoot, testLLMServerNode])
274+
return LayerNode.compile(root, [
275+
[SessionSummary.node, summary],
276+
[LSP.node, lsp],
277+
[MCP.node, makeMcp(input?.mcpInstructions)],
278+
[RuntimeFlags.node, runtimeFlags],
279+
[Plugin.node, pluginHooksNode],
280+
])
281+
}
282+
242283
const it = testEffect(makeHttp())
284+
const withPluginHooks = testEffect(makeHttpWithPluginHooks())
243285
const noLLMServer = testEffect(makeHttpNoLLMServer())
244286
const raceNoLLMServer = testEffect(makeHttpNoLLMServer({ processor: "blocking" }))
245287
const withMcpInstructions = testEffect(
@@ -303,6 +345,20 @@ function providerCfg(url: string) {
303345
}
304346
}
305347

348+
// Same as providerCfg, but also registers a *real* file-based plugin
349+
// (loaded through the actual PluginLoader / Plugin.node, no mocking at all)
350+
// that records every tool.execute.before/after call it observes. Used for
351+
// end-to-end regression coverage of #5894.
352+
const toolHookRecorderPluginUrl = pathToFileURL(
353+
path.join(import.meta.dir, "..", "fixture", "tool-hook-recorder-plugin.ts"),
354+
).href
355+
function providerCfgWithRealPlugin(url: string) {
356+
return {
357+
...providerCfg(url),
358+
plugin: [toolHookRecorderPluginUrl],
359+
}
360+
}
361+
306362
const writeText = Effect.fn("test.writeText")(function* (file: string, text: string) {
307363
const fs = yield* FSUtil.Service
308364
yield* fs.writeWithDirs(file, text)
@@ -1054,6 +1110,125 @@ it.instance(
10541110
10_000,
10551111
)
10561112

1113+
withPluginHooks.instance(
1114+
"subagent tool calls fire tool.execute.before/after under the subagent's own session (regression for #5894)",
1115+
() =>
1116+
Effect.gen(function* () {
1117+
pluginHookCalls.length = 0
1118+
const { llm } = yield* useServerConfig(providerCfg)
1119+
const prompt = yield* SessionPrompt.Service
1120+
const sessions = yield* Session.Service
1121+
const registry = yield* ToolRegistry.Service
1122+
const { read } = yield* registry.named()
1123+
const originalRead = read.execute
1124+
read.execute = (_args, _ctx) =>
1125+
Effect.succeed({
1126+
title: "stub",
1127+
metadata: { preview: "", truncated: false, loaded: [] },
1128+
output: "stubbed read output",
1129+
})
1130+
yield* Effect.addFinalizer(() => Effect.sync(() => void (read.execute = originalRead)))
1131+
1132+
const chat = yield* sessions.create({
1133+
title: "Pinned",
1134+
permission: [{ permission: "*", pattern: "*", action: "allow" }],
1135+
})
1136+
1137+
// Parent turn: delegate to a "general" subagent via the task tool.
1138+
yield* llm.tool("task", {
1139+
description: "inspect bug",
1140+
prompt: "look into the cache key path",
1141+
subagent_type: "general",
1142+
})
1143+
// Subagent turn: the subagent itself calls a regular tool.
1144+
yield* llm.tool("read", { filePath: "/tmp/whatever.txt" })
1145+
// Subagent's final turn after its own tool call completes.
1146+
yield* llm.text("subagent done")
1147+
// Parent's final turn after the task tool completes.
1148+
yield* llm.text("done")
1149+
1150+
yield* user(chat.id, "hello")
1151+
yield* prompt.loop({ sessionID: chat.id })
1152+
1153+
const kids = yield* sessions.children(chat.id)
1154+
expect(kids).toHaveLength(1)
1155+
const childSessionID = kids[0]!.id
1156+
1157+
const beforeToolsBySession = new Map<string, string[]>()
1158+
for (const call of pluginHookCalls) {
1159+
if (call.hook !== "before") continue
1160+
const list = beforeToolsBySession.get(call.sessionID) ?? []
1161+
list.push(call.tool)
1162+
beforeToolsBySession.set(call.sessionID, list)
1163+
}
1164+
1165+
// The hook must fire for the "task" tool call made by the parent...
1166+
expect(beforeToolsBySession.get(chat.id)).toEqual(expect.arrayContaining(["task"]))
1167+
// ...AND for the "read" tool call made by the subagent itself, under
1168+
// the subagent's OWN sessionID. This is exactly the scenario reported
1169+
// in #5894 ("Plugin hooks don't intercept subagent tool calls"): if
1170+
// that regression were present, this list would be empty even though
1171+
// the subagent's read call completed successfully.
1172+
expect(beforeToolsBySession.get(childSessionID)).toEqual(expect.arrayContaining(["read"]))
1173+
}),
1174+
10_000,
1175+
)
1176+
1177+
it.instance(
1178+
"a real file-based plugin (no mocking) sees subagent tool calls too (end-to-end regression for #5894)",
1179+
() =>
1180+
Effect.gen(function* () {
1181+
ToolHookRecorder.reset()
1182+
const { directory: dir } = yield* TestInstance
1183+
yield* Effect.promise(() => markPluginDependenciesReady(path.join(dir, ".opencode")))
1184+
yield* Effect.promise(() => markPluginDependenciesReady(Global.Path.config))
1185+
const { llm } = yield* useServerConfig(providerCfgWithRealPlugin)
1186+
const prompt = yield* SessionPrompt.Service
1187+
const sessions = yield* Session.Service
1188+
const registry = yield* ToolRegistry.Service
1189+
const { read } = yield* registry.named()
1190+
const originalRead = read.execute
1191+
read.execute = (_args, _ctx) =>
1192+
Effect.succeed({
1193+
title: "stub",
1194+
metadata: { preview: "", truncated: false, loaded: [] },
1195+
output: "stubbed read output",
1196+
})
1197+
yield* Effect.addFinalizer(() => Effect.sync(() => void (read.execute = originalRead)))
1198+
1199+
const chat = yield* sessions.create({
1200+
title: "Pinned",
1201+
permission: [{ permission: "*", pattern: "*", action: "allow" }],
1202+
})
1203+
1204+
yield* llm.tool("task", {
1205+
description: "inspect bug",
1206+
prompt: "look into the cache key path",
1207+
subagent_type: "general",
1208+
})
1209+
yield* llm.tool("read", { filePath: "/tmp/whatever.txt" })
1210+
yield* llm.text("subagent done")
1211+
yield* llm.text("done")
1212+
1213+
yield* user(chat.id, "hello")
1214+
yield* prompt.loop({ sessionID: chat.id })
1215+
1216+
const kids = yield* sessions.children(chat.id)
1217+
expect(kids).toHaveLength(1)
1218+
const childSessionID = kids[0]!.id
1219+
1220+
const readCallsForChild = ToolHookRecorder.calls.filter(
1221+
(call) => call.hook === "before" && call.tool === "read" && call.sessionID === childSessionID,
1222+
)
1223+
// A real plugin loaded via the actual PluginLoader (not Layer.mock)
1224+
// must still see the subagent's own "read" tool call, scoped to the
1225+
// subagent's sessionID. This removes any doubt that the Layer.mock in
1226+
// the previous test was masking a real-world loading difference.
1227+
expect(readCallsForChild.length).toBeGreaterThan(0)
1228+
}),
1229+
10_000,
1230+
)
1231+
10571232
it.instance(
10581233
"loop sets status to busy then idle",
10591234
() =>

0 commit comments

Comments
 (0)