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.

🐛 fix(agent): simplify HTTP hook control responses (#20202)

Bryan48c03c63762f
diff --git a/.agents/skills/agent-runtime-hooks/SKILL.md b/.agents/skills/agent-runtime-hooks/SKILL.md
index 9619633e4be..4ff7a482481 100644
--- a/.agents/skills/agent-runtime-hooks/SKILL.md
+++ b/.agents/skills/agent-runtime-hooks/SKILL.md
@@ -101,7 +101,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. `responseHandling: 'toolCall'` is explicitly unsupported at registration/restoration in this version; the response parser and HTTP helper do not enforce tool decisions.
+- 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`.
+- 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.
+- 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`.
## Events
diff --git a/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts
index 436499e2e2f..c740c5f57d0 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts
@@ -53,16 +53,8 @@ const control = (id = 'control', onError: 'continue' | 'block' = 'continue'): Ag
type: 'beforeToolCall',
webhook: { url: `https://hooks.example/${id}`, responseHandling: 'toolCall', onError },
});
-const response = (permissionDecision: 'allow' | 'deny', permissionDecisionReason?: string) =>
- new Response(
- JSON.stringify({
- hookSpecificOutput: {
- hookEventName: 'beforeToolCall',
- permissionDecision,
- permissionDecisionReason,
- },
- }),
- );
+const response = (decision: 'allow' | 'deny', reason?: string) =>
+ new Response(JSON.stringify(decision === 'deny' ? { decision, reason } : { decision }));
function setup(hooks: AgentHook[], signal?: AbortSignal, restore = false) {
const registered = new HookDispatcher();
@@ -291,7 +283,12 @@ describe('beforeToolCall control pipeline', () => {
expect(result.events).toContainEqual(
expect.objectContaining({
type: 'tool_result',
- result: expect.objectContaining({ error: 'hook_denied', success: false }),
+ result: expect.objectContaining({
+ content: reason,
+ error: 'hook_denied',
+ state: { type: 'blocked', reason },
+ success: false,
+ }),
}),
);
expect(fixture.execute).not.toHaveBeenCalled();
@@ -528,30 +525,6 @@ describe('beforeToolCall control pipeline', () => {
expect(fixture.execute).not.toHaveBeenCalled();
});
- it.each([false, true])(
- 'never allows deny with unsupported additionalContext, queue=%s',
- async (queue) => {
- queueMode.mockReturnValue(queue);
- fetchHook.mockImplementation(
- async () =>
- new Response(
- JSON.stringify({
- hookSpecificOutput: {
- hookEventName: 'beforeToolCall',
- permissionDecision: 'deny',
- permissionDecisionReason: 'explicit denial',
- additionalContext: 'context',
- },
- }),
- ),
- );
- const fixture = setup([control()]);
- await fixture.step();
- expect(fixture.execute).not.toHaveBeenCalled();
- expect(fixture.rows[0].content).toBe('explicit denial');
- },
- );
-
it.each(['constructor', '__proto__'])('checks controls for native id %s', async (id) => {
fetchHook.mockImplementation(async () => response('deny'));
const fixture = setup([control()]);
@@ -574,35 +547,81 @@ describe('beforeToolCall control pipeline', () => {
expect(fixture.execute).not.toHaveBeenCalled();
});
- it.each(['updatedInput', 'additionalContext'] as const)(
- 'routes unsupported %s through onError',
- async (field) => {
- fetchHook.mockImplementation(
- async () =>
- new Response(
- JSON.stringify({
- hookSpecificOutput: {
- hookEventName: 'beforeToolCall',
- permissionDecision: 'allow',
- [field]: field === 'updatedInput' ? { path: 'b' } : 'context',
- },
- }),
- ),
- );
- const blocked = setup([control('block', 'block')]);
+ 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 }));
+ const blocked = setup([control('block', 'block')], undefined, queue);
await blocked.step();
expect(blocked.execute).not.toHaveBeenCalled();
- expect(blocked.rows[0].content).toBe('unsupported_control_response');
- expect(blocked.rows[0].pluginIntervention).toEqual({
- status: 'rejected',
- rejectedReason: 'unsupported_control_response',
+ expect(blocked.rows[0]).toMatchObject({
+ content: 'hook_control_error',
+ pluginError: 'hook_denied',
+ pluginIntervention: { status: 'rejected', rejectedReason: 'hook_control_error' },
});
- const continued = setup([control()]);
+ const continued = setup([control()], undefined, queue);
await continued.step();
expect(continued.execute).toHaveBeenCalledTimes(1);
expect(continued.execute.mock.calls[0][0].arguments).toBe('{"path":"a"}');
- },
- );
+ });
+ });
+
+ describe.each([false, true])('service response fields, queue=%s', (queue) => {
+ it.each([
+ { decision: 'allow', onError: 'block' },
+ { decision: 'allow', onError: 'continue' },
+ { decision: 'deny', onError: 'block' },
+ { decision: 'deny', onError: 'continue' },
+ ] as const)(
+ 'honors $decision and ignores extra fields with onError=$onError',
+ async ({ decision, onError }) => {
+ queueMode.mockReturnValue(queue);
+ fetchHook.mockImplementation(
+ async () =>
+ new Response(
+ JSON.stringify({
+ decision,
+ reason: '禁止执行该操作',
+ requestId: 'service-trace',
+ updatedInput: { path: 'replacement' },
+ additionalContext: 'must not enter the conversation',
+ }),
+ ),
+ );
+ const fixture = setup([control('control', onError)], undefined, queue);
+ const result = await fixture.step();
+ if (decision === 'allow') {
+ expect(fixture.execute).toHaveBeenCalledTimes(1);
+ expect(fixture.execute.mock.calls[0][0].arguments).toBe('{"path":"a"}');
+ } else {
+ expect(fixture.execute).not.toHaveBeenCalled();
+ expect(fixture.rows[0]).toMatchObject({
+ content: '禁止执行该操作',
+ pluginError: 'hook_denied',
+ });
+ }
+ expect(JSON.stringify(result)).not.toContain('must not enter the conversation');
+ expect(JSON.stringify(fixture.rows)).not.toContain('service-trace');
+ },
+ );
+ });
it.each([false, true])('does not await an ordinary HTTP observation, queue=%s', async (queue) => {
queueMode.mockReturnValue(queue);
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index adfb8a97d4b..51544953d73 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -168,23 +168,17 @@ 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' };
- // An explicit deny is authoritative even when extra fields are unsupported.
- if (response.status === 'success' && response.decision?.permissionDecision === 'deny') {
+ if (response.status === 'success' && response.decision.decision === 'deny') {
return {
status: 'blocked',
- reason: response.decision.permissionDecisionReason ?? 'Blocked by beforeToolCall hook.',
+ reason: response.decision.reason ?? 'Blocked by beforeToolCall hook.',
};
}
- // This entry supports allow/deny only; unsupported responses follow onError.
- const unsupported =
- response.status === 'success' &&
- (response.decision?.updatedInput !== undefined ||
- response.decision?.additionalContext !== undefined);
- if (response.status === 'error' || unsupported) {
+ if (response.status === 'error') {
if (resolveToolCallHookErrorPolicy(hook.webhook.onError).action === 'block') {
return {
status: 'blocked',
- reason: unsupported ? 'unsupported_control_response' : 'hook_control_error',
+ reason: 'hook_control_error',
};
}
continue;
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/controlWebhookPayload.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/controlWebhookPayload.test.ts
index e0988d9cdfb..19ba7b45ba4 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/controlWebhookPayload.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/controlWebhookPayload.test.ts
@@ -47,7 +47,7 @@ beforeEach(() => {
async () =>
new Response(
JSON.stringify({
- hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'allow' },
+ decision: 'allow',
}),
),
);
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 b9bb95cf8e9..ed1646f081f 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
@@ -20,6 +20,15 @@ describe('HTTP hook network boundary', () => {
if (req.url === '/redirect') {
res.writeHead(302, { Location: `${base}/leaked` });
res.end();
+ } else if (req.url === '/allow' || req.url === '/deny') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(
+ JSON.stringify(
+ req.url === '/allow'
+ ? { decision: 'allow' }
+ : { decision: 'deny', reason: '禁止执行该操作' },
+ ),
+ );
} else if (req.url?.startsWith('/disconnect')) {
req.socket.destroy();
} else if (req.url === '/large') {
@@ -64,6 +73,21 @@ describe('HTTP hook network boundary', () => {
expect(requests).toEqual(['/hook', '/hook']);
},
);
+ it.each(['allow', 'deny'] as const)('parses a flat %s over real HTTP', async (decision) => {
+ expect(await executeToolCallWebhook(config(`${base}/${decision}`), {})).toEqual({
+ status: 'success',
+ decision: decision === 'allow' ? { decision } : { decision, reason: '禁止执行该操作' },
+ });
+ expect(requests).toEqual([`/${decision}`]);
+ });
+ it('rejects 204 for control but accepts it for notification', async () => {
+ expect(await executeToolCallWebhook(config(`${base}/hook`), {})).toEqual({
+ status: 'error',
+ code: 'invalid_response',
+ });
+ await expect(deliverWebhook({ url: `${base}/hook` }, {})).resolves.toBeUndefined();
+ expect(requests).toEqual(['/hook', '/hook']);
+ });
it('does not log query credentials when the connection fails', async () => {
const logger = vi.mocked(console.error);
expect(
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 7b00ca583af..4358081d6f4 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.test.ts
@@ -30,7 +30,7 @@ describe('HTTP hook primitive', () => {
});
it('uses fetch without redirects and with a default deadline', async () => {
- fetchMock.mockResolvedValue(new Response('{}'));
+ fetchMock.mockResolvedValue(new Response('{"decision":"allow"}'));
expect(await executeToolCallWebhook(config, { args: { value: 1 } })).toMatchObject({
status: 'success',
});
@@ -43,17 +43,29 @@ describe('HTTP hook primitive', () => {
expect(request.signal).toBeInstanceOf(AbortSignal);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
- it.each([200, 204, 205])('accepts empty 2xx %i', async (status) => {
+ it.each([200, 204, 205])('rejects empty control response %i', async (status) => {
fetchMock.mockResolvedValue(new Response(null, { status }));
- expect(await executeToolCallWebhook(config, {})).toEqual({ status: 'success' });
+ expect(await executeToolCallWebhook(config, {})).toEqual({
+ status: 'error',
+ code: 'invalid_response',
+ });
+ });
+ it.each([201, 202, 206])(
+ 'requires HTTP 200 even with a valid control body: %i',
+ async (status) => {
+ fetchMock.mockResolvedValue(new Response('{"decision":"allow"}', { status }));
+ expect(await executeToolCallWebhook(config, {})).toEqual({
+ status: 'error',
+ code: 'invalid_response',
+ });
+ },
+ );
+ 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();
});
it.each([301, 400, 500])('rejects status %i without parsing the body', async (status) => {
- fetchMock.mockResolvedValue(
- new Response(
- '{"hookSpecificOutput":{"hookEventName":"beforeToolCall","permissionDecision":"allow"}}',
- { status },
- ),
- );
+ fetchMock.mockResolvedValue(new Response('{"decision":"allow"}', { status }));
expect(await executeToolCallWebhook(config, {})).toEqual({
status: 'error',
code: 'http_error',
@@ -99,9 +111,7 @@ describe('HTTP hook primitive', () => {
const controller = new AbortController();
fetchMock.mockImplementation(async () => {
controller.abort();
- return new Response(
- '{"hookSpecificOutput":{"hookEventName":"beforeToolCall","permissionDecision":"allow"}}',
- );
+ return new Response('{"decision":"allow"}');
});
expect(await executeToolCallWebhook(config, {}, { signal: controller.signal })).toEqual({
status: 'cancelled',
@@ -118,10 +128,12 @@ describe('HTTP hook primitive', () => {
it('ignores legacy notification response bodies', async () => {
fetchMock.mockResolvedValueOnce(new Response('not json'));
fetchMock.mockResolvedValueOnce(new Response(new Uint8Array([0xff])));
+ fetchMock.mockResolvedValueOnce(new Response('{"decision":"deny","reason":"ignored"}'));
await expect(
deliverWebhook({ url: config.url, fallback: 'none' }, {}),
).resolves.toBeUndefined();
await expect(deliverWebhook({ url: config.url }, {})).resolves.toBeUndefined();
+ await expect(deliverWebhook({ url: config.url }, {})).resolves.toBeUndefined();
});
it('expands only allowed env values at send time without mutating configuration', async () => {
vi.stubEnv('HOOK_TOKEN', 'first-secret');
diff --git a/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts b/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
index f7358ff8d69..34bdb8bda03 100644
--- a/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
+++ b/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
@@ -126,6 +126,10 @@ async function discardNotificationBody(response: Response): Promise<void> {
}
async function readControlBody(response: Response, signal: AbortSignal): Promise<ArrayBuffer> {
+ if (response.status !== 200) {
+ await response.body?.cancel();
+ throw new HookHttpError('invalid_response');
+ }
const body = await readBlobWithLimit(response, AGENT_HOOK_RESPONSE_MAX_BYTES).catch(
(error: unknown) => {
if (error instanceof RangeError) throw new HookHttpError('response_too_large');
diff --git a/packages/types/src/agentHook.test.ts b/packages/types/src/agentHook.test.ts
index 5e6525372f8..f0c897ab88c 100644
--- a/packages/types/src/agentHook.test.ts
+++ b/packages/types/src/agentHook.test.ts
@@ -12,8 +12,7 @@ const control = {
type: 'beforeToolCall',
webhook: { responseHandling: 'toolCall', url: 'https://example.com' },
};
-const response = (output: Record<string, unknown>) =>
- JSON.stringify({ hookSpecificOutput: { hookEventName: 'beforeToolCall', ...output } });
+const response = (output: Record<string, unknown>) => JSON.stringify(output);
describe('serialized hook contract', () => {
it('round trips all fields including legacy fallback without expanding secrets', () => {
@@ -100,65 +99,72 @@ describe('serialized hook contract', () => {
});
});
-describe('strict tool response parser', () => {
- it.each(['', '{}'])('accepts an empty response or no decision: %s', (body) => {
- expect(parseToolCallHookResponse(body)).toMatchObject({ status: 'success' });
- });
- it('returns allow/replacement/context without applying them', () => {
- const decision = {
- additionalContext: 'untrusted tool context',
- permissionDecision: 'allow',
- updatedInput: { path: '/new' },
- };
+describe('flat tool response parser', () => {
+ it.each([
+ { decision: 'allow' },
+ { decision: 'deny' },
+ { decision: 'deny', reason: '禁止执行该操作' },
+ { decision: 'deny', reason: '' },
+ ])('accepts only flat allow/deny: %j', (decision) => {
expect(parseToolCallHookResponse(response(decision))).toEqual({
- decision: { hookEventName: 'beforeToolCall', ...decision },
+ decision,
status: 'success',
});
- expect(
- parseToolCallHookResponse(
- response({ permissionDecision: 'deny', permissionDecisionReason: 'private' }),
- ),
- ).toMatchObject({ status: 'success', decision: { permissionDecision: 'deny' } });
});
it.each([
+ '',
+ '{}',
' ',
'{',
'null',
'[]',
'true',
- '{"continue":false}',
- '{"decision":"block"}',
- '{"stopReason":"stop"}',
- '{"hookSpecificOutput":null}',
...[
- { hookEventName: 'afterToolCall' },
- { permissionDecision: 'ask' },
- { permissionDecision: 'defer' },
- { updatedInput: {} },
- { updatedInput: {}, permissionDecision: 'deny' },
- { updatedInput: [], permissionDecision: 'allow' },
- { additionalContext: 1 },
- { additionalContext: 'x'.repeat(10_001) },
- { updatedOutput: {} },
- { permissionDecisionReason: 3 },
+ { 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) => {
expect(parseToolCallHookResponse(body)).toEqual({ code: 'invalid_response', status: 'error' });
});
- it('counts response UTF-8 bytes and enforces exact context boundary', () => {
- expect(parseToolCallHookResponse('{}' + ' '.repeat(65_534))).toMatchObject({
+ it.each(['allow', 'deny'])(
+ 'discards service fields from %s without extending control',
+ (decision) => {
+ const body = {
+ decision,
+ reason: '禁止执行该操作',
+ requestId: 'service-trace',
+ version: 2,
+ updatedInput: { path: '/replacement' },
+ additionalContext: 'must not enter the conversation',
+ hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'deny' },
+ };
+ expect(parseToolCallHookResponse(response(body))).toEqual({
+ status: 'success',
+ decision: decision === 'allow' ? { decision } : { decision, reason: body.reason },
+ });
+ },
+ );
+ it('counts response UTF-8 bytes at the exact response boundary', () => {
+ const body = response({ decision: 'allow' });
+ expect(parseToolCallHookResponse(body + ' '.repeat(65_536 - body.length))).toEqual({
+ decision: { decision: 'allow' },
status: 'success',
});
- expect(parseToolCallHookResponse('{}' + ' '.repeat(65_535))).toEqual({
+ expect(parseToolCallHookResponse(body + ' '.repeat(65_537 - body.length))).toEqual({
status: 'error',
code: 'response_too_large',
});
expect(
- parseToolCallHookResponse(response({ permissionDecisionReason: '界'.repeat(22_000) })),
+ parseToolCallHookResponse(response({ decision: 'deny', reason: '界'.repeat(22_000) })),
).toEqual({ status: 'error', code: 'response_too_large' });
- expect(
- parseToolCallHookResponse(response({ additionalContext: 'x'.repeat(10_000) })),
- ).toMatchObject({ status: 'success' });
});
it('defaults errors to continue and supports explicit block', () => {
expect(resolveToolCallHookErrorPolicy()).toEqual({ action: 'continue' });
diff --git a/packages/types/src/agentHookResponse.ts b/packages/types/src/agentHookResponse.ts
index 8abd2a53ca1..a6324274f1e 100644
--- a/packages/types/src/agentHookResponse.ts
+++ b/packages/types/src/agentHookResponse.ts
@@ -1,27 +1,15 @@
import { z } from 'zod';
export const AGENT_HOOK_RESPONSE_MAX_BYTES = 64 * 1024;
-export const AGENT_HOOK_CONTEXT_MAX_CHARACTERS = 10_000;
-
-export const toolCallHookDecisionSchema = z
- .strictObject({
- additionalContext: z.string().max(AGENT_HOOK_CONTEXT_MAX_CHARACTERS).optional(),
- hookEventName: z.literal('beforeToolCall'),
- permissionDecision: z.enum(['allow', 'deny']).optional(),
- permissionDecisionReason: z.string().optional(),
- updatedInput: z.record(z.string(), z.unknown()).optional(),
- })
- .refine((value) => value.updatedInput === undefined || value.permissionDecision === 'allow', {
- message: 'updatedInput requires permissionDecision:allow',
- });
-
-const responseSchema = z.strictObject({
- hookSpecificOutput: toolCallHookDecisionSchema.optional(),
-});
+/** Consume only the flat decision fields from an HTTP 200 body; 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() }),
+]);
export type ToolCallHookDecision = z.infer<typeof toolCallHookDecisionSchema>;
export type ToolCallHookParseResult =
- | { decision?: ToolCallHookDecision; status: 'success' }
+ | { decision: ToolCallHookDecision; status: 'success' }
| { code: 'invalid_response' | 'response_too_large'; status: 'error' };
/** Pure parser: never executes tools, applies policy, or includes remote text in errors. */
@@ -29,16 +17,15 @@ export function parseToolCallHookResponse(body: string): ToolCallHookParseResult
if (new TextEncoder().encode(body).byteLength > AGENT_HOOK_RESPONSE_MAX_BYTES) {
return { code: 'response_too_large', status: 'error' };
}
- if (body.length === 0) return { status: 'success' };
let value: unknown;
try {
value = JSON.parse(body);
} catch {
return { code: 'invalid_response', status: 'error' };
}
- const parsed = responseSchema.safeParse(value);
+ const parsed = toolCallHookDecisionSchema.safeParse(value);
if (!parsed.success) return { code: 'invalid_response', status: 'error' };
- return { decision: parsed.data.hookSpecificOutput, status: 'success' };
+ return { decision: parsed.data, status: 'success' };
}
/** C1 must branch on cancelled before applying onError; cancellation never grants permission. */