fix(hooks): consolidate after_tool_call context + single-fire behavior (#32201)

* fix(hooks): deduplicate after_tool_call hook in embedded runs

(cherry picked from commit c129a1a74b)

* fix(hooks): propagate sessionKey in after_tool_call context

The after_tool_call hook in handleToolExecutionEnd was passing
`sessionKey: undefined` in the ToolContext, even though the value is
available on ctx.params. This broke plugins that need session context
in after_tool_call handlers (e.g., for per-session audit trails or
security logging).

- Add `sessionKey` to the `ToolHandlerParams` Pick type
- Pass `ctx.params.sessionKey` through to the hook context
- Add test assertion to prevent regression

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
(cherry picked from commit b7117384fc)

* fix(hooks): thread agentId through to after_tool_call hook context

Follow-up to #30511 — the after_tool_call hook context was passing
`agentId: undefined` because SubscribeEmbeddedPiSessionParams did not
carry the agent identity. This threads sessionAgentId (resolved in
attempt.ts) through the session params into the tool handler context,
giving plugins accurate agent-scoped context for both before_tool_call
and after_tool_call hooks.

Changes:
- Add `agentId?: string` to SubscribeEmbeddedPiSessionParams
- Add "agentId" to ToolHandlerParams Pick type
- Pass `agentId: sessionAgentId` at the subscribeEmbeddedPiSession()
  call site in attempt.ts
- Wire ctx.params.agentId into the after_tool_call hook context
- Update tests to assert agentId propagation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
(cherry picked from commit aad01edd3e)

* changelog: credit after_tool_call hook contributors

* Update CHANGELOG.md

* agents: preserve adjusted params until tool end

* agents: emit after_tool_call with adjusted args

* tests: cover adjusted after_tool_call params

* tests: align adapter after_tool_call expectation

---------

Co-authored-by: jbeno <jim@jimbeno.net>
Co-authored-by: scoootscooob <zhentongfan@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Vincent Koc
2026-03-02 14:33:37 -08:00
committed by GitHub
parent f9cbcfca0d
commit 44183c6eb1
9 changed files with 338 additions and 127 deletions

View File

@@ -5,7 +5,7 @@ import { toToolDefinitions } from "./pi-tool-definition-adapter.js";
const hookMocks = vi.hoisted(() => ({
runner: {
hasHooks: vi.fn((_: string) => false),
hasHooks: vi.fn((_: string) => true),
runAfterToolCall: vi.fn(async () => {}),
},
isToolWrappedWithBeforeToolCallHook: vi.fn(() => false),
@@ -39,31 +39,6 @@ function createReadTool() {
type ToolExecute = ReturnType<typeof toToolDefinitions>[number]["execute"];
const extensionContext = {} as Parameters<ToolExecute>[4];
function enableAfterToolCallHook() {
hookMocks.runner.hasHooks.mockImplementation((name: string) => name === "after_tool_call");
}
async function executeReadTool(callId: string) {
const defs = toToolDefinitions([createReadTool()]);
const def = defs[0];
if (!def) {
throw new Error("missing tool definition");
}
const execute = (...args: Parameters<(typeof defs)[0]["execute"]>) => def.execute(...args);
return await execute(callId, { path: "/tmp/file" }, undefined, undefined, extensionContext);
}
function expectReadAfterToolCallPayload(result: Awaited<ReturnType<typeof executeReadTool>>) {
expect(hookMocks.runner.runAfterToolCall).toHaveBeenCalledWith(
{
toolName: "read",
params: { mode: "safe" },
result,
},
{ toolName: "read" },
);
}
describe("pi tool definition adapter after_tool_call", () => {
beforeEach(() => {
hookMocks.runner.hasHooks.mockClear();
@@ -80,32 +55,21 @@ describe("pi tool definition adapter after_tool_call", () => {
}));
});
it("dispatches after_tool_call once on successful adapter execution", async () => {
enableAfterToolCallHook();
hookMocks.runBeforeToolCallHook.mockResolvedValue({
blocked: false,
params: { mode: "safe" },
});
const result = await executeReadTool("call-ok");
// Regression guard: after_tool_call is handled exclusively by
// handleToolExecutionEnd in the subscription handler to prevent
// duplicate invocations in embedded runs.
it("does not fire after_tool_call from the adapter (handled by subscription handler)", async () => {
const defs = toToolDefinitions([createReadTool()]);
const def = defs[0];
if (!def) {
throw new Error("missing tool definition");
}
await def.execute("call-ok", { path: "/tmp/file" }, undefined, undefined, extensionContext);
expect(result.details).toMatchObject({ ok: true });
expect(hookMocks.runner.runAfterToolCall).toHaveBeenCalledTimes(1);
expectReadAfterToolCallPayload(result);
expect(hookMocks.runner.runAfterToolCall).not.toHaveBeenCalled();
});
it("uses wrapped-tool adjusted params for after_tool_call payload", async () => {
enableAfterToolCallHook();
hookMocks.isToolWrappedWithBeforeToolCallHook.mockReturnValue(true);
hookMocks.consumeAdjustedParamsForToolCall.mockReturnValue({ mode: "safe" } as unknown);
const result = await executeReadTool("call-ok-wrapped");
expect(result.details).toMatchObject({ ok: true });
expect(hookMocks.runBeforeToolCallHook).not.toHaveBeenCalled();
expectReadAfterToolCallPayload(result);
});
it("dispatches after_tool_call once on adapter error with normalized tool name", async () => {
enableAfterToolCallHook();
it("does not fire after_tool_call from the adapter on error", async () => {
const tool = {
name: "bash",
label: "Bash",
@@ -121,31 +85,27 @@ describe("pi tool definition adapter after_tool_call", () => {
if (!def) {
throw new Error("missing tool definition");
}
const execute = (...args: Parameters<(typeof defs)[0]["execute"]>) => def.execute(...args);
const result = await execute("call-err", { cmd: "ls" }, undefined, undefined, extensionContext);
await def.execute("call-err", { cmd: "ls" }, undefined, undefined, extensionContext);
expect(result.details).toMatchObject({
status: "error",
tool: "exec",
error: "boom",
});
expect(hookMocks.runner.runAfterToolCall).toHaveBeenCalledTimes(1);
expect(hookMocks.runner.runAfterToolCall).toHaveBeenCalledWith(
{
toolName: "exec",
params: { cmd: "ls" },
error: "boom",
},
{ toolName: "exec" },
);
expect(hookMocks.runner.runAfterToolCall).not.toHaveBeenCalled();
});
it("does not break execution when after_tool_call hook throws", async () => {
enableAfterToolCallHook();
hookMocks.runner.runAfterToolCall.mockRejectedValue(new Error("hook failed"));
const result = await executeReadTool("call-ok2");
it("does not consume adjusted params in adapter for wrapped tools", async () => {
hookMocks.isToolWrappedWithBeforeToolCallHook.mockReturnValue(true);
const defs = toToolDefinitions([createReadTool()]);
const def = defs[0];
if (!def) {
throw new Error("missing tool definition");
}
await def.execute(
"call-wrapped",
{ path: "/tmp/file" },
undefined,
undefined,
extensionContext,
);
expect(result.details).toMatchObject({ ok: true });
expect(hookMocks.runner.runAfterToolCall).toHaveBeenCalledTimes(1);
expect(hookMocks.runBeforeToolCallHook).not.toHaveBeenCalled();
expect(hookMocks.consumeAdjustedParamsForToolCall).not.toHaveBeenCalled();
});
});