Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(agent): unify webhook controls under toolCall (#20709)

Bryan8f3eec2c3af5
diff --git a/.agents/skills/agent-runtime-hooks/SKILL.md b/.agents/skills/agent-runtime-hooks/SKILL.md
index dd182eef9d6..320a9b49bfb 100644
--- a/.agents/skills/agent-runtime-hooks/SKILL.md
+++ b/.agents/skills/agent-runtime-hooks/SKILL.md
@@ -102,10 +102,10 @@ const hook: AgentHook = {
- `matcher` is a regex against `${identifier}/${apiName}`, supported only on tool events. Omitted, empty, or `*` matches all tools.
- Header environment templates resolve only at send time from `allowedEnvVars`; persist templates, never resolved secrets.
- Notifications ignore response content and may return HTTP 204.
-- `beforeToolCall` with `responseHandling: 'toolCall'` awaits an HTTP control response before tool execution. Return HTTP 200 JSON with `{ "decision": "allow" }` or `{ "decision": "deny", "reason": "禁止执行该操作" }`. The type is `{ decision: 'allow' } | { decision: 'deny'; reason?: string }`; a deny without reason uses `Blocked by beforeToolCall hook.`. Denials preserve the reason in the tool result/card with classification `hook_denied`.
+- `beforeToolCall` with `responseHandling: 'toolCall'` awaits an optional HTTP decision before tool execution. Return HTTP 2xx JSON with `{ "decision": "allow" }` or `{ "decision": "deny", "reason": "禁止执行该操作" }` to intervene. The type is `{ decision: 'allow' } | { decision: 'deny'; reason?: string }`; a deny without reason uses `Blocked by beforeToolCall hook.`. Denials preserve the reason in the tool result/card with classification `hook_denied`.
- `afterToolCall` also accepts `responseHandling: 'toolCall'`. It synchronously checks the full request/result before archival and model consumption; deny substitutes a neutral result and never echoes receiver reasons. It does not undo tool side effects, retries, or charges. See [the result-control contract](../../../docs/development/agent-tool-result-hooks.md) for deferred completions and runtime boundaries.
-- Environment response modes preserve compatibility: `toolCall` controls only before; opt into `toolResult` for after-only or `toolCallAndResult` for both. The per-hook decision protocol remains `responseHandling: 'toolCall'`.
-- Empty bodies, HTTP 204 or other non-200 status, invalid JSON, missing/invalid decisions, and responses containing only the old nested `hookSpecificOutput` format are protocol errors. They follow the control hook's `onError: 'continue' | 'block'` policy (default `continue`); an empty response is never an allow decision.
+- Environment response modes are `ignore` (default notifications) and `toolCall` (optional decisions for both before and after). Only subscribed events are enabled. Replace removed `toolResult`/`toolCallAndResult` values with `toolCall`; use the events list to select after-only checking. Existing after responses with a valid decision now control results.
+- HTTP 204, empty successful bodies, invalid JSON, and JSON without a top-level decision (including arrays, scalars, null, or only the old nested `hookSpecificOutput`) are notification responses, even with `onError: 'block'`. Continue checking subsequent hooks; do not treat a notification as permission to skip later policies. Explicit invalid decisions, non-2xx status, oversized bodies, invalid UTF-8, network failures, and timeouts follow `onError: 'continue' | 'block'` (default `continue`). Cancellation never grants permission.
- Extra response fields are allowed and discarded. Only `decision` and a deny's optional string `reason` are consumed; `updatedInput`/`additionalContext` do not change tool arguments or conversation context.
- Configuration: `packages/types/src/agentHook.ts`; response parsing: `packages/types/src/agentHookResponse.ts`; HTTP delivery: `apps/server/src/services/agentRuntime/hooks/httpWebhook.ts`.
diff --git a/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts
index 1b44b15121d..b42c01ddf78 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts
@@ -326,7 +326,7 @@ describe('afterToolCall control pipeline', () => {
'uses onError=%s for invalid responses and never leaks response text',
async (onError) => {
const fixture = setup([control('control', onError)]);
- fetchHook.mockResolvedValue(new Response(JSON.stringify({ invalid: secret })));
+ fetchHook.mockResolvedValue(new Response(JSON.stringify({ decision: secret })));
const result = await fixture.step();
expect(fixture.execute).toHaveBeenCalledTimes(1);
expect(fixture.rows[0].content).toBe(
@@ -536,7 +536,7 @@ describe('afterToolCall control pipeline', () => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/environment');
vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');
vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
const fixture = setup([]);
fixture.rows.push({
id: 'protected-row',
@@ -719,13 +719,13 @@ describe('afterToolCall control pipeline', () => {
]);
});
- it.each(['toolCall', 'toolResult', 'toolCallAndResult'] as const)(
- 'applies the explicit environment mode %s at runtime',
- async (mode) => {
+ it.each(['beforeToolCall', 'afterToolCall', 'beforeToolCall,afterToolCall'])(
+ 'uses toolCall to control selected events %s at runtime',
+ async (events) => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/env');
vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-token');
- vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'beforeToolCall,afterToolCall');
- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', mode);
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', events);
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');
fetchHook.mockImplementation(async (_url, init) =>
response(JSON.parse(init.body).hookType === 'afterToolCall' ? 'deny' : 'allow'),
@@ -734,13 +734,28 @@ describe('afterToolCall control pipeline', () => {
await fixture.step();
expect(fixture.execute).toHaveBeenCalledTimes(1);
expect(fixture.rows[0].content).toBe(
- mode === 'toolCall' ? 'executed' : BLOCKED_TOOL_RESULT_CONTENT,
+ events.includes('afterToolCall') ? BLOCKED_TOOL_RESULT_CONTENT : 'executed',
);
- await vi.waitFor(() => expect(fetchHook).toHaveBeenCalledTimes(2));
- expect(fetchHook.mock.calls.map(([, init]) => JSON.parse(init.body).hookType)).toEqual([
- 'beforeToolCall',
- 'afterToolCall',
- ]);
+ expect(fetchHook.mock.calls.map(([, init]) => JSON.parse(init.body).hookType)).toEqual(
+ events.split(','),
+ );
+ },
+ );
+
+ it.each(['', 'not JSON', '{"decision":', '{}'])(
+ 'executes and publishes normally when both hooks respond with notification body %j',
+ async (body) => {
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/env');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-token');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'beforeToolCall,afterToolCall');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');
+ fetchHook.mockImplementation(async () => new Response(body));
+ const fixture = setup([]);
+ await fixture.step();
+ expect(fixture.execute).toHaveBeenCalledTimes(1);
+ expect(fixture.rows[0].content).toBe('executed');
+ expect(fetchHook).toHaveBeenCalledTimes(2);
},
);
diff --git a/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts
index c740c5f57d0..7b0bc571289 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts
@@ -256,7 +256,7 @@ describe('beforeToolCall control pipeline', () => {
'preserves the $failure rejection reason in a new $mode tool card',
async ({ mode, failure, reason }) => {
fetchHook.mockImplementation(async () =>
- failure === 'deny' ? response('deny', reason) : new Response('invalid JSON'),
+ failure === 'deny' ? response('deny', reason) : new Response('{"decision":"invalid"}'),
);
const fixture = setup([control('control', 'block')]);
const result =
@@ -549,22 +549,10 @@ describe('beforeToolCall control pipeline', () => {
describe.each([false, true])('control errors, queue=%s', (queue) => {
it.each([
- { body: '', status: 200 },
- { body: null, status: 204 },
- { body: '{}', status: 200 },
- { body: 'not JSON', status: 200 },
- { body: '{"reason":"missing decision"}', status: 200 },
{ body: '{"decision":"ask"}', status: 200 },
{ body: '{"decision":"deny","reason":42}', status: 200 },
- { body: '{"decision":"allow"}', status: 201 },
{ body: '{"decision":"allow"}', status: 400 },
{ body: '{"decision":"allow"}', status: 500 },
- ...['allow', 'deny'].map((decision) => ({
- body: JSON.stringify({
- hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: decision },
- }),
- status: 200,
- })),
])('applies both onError policies to response %#', async ({ body, status }) => {
queueMode.mockReturnValue(queue);
fetchHook.mockImplementation(async () => new Response(body, { status }));
@@ -581,6 +569,22 @@ describe('beforeToolCall control pipeline', () => {
expect(continued.execute).toHaveBeenCalledTimes(1);
expect(continued.execute.mock.calls[0][0].arguments).toBe('{"path":"a"}');
});
+
+ it.each([
+ { body: '', status: 200 },
+ { body: null, status: 204 },
+ { body: '{}', status: 200 },
+ { body: 'not JSON', status: 200 },
+ { body: '{"reason":"missing decision"}', status: 200 },
+ { body: '{"decision":"allow"}', status: 201 },
+ { body: '{"hookSpecificOutput":{"permissionDecision":"deny"}}', status: 200 },
+ ])('allows notification responses with onError=block %#', async ({ body, status }) => {
+ queueMode.mockReturnValue(queue);
+ fetchHook.mockImplementation(async () => new Response(body, { status }));
+ const fixture = setup([control('control', 'block')], undefined, queue);
+ await fixture.step();
+ expect(fixture.execute).toHaveBeenCalledTimes(1);
+ });
});
describe.each([false, true])('service response fields, queue=%s', (queue) => {
diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts
index 04622b5f36f..1fed8f9b9d6 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts
@@ -231,7 +231,7 @@ describe('Server callSubAgent suspend/resume', () => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/subagent-result');
vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');
vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
const originalFetch = globalThis.fetch;
vi.stubGlobal('fetch', (url: string, init: RequestInit) =>
String(url) === 'https://hooks.example/subagent-result'
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 4a06bbbf381..7b0146536a4 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -709,7 +709,7 @@ describe('AgentRuntimeService', () => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/environment');
vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');
vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(
new Error('db down'),
);
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index 13d86b21d7c..1af59c0a044 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -215,6 +215,8 @@ export class HookDispatcher {
if (!payload || signal?.aborted) return { status: 'cancelled' };
const response = await executeToolCallWebhook(hook.webhook, payload, { signal });
if (signal?.aborted || response.status === 'cancelled') return { status: 'cancelled' };
+ // A notification response does not decide for any subsequent policy.
+ if (response.status === 'ignored') continue;
if (response.status === 'success' && response.decision.decision === 'deny') {
return {
status: 'blocked',
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/deferredToolResultControl.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/deferredToolResultControl.test.ts
index 7fbbc0d4bad..5bdec70739b 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/deferredToolResultControl.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/deferredToolResultControl.test.ts
@@ -87,7 +87,7 @@ describe('out-of-band tool result control', () => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/environment');
vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');
vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
deps.messageModel.findMessagePlugin.mockResolvedValue({
...plugin,
intervention: { operationId: 'original', status: 'approved' },
@@ -199,7 +199,7 @@ describe('out-of-band tool result control', () => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/after');
vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-token');
vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
expect(deps.dispatcher.hasAfterToolCallControl('parent', [])).toBe(true);
deps.loadState.mockResolvedValue(null);
deps.loadDurableHooks.mockResolvedValue([]);
@@ -362,7 +362,7 @@ describe('out-of-band tool result control', () => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/after');
vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-token');
vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');
expect((await controlDeferredToolResult(deps, input)).result.content).toBe(
BLOCKED_TOOL_RESULT_CONTENT,
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.network.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.network.test.ts
index ed1646f081f..a136909033e 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.network.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.network.test.ts
@@ -80,10 +80,9 @@ describe('HTTP hook network boundary', () => {
});
expect(requests).toEqual([`/${decision}`]);
});
- it('rejects 204 for control but accepts it for notification', async () => {
+ it('accepts 204 as a notification in either response mode', async () => {
expect(await executeToolCallWebhook(config(`${base}/hook`), {})).toEqual({
- status: 'error',
- code: 'invalid_response',
+ status: 'ignored',
});
await expect(deliverWebhook({ url: `${base}/hook` }, {})).resolves.toBeUndefined();
expect(requests).toEqual(['/hook', '/hook']);
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.test.ts
index 4358081d6f4..223c13c0121 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.test.ts
@@ -43,23 +43,29 @@ describe('HTTP hook primitive', () => {
expect(request.signal).toBeInstanceOf(AbortSignal);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
- it.each([200, 204, 205])('rejects empty control response %i', async (status) => {
+ it.each([200, 204, 205])('ignores empty decision response %i', async (status) => {
fetchMock.mockResolvedValue(new Response(null, { status }));
expect(await executeToolCallWebhook(config, {})).toEqual({
- status: 'error',
- code: 'invalid_response',
+ status: 'ignored',
});
});
it.each([201, 202, 206])(
- 'requires HTTP 200 even with a valid control body: %i',
+ 'accepts a valid decision on a successful HTTP response: %i',
async (status) => {
fetchMock.mockResolvedValue(new Response('{"decision":"allow"}', { status }));
expect(await executeToolCallWebhook(config, {})).toEqual({
- status: 'error',
- code: 'invalid_response',
+ status: 'success',
+ decision: { decision: 'allow' },
});
},
);
+ it.each(['{', 'notification accepted', '{}', 'null', '[]'])(
+ 'ignores a successful response without a decision: %s',
+ async (body) => {
+ fetchMock.mockResolvedValue(new Response(body));
+ expect(await executeToolCallWebhook(config, {})).toEqual({ status: 'ignored' });
+ },
+ );
it.each([200, 204, 205])('accepts empty notification response %i', async (status) => {
fetchMock.mockResolvedValue(new Response(null, { status }));
await expect(deliverWebhook({ url: config.url }, {})).resolves.toBeUndefined();
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.ts
index 61e95429725..16ee3334ae5 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.ts
@@ -31,6 +31,7 @@ const event: Omit<ToolCallHookEvent, 'mock'> = {
describe('environment hooks through real HTTP transport', () => {
const requests: { authorization?: string; body: Record<string, unknown>; path?: string }[] = [];
let response: unknown;
+ let responseStatus: number;
const receiver = createServer(async (request, reply) => {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(Buffer.from(chunk));
@@ -39,14 +40,16 @@ describe('environment hooks through real HTTP transport', () => {
body: JSON.parse(Buffer.concat(chunks).toString()),
path: request.url,
});
+ reply.statusCode = request.url === '/notification' ? 204 : responseStatus;
reply.setHeader('content-type', 'application/json');
- reply.end(JSON.stringify(response));
+ reply.end(typeof response === 'string' ? response : JSON.stringify(response));
});
let url: string;
beforeEach(async () => {
requests.length = 0;
response = { decision: 'allow' };
+ responseStatus = 200;
queueMode.mockReturnValue(false);
await new Promise<void>((resolve) => receiver.listen(0, '127.0.0.1', resolve));
url = `http://127.0.0.1:${(receiver.address() as AddressInfo).port}/ingress`;
@@ -88,8 +91,8 @@ describe('environment hooks through real HTTP transport', () => {
responseHandling: 'toolCall',
url,
});
- for (const hook of hooks.slice(1))
- expect(hook.webhook).toMatchObject({ onError: 'continue', responseHandling: 'ignore' });
+ expect(hooks[1].webhook).toMatchObject({ onError: 'block', responseHandling: 'toolCall' });
+ expect(hooks[2].webhook).toMatchObject({ onError: 'continue', responseHandling: 'ignore' });
// A cold worker uses its current configuration, ignoring legacy snapshot copies.
vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-secret-two');
@@ -105,12 +108,16 @@ describe('environment hooks through real HTTP transport', () => {
reason: 'Denied by current env hook',
status: 'blocked',
});
- await cold.dispatch(
- event.operationId,
- 'afterToolCall',
- { ...event, executionTimeMs: 1, mocked: true, result: { content: 'safe', success: true } },
- restored,
- );
+ const after = {
+ ...event,
+ executionTimeMs: 1,
+ mocked: true,
+ result: { content: 'safe', success: true },
+ };
+ expect(await cold.evaluateAfterToolCall(event.operationId, after, restored)).toMatchObject({
+ status: 'blocked',
+ });
+ await cold.dispatch(event.operationId, 'afterToolCall', after, restored);
await cold.dispatch(
event.operationId,
'onToolCallError',
@@ -135,14 +142,10 @@ describe('environment hooks through real HTTP transport', () => {
},
);
- it.each(['toolResult', 'toolCallAndResult'])(
- 'opts into afterToolCall controls with %s without persisting server secrets',
- async (mode) => {
- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', mode);
- vi.stubEnv(
- 'AGENT_HOOK_WEBHOOK_EVENTS',
- mode === 'toolResult' ? 'afterToolCall' : 'beforeToolCall,afterToolCall',
- );
+ it.each(['afterToolCall', 'beforeToolCall,afterToolCall'])(
+ 'checks selected events %s with toolCall without persisting server secrets',
+ async (events) => {
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', events);
response = { decision: 'deny' };
const dispatcher = new HookDispatcher();
dispatcher.register(event.operationId, []);
@@ -155,9 +158,82 @@ describe('environment hooks through real HTTP transport', () => {
expect(requests).toHaveLength(1);
expect(requests[0].body).toMatchObject({ hookType: 'afterToolCall', result: after.result });
expect(await dispatcher.evaluateToolCall(event.operationId, event)).toMatchObject({
- status: mode === 'toolCallAndResult' ? 'blocked' : 'allow',
+ status: events.includes('beforeToolCall') ? 'blocked' : 'allow',
+ });
+ expect(requests).toHaveLength(events.includes('beforeToolCall') ? 2 : 1);
+ },
+ );
+
+ describe.each(['beforeToolCall', 'afterToolCall'] as const)(
+ 'optional decisions for %s',
+ (type) => {
+ const after = { ...event, mocked: false, result: { content: 'full result', success: true } };
+ const evaluate = (dispatcher: HookDispatcher) =>
+ type === 'beforeToolCall'
+ ? dispatcher.evaluateToolCall(event.operationId, event)
+ : dispatcher.evaluateAfterToolCall(event.operationId, after);
+
+ it.each([
+ [204, ''],
+ [200, ''],
+ [200, 'not JSON'],
+ [200, '{"decision":'],
+ [200, {}],
+ [200, null],
+ [200, [{ decision: 'deny' }]],
+ [202, { accepted: true }],
+ ] as const)(
+ 'continues on notification response %i %j even with onError=block',
+ async (status, body) => {
+ responseStatus = status;
+ response = body;
+ const dispatcher = new HookDispatcher();
+ expect(await evaluate(dispatcher)).toEqual({ status: 'allow' });
+ await dispatcher.dispatch(
+ event.operationId,
+ type,
+ type === 'beforeToolCall' ? event : after,
+ );
+ expect(requests).toHaveLength(1);
+ expect(requests[0].body.hookType).toBe(type);
+ },
+ );
+
+ it.each(['continue', 'block'] as const)(
+ 'honors onError=%s for delivery and decision errors',
+ async (onError) => {
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', onError);
+ const dispatcher = new HookDispatcher();
+ for (const [status, body] of [
+ [503, 'not JSON'],
+ [200, { decision: 'invalid' }],
+ ] as const) {
+ responseStatus = status;
+ response = body;
+ expect(await evaluate(dispatcher)).toMatchObject({
+ status: onError === 'block' ? 'blocked' : 'allow',
+ });
+ }
+ },
+ );
+
+ it('keeps evaluating later policies after a notification response', async () => {
+ response = { decision: 'deny' };
+ const dispatcher = new HookDispatcher();
+ dispatcher.register(event.operationId, [
+ {
+ id: 'notification-response',
+ type,
+ webhook: {
+ url: url.replace('/ingress', '/notification'),
+ responseHandling: 'toolCall',
+ onError: 'block',
+ },
+ },
+ ]);
+ expect(await evaluate(dispatcher)).toMatchObject({ status: 'blocked' });
+ expect(requests.map((request) => request.path)).toEqual(['/notification', '/ingress']);
});
- expect(requests).toHaveLength(mode === 'toolCallAndResult' ? 2 : 1);
},
);
@@ -180,7 +256,7 @@ describe('environment hooks through real HTTP transport', () => {
result: { content: 'ok', success: true },
});
expect(handler).toHaveBeenCalledTimes(1);
- expect(requests.map((request) => request.path)).toEqual(['/ingress/internal', '/ingress']);
+ expect(requests.map((request) => request.path)).toEqual(['/ingress/internal']);
expect(dispatcher.getSerializedHooks(event.operationId)).toEqual([original[0]]);
});
@@ -320,18 +396,14 @@ describe('environment hooks through real HTTP transport', () => {
{ ...event, executionTimeMs: 1, result: { content: 'ok', success: true } },
restored,
);
- expect(requests.map((request) => request.path)).toEqual([
- '/ingress',
- '/ingress/internal',
- '/ingress',
- ]);
+ expect(requests.map((request) => request.path)).toEqual(['/ingress', '/ingress/internal']);
});
it.each(['continue', 'block'] as const)(
'applies onError=%s to an invalid control response without leaking credentials',
async (onError) => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', onError);
- response = { invalid: 'synthetic-secret-two' };
+ response = { decision: 'synthetic-secret-two' };
const log = vi.spyOn(console, 'error');
const dispatcher = new HookDispatcher();
dispatcher.register(event.operationId, []);
diff --git a/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts b/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
index 34bdb8bda03..4243e8dd0bf 100644
--- a/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
+++ b/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
@@ -126,9 +126,9 @@ async function discardNotificationBody(response: Response): Promise<void> {
}
async function readControlBody(response: Response, signal: AbortSignal): Promise<ArrayBuffer> {
- if (response.status !== 200) {
+ if (response.status === 204) {
await response.body?.cancel();
- throw new HookHttpError('invalid_response');
+ return new ArrayBuffer(0);
}
const body = await readBlobWithLimit(response, AGENT_HOOK_RESPONSE_MAX_BYTES).catch(
(error: unknown) => {
diff --git a/apps/server/src/services/agentRuntime/hooks/serverHooks.ts b/apps/server/src/services/agentRuntime/hooks/serverHooks.ts
index 93a167230ba..75ea734d624 100644
--- a/apps/server/src/services/agentRuntime/hooks/serverHooks.ts
+++ b/apps/server/src/services/agentRuntime/hooks/serverHooks.ts
@@ -17,10 +17,8 @@ export function getServerHooks(): AgentHook[] {
return env.AGENT_HOOK_WEBHOOK_EVENTS!.map((type): AgentHook => {
const id = `${SERVER_HOOK_PREFIX}${type}`;
if (
- (type === 'beforeToolCall' &&
- ['toolCall', 'toolCallAndResult'].includes(env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING)) ||
- (type === 'afterToolCall' &&
- ['toolResult', 'toolCallAndResult'].includes(env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING))
+ (type === 'beforeToolCall' || type === 'afterToolCall') &&
+ env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolCall'
) {
return {
id,
diff --git a/docs/development/agent-tool-result-hooks.md b/docs/development/agent-tool-result-hooks.md
index 7a93a679326..088aee942fe 100644
--- a/docs/development/agent-tool-result-hooks.md
+++ b/docs/development/agent-tool-result-hooks.md
@@ -1,6 +1,6 @@
# Controlling tool results with afterToolCall
-`afterToolCall` can synchronously decide whether a completed tool result may enter the next model turn. It uses the same flat HTTP allow/deny protocol as `beforeToolCall`.
+`beforeToolCall` and `afterToolCall` share one optional flat HTTP allow/deny protocol: `responseHandling: 'toolCall'`. A valid decision controls execution or result publication; a successful response without a decision is treated as a notification. `afterToolCall` decides whether a completed tool result may enter the next model turn.
This is a **result gate**. The tool has already executed, so denying its output does not undo file writes, network requests, child-agent work, or messages already posted to a shared conversation.
@@ -25,7 +25,7 @@ const hooks = [
The webhook receives the normal tool correlation fields (`operationId`, native `toolCallId`, `assistantMessageId`, tool identifier/API, effective `args`, and available run context) plus `mocked` and `result`. For controls, `result` is the complete result returned to the server runtime, including content, error/state, execution timing, and Work-registration intent. It is sent **before** content truncation, archival, and observation-event redaction. The policy receiver is therefore a trusted destination for the original result, including any sensitive data it contains.
-Reply with HTTP 200 and either:
+To control the call or result, reply with HTTP 2xx and either:
```json
{ "decision": "allow" }
@@ -37,6 +37,8 @@ Reply with HTTP 200 and either:
Only `decision` and an optional string denial `reason` are parsed. Extra fields are ignored; controls cannot replace results, rewrite arguments, or append model context. Controls require fetch, cannot also have a local handler, and cannot filter or override their request with `eventFields` or `body`.
+HTTP 204, empty bodies, invalid JSON, and valid JSON without a top-level `decision` are notification responses. This includes arrays, scalars, `null`, and the old nested `hookSpecificOutput` format. They continue even with `onError: 'block'`. An explicit but invalid decision (including an invalid denial reason) is a protocol error and follows `onError`. Each hook is still awaited; notification responses do not bypass later matching controls.
+
Matching controls run in registration order. A deny stops the remaining controls for that result. With no matching controls, normal behavior is unchanged. Ordinary `afterToolCall` handlers/webhooks remain notifications; their returned bodies do not control execution.
## Denial and failure behavior
@@ -46,7 +48,7 @@ Matching controls run in registration order. A deny stops the remaining controls
- The receiver's denial reason is deliberately not echoed into model context or tool state, because it could quote the denied output
- The native call/result pairing remains intact. A deny does not retry the tool or charge it as an unexecuted call; actual attempt count, execution time, and existing tool charges remain. Deferred child usage counters are retained without child output
- Result controls run after the tool's existing internal retry loop and also inspect failed/timeout results. Exceptions that do not produce a result retain the existing `onToolCallError` behavior
-- Non-200 responses (including 204), invalid/missing decisions, oversized/malformed responses, network failures, and timeouts use the existing `onError` policy: `continue` by default, or `block` for fail-closed operation. Cancellation never becomes permission to release a result
+- Non-2xx responses, explicit invalid decisions, oversized responses, invalid UTF-8, network failures, and timeouts use the existing `onError` policy: `continue` by default, or `block`. Successful notification responses do not invoke `onError`. Cancellation never becomes permission to release a result
- Denied results are persisted in sanitized form, so later history rehydration cannot recover their original content or state. Deferred completion replays cannot overwrite an already withheld result, even if the hook is later removed
## Server environment configuration
@@ -55,26 +57,28 @@ The existing `AGENT_HOOK_WEBHOOK_URL`, `AGENT_HOOK_WEBHOOK_TOKEN`, `AGENT_HOOK_W
`AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING` selects which configured events are controls:
-| Value | beforeToolCall | afterToolCall |
-| ------------------------------ | -------------- | ------------- |
-| `ignore` (default) | Notification | Notification |
-| `toolCall` (existing behavior) | Control | Notification |
-| `toolResult` | Notification | Control |
-| `toolCallAndResult` | Control | Control |
+| Value | beforeToolCall | afterToolCall |
+| ------------------ | ----------------- | ----------------- |
+| `ignore` (default) | Notification | Notification |
+| `toolCall` | Optional decision | Optional decision |
-Only events listed in `AGENT_HOOK_WEBHOOK_EVENTS` are enabled. A control mode requires at least one corresponding event; unsupported values and incompatible configurations fail validation. Other lifecycle events remain notifications. The environment mode names are intentionally distinct from the per-hook registration's `responseHandling: 'toolCall'`, which identifies the shared decision protocol.
+Only events listed in `AGENT_HOOK_WEBHOOK_EVENTS` are enabled. `toolCall` requires at least one of `beforeToolCall` or `afterToolCall`; unsupported values and incompatible configurations fail validation. Other lifecycle events, including `onToolCallError`, remain notifications. Environment hooks and per-hook registrations use the same `toolCall` decision protocol.
-For after-only fail-closed checking:
+For after-only checking that blocks delivery and decision errors:
```dotenv
AGENT_HOOK_WEBHOOK_URL=https://example.com/tool-policy
AGENT_HOOK_WEBHOOK_TOKEN=your-server-side-token
AGENT_HOOK_WEBHOOK_EVENTS=afterToolCall
-AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING=toolResult
+AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING=toolCall
AGENT_HOOK_WEBHOOK_ON_ERROR=block
```
-Existing deployments using `EVENTS=beforeToolCall,afterToolCall` with `RESPONSE_HANDLING=toolCall` keep their original behavior; after notifications do not silently become result controls. All executing server/worker processes need the intended configuration. Environment hooks continue to use current process configuration rather than persisted copies.
+### Migration
+
+`toolResult` and `toolCallAndResult` have been removed; replace either with `toolCall` before starting updated workers. Select after-only checking with `EVENTS=afterToolCall`; subscribe to both events for decisions at both phases.
+
+Existing `toolCall` deployments now honor decisions returned for `afterToolCall`. Receivers that only record an event can return HTTP 204, an empty successful response, or a body without a top-level decision. Existing before hooks also allow these notification responses, including invalid JSON, even with `ON_ERROR=block`; explicit allow is no longer required. Use a valid decision whenever intervention is intended. All executing server/worker processes need the intended configuration. Environment hooks continue to use current process configuration rather than persisted copies.
## Publication, configuration lifetime, and rollout
diff --git a/packages/env/src/__tests__/agentHook.test.ts b/packages/env/src/__tests__/agentHook.test.ts
index 7c0478a8922..f67001bf6a4 100644
--- a/packages/env/src/__tests__/agentHook.test.ts
+++ b/packages/env/src/__tests__/agentHook.test.ts
@@ -40,6 +40,8 @@ describe('server hook environment', () => {
['URL', 'ftp://webhook-service/ingress'],
['URL', ''],
['RESPONSE_HANDLING', 'invalid'],
+ ['RESPONSE_HANDLING', 'toolResult'],
+ ['RESPONSE_HANDLING', 'toolCallAndResult'],
['ON_ERROR', 'invalid'],
['ON_ERROR', 'block'],
])('rejects invalid %s without exposing the token', (name, value) => {
@@ -59,14 +61,14 @@ describe('server hook environment', () => {
it('accepts afterToolCall-only result controls', () => {
enable();
vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
- vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');
expect(getAgentHookConfig().AGENT_HOOK_WEBHOOK_EVENTS).toEqual(['afterToolCall']);
});
- it('keeps toolCall before-only for existing deployment configurations', () => {
+ it('requires a beforeToolCall or afterToolCall event for toolCall', () => {
enable();
- vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'onToolCallError');
vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
expect(() => getAgentHookConfig()).toThrow('beforeToolCall');
});
diff --git a/packages/env/src/agentHook.ts b/packages/env/src/agentHook.ts
index cc357d8b730..83d359c16b7 100644
--- a/packages/env/src/agentHook.ts
+++ b/packages/env/src/agentHook.ts
@@ -34,9 +34,7 @@ export const getAgentHookConfig = () => {
z.array(agentHookTypeSchema).min(1).optional(),
),
AGENT_HOOK_WEBHOOK_ON_ERROR: z.enum(['continue', 'block']).default('continue'),
- AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING: z
- .enum(['ignore', 'toolCall', 'toolResult', 'toolCallAndResult'])
- .default('ignore'),
+ AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING: z.enum(['ignore', 'toolCall']).default('ignore'),
AGENT_HOOK_WEBHOOK_TOKEN: z
.string()
.refine((token) => token.trim().length > 0)
@@ -56,16 +54,12 @@ export const getAgentHookConfig = () => {
env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'ignore'
)
throw new Error(
- 'AGENT_HOOK_WEBHOOK_ON_ERROR=block requires toolCall, toolResult, or toolCallAndResult response handling',
+ 'AGENT_HOOK_WEBHOOK_ON_ERROR=block requires AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING=toolCall',
);
const controlEvents =
env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolCall'
- ? ['beforeToolCall']
- : env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolResult'
- ? ['afterToolCall']
- : env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolCallAndResult'
- ? ['beforeToolCall', 'afterToolCall']
- : [];
+ ? ['beforeToolCall', 'afterToolCall']
+ : [];
if (
controlEvents.length > 0 &&
!env.AGENT_HOOK_WEBHOOK_EVENTS?.some((type) => controlEvents.includes(type))
diff --git a/packages/types/src/agentHook.test.ts b/packages/types/src/agentHook.test.ts
index ad176d322cd..5d65f6cf751 100644
--- a/packages/types/src/agentHook.test.ts
+++ b/packages/types/src/agentHook.test.ts
@@ -123,19 +123,26 @@ describe('flat tool response parser', () => {
'null',
'[]',
'true',
+ '42',
+ '"notification"',
+ '[{"decision":"deny"}]',
+ '{"decision":',
+ response({ reason: 'missing decision' }),
+ response({ hookSpecificOutput: { permissionDecision: 'deny' } }),
+ ])('ignores a notification response without a top-level decision %#', (body) => {
+ expect(parseToolCallHookResponse(body)).toEqual({ status: 'ignored' });
+ });
+ it.each([
...[
{ decision: 'block' },
{ decision: 'ask' },
{ decision: 'defer' },
{ decision: null },
{ decision: 1 },
- { reason: 'missing decision' },
{ decision: 'deny', reason: 3 },
{ decision: 'deny', reason: null },
- { hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'allow' } },
- { hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'deny' } },
].map(response),
- ])('rejects malformed or unsupported control response %#', (body) => {
+ ])('rejects an explicitly invalid decision %#', (body) => {
expect(parseToolCallHookResponse(body)).toEqual({ code: 'invalid_response', status: 'error' });
});
it.each(['allow', 'deny'])(
diff --git a/packages/types/src/agentHookResponse.ts b/packages/types/src/agentHookResponse.ts
index a6324274f1e..227440c059d 100644
--- a/packages/types/src/agentHookResponse.ts
+++ b/packages/types/src/agentHookResponse.ts
@@ -1,7 +1,7 @@
import { z } from 'zod';
export const AGENT_HOOK_RESPONSE_MAX_BYTES = 64 * 1024;
-/** Consume only the flat decision fields from an HTTP 200 body; strip service metadata. */
+/** Consume only explicit flat decisions from successful responses; strip service metadata. */
export const toolCallHookDecisionSchema = z.discriminatedUnion('decision', [
z.object({ decision: z.literal('allow') }),
z.object({ decision: z.literal('deny'), reason: z.string().optional() }),
@@ -10,6 +10,7 @@ export const toolCallHookDecisionSchema = z.discriminatedUnion('decision', [
export type ToolCallHookDecision = z.infer<typeof toolCallHookDecisionSchema>;
export type ToolCallHookParseResult =
| { decision: ToolCallHookDecision; status: 'success' }
+ | { status: 'ignored' }
| { code: 'invalid_response' | 'response_too_large'; status: 'error' };
/** Pure parser: never executes tools, applies policy, or includes remote text in errors. */
@@ -21,8 +22,10 @@ export function parseToolCallHookResponse(body: string): ToolCallHookParseResult
try {
value = JSON.parse(body);
} catch {
- return { code: 'invalid_response', status: 'error' };
+ return { status: 'ignored' };
}
+ const record = z.record(z.string(), z.unknown()).safeParse(value);
+ if (!record.success || !Object.hasOwn(record.data, 'decision')) return { status: 'ignored' };
const parsed = toolCallHookDecisionSchema.safeParse(value);
if (!parsed.success) return { code: 'invalid_response', status: 'error' };
return { decision: parsed.data, status: 'success' };