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.

✨ feat(agent): add validated HTTP hook contracts and delivery primitives (#20128)

Bryanedb77a187244
diff --git a/.agents/skills/agent-runtime-hooks/SKILL.md b/.agents/skills/agent-runtime-hooks/SKILL.md
index ad465810044..9619633e4be 100644
--- a/.agents/skills/agent-runtime-hooks/SKILL.md
+++ b/.agents/skills/agent-runtime-hooks/SKILL.md
@@ -78,7 +78,31 @@ const hooks: AgentHook[] = [
await aiAgentService.execAgent({ agentId, prompt, hooks });
```
-Local dispatch awaits in-process handlers. Queue dispatch uses serialized webhook configuration from `state.host.hooks` or registered hooks. Completion cleans up registrations through `hookDispatcher.unregister(operationId)`.
+Completion cleans up registrations through `hookDispatcher.unregister(operationId)`.
+
+### Webhook Hooks
+
+Webhook-only hooks deliver in both local and queue modes. For hooks with both `handler` and `webhook`, local dispatch calls the handler; queue dispatch uses the serialized webhook. Only webhook configuration is persisted, so functions are unavailable after a process restart.
+
+```ts
+const hook: AgentHook = {
+ id: 'tool-notification',
+ type: 'afterToolCall',
+ matcher: '^fs/readFile$',
+ webhook: {
+ url: 'https://example.com/hooks',
+ delivery: 'fetch',
+ timeout: 5, // seconds; default 30
+ headers: { Authorization: 'Bearer ${HOOK_TOKEN}' },
+ allowedEnvVars: ['HOOK_TOKEN'],
+ },
+};
+```
+
+- `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.
+- Configuration: `packages/types/src/agentHook.ts`; response parsing: `packages/types/src/agentHookResponse.ts`; HTTP delivery: `apps/server/src/services/agentRuntime/hooks/httpWebhook.ts`.
## Events
@@ -123,7 +147,7 @@ Sandbox and MCP tools use the same event path. Filter with `identifier`, `apiNam
event.mock({ content: '{"items":[]}', success: true });
```
-Tool observation payloads use `BeforeToolCallObservationEvent`; the callback belongs to the local handler event.
+Tool observation payloads use `BeforeToolCallObservationEvent`; the callback belongs to the in-memory handler event. `dispatchBeforeToolCall()` does not deliver webhooks.
## Webhook Payloads
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 556d89d8955..e3b97e3db19 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -301,7 +301,7 @@ describe('AgentRuntimeService', () => {
twitter: { endpoint: 'https://mock.test/tool-calls' },
});
- await hook.handler(event as any);
+ await hook.handler!(event as any);
expect(mockSsrfSafeFetch).toHaveBeenCalledWith(
'https://mock.test/tool-calls',
@@ -327,7 +327,7 @@ describe('AgentRuntimeService', () => {
'case-42',
);
- await hook.handler(event as any);
+ await hook.handler!(event as any);
expect(JSON.parse(mockSsrfSafeFetch.mock.calls[0][1].body)).toMatchObject({
metadata: { caseId: 'case-42' },
@@ -342,7 +342,7 @@ describe('AgentRuntimeService', () => {
twitter: { endpoint: 'https://mock.test/tool-calls' },
});
- await hook.handler(event as any);
+ await hook.handler!(event as any);
expect(event.mock).toHaveBeenCalledWith({
content: 'fixture unavailable',
@@ -357,7 +357,7 @@ describe('AgentRuntimeService', () => {
twitter: { endpoint: 'https://mock.test/tool-calls' },
});
- await hook.handler(event as any);
+ await hook.handler!(event as any);
expect(event.mock).toHaveBeenCalledWith({ content: 'No tool result', success: true });
});
@@ -370,7 +370,7 @@ describe('AgentRuntimeService', () => {
twitter: { endpoint: 'https://mock.test/tool-calls' },
});
- await hook.handler(event as any);
+ await hook.handler!(event as any);
expect(event.mock).toHaveBeenCalledWith({ content: 'No tool result', success: true });
});
@@ -381,7 +381,7 @@ describe('AgentRuntimeService', () => {
twitter: { endpoint: 'https://mock.test/tool-calls' },
});
- await hook.handler(event as any);
+ await hook.handler!(event as any);
expect(event.mock).toHaveBeenCalledWith({
content: expect.stringContaining('SyntaxError'),
@@ -396,7 +396,7 @@ describe('AgentRuntimeService', () => {
twitter: { endpoint: 'https://mock.test/tool-calls' },
});
- await hook.handler(event as any);
+ await hook.handler!(event as any);
expect(event.mock).toHaveBeenCalledWith({
content: 'SSRF blocked',
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index 45e2bf18129..a3efad157e1 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -1,16 +1,20 @@
import type { ToolRunResult } from '@lobechat/agent-runtime';
import type { SerializedAgentHook } from '@lobechat/types';
+import {
+ agentHookMatcherSchema,
+ agentHookTypeSchema,
+ serializedAgentHookSchema,
+} from '@lobechat/types';
import debug from 'debug';
-import urlJoin from 'url-join';
-import { OtelQstashClient } from '@/libs/qstash';
import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
+import { deliverWebhook } from './httpWebhook';
+import { matchesHook } from './matcher';
import type {
AgentHook,
AgentHookEvent,
AgentHookType,
- AgentHookWebhook,
AnyHookEvent,
SerializedHook,
ToolCallHookEvent,
@@ -29,66 +33,22 @@ export class CriticalHookDeliveryError extends Error {
}
}
-/**
- * Delivers a webhook via HTTP POST (fetch or QStash)
- */
-export async function deliverWebhook(
- webhook: AgentHookWebhook,
- payload: Record<string, unknown>,
-): Promise<void> {
- const { url, delivery = 'fetch', fallback = 'fetch' } = webhook;
+export { deliverWebhook } from './httpWebhook';
- // Resolve URL: relative paths joined with INTERNAL_APP_URL or APP_URL
- const resolvedUrl = url.startsWith('http')
- ? url
- : urlJoin(process.env.INTERNAL_APP_URL || process.env.APP_URL || '', url);
-
- if (delivery === 'qstash') {
- try {
- const qstashToken = process.env.QSTASH_TOKEN;
- if (!qstashToken) {
- if (fallback === 'none') {
- throw new Error(`QSTASH_TOKEN not available for qstash-only webhook: ${url}`);
- }
- log('QStash token not available, falling back to fetch delivery');
- await fetchDeliver(resolvedUrl, payload);
- return;
- }
- const client = new OtelQstashClient({ token: qstashToken });
- await client.publishJSON({
- body: payload,
- headers: {
- ...(process.env.VERCEL_AUTOMATION_BYPASS_SECRET && {
- 'x-vercel-protection-bypass': process.env.VERCEL_AUTOMATION_BYPASS_SECRET,
- }),
- },
- url: resolvedUrl,
- });
- log('Webhook delivered via QStash: %s', url);
- } catch (error) {
- // An unsigned fetch can never authenticate against a QStash-signed
- // endpoint β€” falling back would just be a silently-dropped 401. Let
- // the failure surface to the dispatcher instead.
- if (fallback === 'none') throw error;
-
- log('QStash delivery failed, falling back to fetch: %O', error);
- await fetchDeliver(resolvedUrl, payload);
- }
- } else {
- await fetchDeliver(resolvedUrl, payload);
+export class UnsupportedControlHookError extends Error {
+ constructor() {
+ super('toolCall hooks are unsupported until the tool preparation pipeline is integrated');
+ this.name = 'UnsupportedControlHookError';
}
}
-async function fetchDeliver(url: string, payload: Record<string, unknown>): Promise<void> {
- const res = await fetch(url, {
- body: JSON.stringify(payload),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
+/** Validate persisted configurations before selecting an event, never silently discard controls. */
+export function parseSerializedHooks(hooks: SerializedAgentHook[]): SerializedHook[] {
+ return hooks.map((hook) => {
+ const parsed = serializedAgentHookSchema.parse(hook);
+ if (parsed.webhook.responseHandling === 'toolCall') throw new UnsupportedControlHookError();
+ return parsed;
});
- if (res.status < 200 || res.status >= 300) {
- throw new Error(`Webhook delivery failed: ${res.status} ${res.statusText}`);
- }
- log('Webhook delivered via fetch: %s (status: %d)', url, res.status);
}
/**
@@ -124,71 +84,47 @@ export class HookDispatcher {
serializedHooks?: SerializedAgentHook[],
): Promise<void> {
const isQueueMode = isQueueAgentRuntimeEnabled();
-
- if (!isQueueMode) {
- // Local mode: call handler functions directly
- const hooks = this.hooks.get(operationId)?.filter((h) => h.type === type) || [];
-
- for (const hook of hooks) {
- try {
- log('[%s][%s] Dispatching local hook: %s', operationId, type, hook.id);
- await hook.handler(event as AgentHookEvent);
- } catch (error) {
- log('[%s][%s] Hook error (non-fatal): %s %O', operationId, type, hook.id, error);
- // Hook errors should NOT affect main execution flow
- }
- }
- } else {
- // Production mode: deliver via webhooks
- const webhookHooks =
- serializedHooks?.filter(
- (h): h is SerializedHook => h.type === type && h.webhook !== undefined,
- ) ||
- this.getSerializedHooks(operationId)?.filter((h) => h.type === type) ||
- [];
-
- let criticalError: CriticalHookDeliveryError | undefined;
- for (const hook of webhookHooks) {
- try {
- log(
- '[%s][%s] Delivering webhook hook: %s β†’ %s',
- operationId,
- type,
- hook.id,
- hook.webhook.url,
- );
- const webhookPayload = await this.buildWebhookPayload(event, hook.webhook, {
+ const restored = serializedHooks ? parseSerializedHooks(serializedHooks) : undefined;
+
+ const registered = this.hooks.get(operationId);
+ const hooks: (AgentHook | SerializedHook)[] = isQueueMode
+ ? (restored ?? this.getSerializedHooks(operationId) ?? [])
+ : (registered ?? restored ?? []);
+ let criticalError: CriticalHookDeliveryError | undefined;
+ for (const hook of hooks.filter((h) => h.type === type && matchesHook(h.matcher, event))) {
+ const handler = 'handler' in hook ? hook.handler : undefined;
+ const useHandler = !isQueueMode && !!handler;
+ try {
+ if (useHandler) {
+ await handler(event as AgentHookEvent);
+ } else if (hook.webhook) {
+ const payload = await this.buildWebhookPayload(event, hook.webhook, {
hookId: hook.id,
hookType: type,
});
- if (webhookPayload) await deliverWebhook(hook.webhook, webhookPayload);
- } catch (error) {
- if (hook.webhook.fallback === 'none') {
- // No-fallback webhooks carry control flow (e.g. the sub-agent
- // resume bridge) β€” losing one strands its consumer, so surface
- // the failure in production logs, not just the debug namespace.
- console.error(
- `[HookDispatcher][${operationId}][${type}] Webhook delivery failed with no fallback: ${hook.id} β†’ ${hook.webhook.url}`,
- error,
- );
- criticalError ??= new CriticalHookDeliveryError(hook.id, error);
- } else {
- log(
- '[%s][%s] Webhook delivery error (non-fatal): %s %O',
- operationId,
- type,
- hook.id,
- error,
- );
- }
+ if (payload) await deliverWebhook(hook.webhook, payload);
+ }
+ } catch (error) {
+ if (!useHandler && hook.webhook?.fallback === 'none') {
+ console.error(
+ '[HookDispatcher] Critical webhook delivery failed',
+ { operationId, hookId: hook.id, hookType: type },
+ error,
+ );
+ criticalError ??= new CriticalHookDeliveryError(hook.id, error);
+ } else if (!useHandler) {
+ console.error(
+ '[HookDispatcher] Webhook delivery failed (non-fatal)',
+ { operationId, hookId: hook.id, hookType: type },
+ error,
+ );
+ } else {
+ log('[%s][%s] Hook failed (non-fatal): %s', operationId, type, hook.id);
}
}
-
- // Finish independent sibling hooks first, then fail the queue execution.
- // Queue runtimes can retry a lost control-flow handoff instead of
- // reporting success while stranding its consumer.
- if (criticalError) throw criticalError;
}
+ // Independent critical callbacks all get a chance to run before surfacing the failure.
+ if (criticalError) throw criticalError;
}
/**
@@ -202,7 +138,12 @@ export class HookDispatcher {
isMocked: true;
result: ToolRunResult;
} | null> {
- const hooks = this.hooks.get(operationId)?.filter((h) => h.type === 'beforeToolCall') || [];
+ const hooks =
+ this.hooks
+ .get(operationId)
+ ?.filter(
+ (h) => h.type === 'beforeToolCall' && h.handler && matchesHook(h.matcher, event),
+ ) || [];
if (hooks.length === 0) return null;
let isMocked = false;
@@ -222,9 +163,9 @@ export class HookDispatcher {
for (const hook of hooks) {
try {
log('[%s][beforeToolCall] Dispatching: %s', operationId, hook.id);
- await hook.handler(toolCallEvent as any);
- } catch (error) {
- log('[%s][beforeToolCall] Hook error (non-fatal): %s %O', operationId, hook.id, error);
+ await hook.handler?.(toolCallEvent as any);
+ } catch {
+ log('[%s][beforeToolCall] Hook error (non-fatal): %s', operationId, hook.id);
}
if (isMocked) break;
}
@@ -239,13 +180,16 @@ export class HookDispatcher {
const hooks = this.hooks.get(operationId);
if (!hooks) return undefined;
- return hooks
- .filter((h) => h.webhook)
- .map((h) => ({
- id: h.id,
- type: h.type,
- webhook: h.webhook!,
- }));
+ return parseSerializedHooks(
+ hooks
+ .filter((h) => h.webhook)
+ .map((h) => ({
+ id: h.id,
+ matcher: h.matcher,
+ type: h.type,
+ webhook: h.webhook!,
+ })),
+ );
}
/**
@@ -262,7 +206,7 @@ export class HookDispatcher {
/**
* Whether dispatching `type` right now would actually reach a consumer, under
* the rules {@link dispatch} applies for the current runtime mode: local mode
- * needs an in-memory handler, queue mode needs a webhook to deliver.
+ * needs a handler or webhook, queue mode needs a webhook to deliver.
*
* Callers that ALSO surface the same failure themselves (the IM bot bridge
* reports a startup failure inline) ask this before deciding whether their own
@@ -284,8 +228,42 @@ export class HookDispatcher {
register(operationId: string, hooks: AgentHook[]): void {
if (hooks.length === 0) return;
+ // Validate the entire batch before mutating registration state.
+ const validatedHooks = hooks.map((hook) => {
+ agentHookTypeSchema.parse(hook.type);
+ if (typeof hook.id !== 'string') throw new Error('Hook id must be a string');
+ if (hook.matcher !== undefined) {
+ agentHookMatcherSchema.parse(hook.matcher);
+ if (!['beforeToolCall', 'afterToolCall', 'onToolCallError'].includes(hook.type)) {
+ throw new Error('Matchers are only supported for tool events');
+ }
+ }
+ if (hook.handler !== undefined && typeof hook.handler !== 'function') {
+ throw new Error('Hook handler must be a function');
+ }
+ if (hook.webhook) {
+ const parsed = serializedAgentHookSchema.parse({
+ id: hook.id,
+ matcher: hook.matcher,
+ type: hook.type,
+ webhook: hook.webhook,
+ });
+ if (parsed.webhook.responseHandling === 'toolCall') {
+ if (hook.handler) throw new Error('Control hooks cannot have a handler');
+ throw new UnsupportedControlHookError();
+ }
+ return { ...parsed, handler: hook.handler } as AgentHook;
+ } else if (!hook.handler) {
+ throw new Error('A hook requires a handler or webhook');
+ }
+ return {
+ ...hook,
+ matcher:
+ hook.matcher !== undefined ? agentHookMatcherSchema.parse(hook.matcher) : undefined,
+ };
+ });
const existing = this.hooks.get(operationId) || [];
- this.hooks.set(operationId, [...existing, ...hooks]);
+ this.hooks.set(operationId, [...existing, ...validatedHooks]);
log(
'[%s] Registered %d hooks: %s',
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
index d5e93e361cf..bfe2d5666b7 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
@@ -1,3 +1,4 @@
+import type * as Qstash from '@upstash/qstash';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { deliverWebhook, HookDispatcher } from '../HookDispatcher';
@@ -7,7 +8,6 @@ vi.mock('@/database/models/user', () => ({
UserModel: { getEmailsByIds: async () => [] },
}));
vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));
-
// Mock isQueueAgentRuntimeEnabled to control local vs production mode
vi.mock('@/server/services/queue/impls', () => ({
isQueueAgentRuntimeEnabled: vi.fn(function () {
@@ -19,7 +19,8 @@ const mockPublishJSON = vi.hoisted(() => vi.fn());
// Plain class (not vi.fn) so the file-level `vi.restoreAllMocks()` can't wipe
// the implementation between tests.
-vi.mock('@upstash/qstash', () => ({
+vi.mock('@upstash/qstash', async (importOriginal) => ({
+ ...(await importOriginal<typeof Qstash>()),
Client: class {
publishJSON = mockPublishJSON;
},
@@ -154,7 +155,7 @@ describe('HookDispatcher', () => {
beforeEach(() => {
vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
// Mock global fetch
- global.fetch = vi.fn().mockResolvedValue({ status: 200 });
+ global.fetch = vi.fn().mockImplementation(async () => new Response(''));
});
afterEach(() => {
@@ -280,7 +281,7 @@ describe('HookDispatcher', () => {
const originalToken = process.env.QSTASH_TOKEN;
beforeEach(() => {
- global.fetch = vi.fn().mockResolvedValue({ status: 200 });
+ global.fetch = vi.fn().mockImplementation(async () => new Response(''));
mockPublishJSON.mockReset();
delete process.env.QSTASH_TOKEN;
});
@@ -317,11 +318,36 @@ describe('HookDispatcher', () => {
{ delivery: 'qstash', fallback: 'none', url: 'https://example.com/hook' },
{ a: 1 },
),
- ).rejects.toThrow('qstash down');
+ ).rejects.toThrow('network_error: QStash publish failed');
expect(global.fetch).not.toHaveBeenCalled();
});
+ it.each([false, true])(
+ 'does not escalate an accepted large notification (queue=%s)',
+ async (queue) => {
+ vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(queue);
+ vi.mocked(global.fetch).mockResolvedValueOnce(new Response('x'.repeat(100_000)));
+ dispatcher.register(operationId, [
+ {
+ id: 'critical-hook',
+ type: 'onComplete',
+ webhook: { fallback: 'none', url: 'https://example.com/critical' },
+ },
+ ]);
+
+ await expect(
+ dispatcher.dispatch(
+ operationId,
+ 'onComplete',
+ makeEvent(),
+ dispatcher.getSerializedHooks(operationId),
+ ),
+ ).resolves.toBeUndefined();
+ expect(global.fetch).toHaveBeenCalledTimes(1);
+ },
+ );
+
it('dispatch rejects a no-fallback delivery failure after delivering other hooks', async () => {
vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
const consoleError = vi.spyOn(console, 'error').mockImplementation(function () {});
@@ -349,8 +375,9 @@ describe('HookDispatcher', () => {
// The failure is escalated to production logs, and the sibling webhook
// still gets delivered.
expect(consoleError).toHaveBeenCalledWith(
- expect.stringContaining('critical-hook'),
- expect.any(Error),
+ '[HookDispatcher] Critical webhook delivery failed',
+ { operationId, hookId: 'critical-hook', hookType: 'onComplete' },
+ expect.objectContaining({ code: 'configuration' }),
);
expect(global.fetch).toHaveBeenCalledWith(
'https://example.com/normal',
@@ -1114,7 +1141,7 @@ describe('HookDispatcher', () => {
it('observation hooks should work in production mode via serializedHooks', async () => {
vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
- global.fetch = vi.fn().mockResolvedValue({ status: 200 });
+ global.fetch = vi.fn().mockImplementation(async () => new Response(''));
dispatcher.register(operationId, [
{
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.ts
new file mode 100644
index 00000000000..084b5718995
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.ts
@@ -0,0 +1,250 @@
+import type { SerializedAgentHook } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { HookDispatcher, UnsupportedControlHookError } from '../HookDispatcher';
+import { matchesHook } from '../matcher';
+import type { AgentHook, AgentHookEvent } from '../types';
+
+const { fetchMock, queueMode } = vi.hoisted(() => ({ fetchMock: vi.fn(), queueMode: vi.fn() }));
+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: queueMode }));
+vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));
+vi.mock('@/database/models/user', () => ({
+ UserModel: { getEmailsByIds: async () => [{ id: 'user', email: '[email protected]' }] },
+}));
+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));
+
+beforeEach(() => {
+ vi.stubGlobal('fetch', fetchMock);
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+const event: AgentHookEvent = {
+ operationId: 'op',
+ userId: 'user',
+ agentId: 'agent',
+ status: 'done',
+};
+const hook: AgentHook = {
+ id: 'notification',
+ type: 'onComplete',
+ webhook: { url: 'https://example.com/hooks' },
+};
+
+describe('hook registration and restoration', () => {
+ beforeEach(() => {
+ fetchMock.mockReset().mockImplementation(async () => new Response('{}'));
+ queueMode.mockReturnValue(false);
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+ it.each([false, true])('sends webhook-only hooks in queue=%s', async (queue) => {
+ queueMode.mockReturnValue(queue);
+ const dispatcher = new HookDispatcher();
+ dispatcher.register('op', [hook]);
+ await dispatcher.dispatch('op', 'onComplete', event);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toMatchObject({
+ operationId: 'op',
+ hookId: 'notification',
+ userEmail: '[email protected]',
+ });
+ });
+ it.each([false, true])(
+ 'restores and validates notifications in a new worker queue=%s',
+ async (queue) => {
+ queueMode.mockReturnValue(queue);
+ const dispatcher = new HookDispatcher();
+ dispatcher.register('op', [hook]);
+ const restored = new HookDispatcher();
+ const persisted = JSON.stringify(dispatcher.getSerializedHooks('op'));
+ await restored.dispatch('op', 'onComplete', event, JSON.parse(persisted));
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ },
+ );
+ it('retains dual handler/webhook mode selection', async () => {
+ const handler = vi.fn();
+ const dispatcher = new HookDispatcher();
+ dispatcher.register('op', [{ ...hook, handler }]);
+ await dispatcher.dispatch('op', 'onComplete', event);
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(fetchMock).not.toHaveBeenCalled();
+ queueMode.mockReturnValue(true);
+ await dispatcher.dispatch('op', 'onComplete', event);
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+ it('retains matcher and fallback:none through serialization', () => {
+ const dispatcher = new HookDispatcher();
+ const serialized = {
+ id: 'tool',
+ type: 'afterToolCall' as const,
+ matcher: '^fs/',
+ webhook: { url: '/hook', fallback: 'none' as const },
+ };
+ dispatcher.register('op', [serialized]);
+ expect(dispatcher.getSerializedHooks('op')).toEqual([serialized]);
+ });
+ it('blocks unsupported controls on registration atomically and on restore before event selection', async () => {
+ const dispatcher = new HookDispatcher();
+ const control: AgentHook = {
+ id: 'control',
+ type: 'beforeToolCall',
+ webhook: { url: '/hook', responseHandling: 'toolCall' },
+ };
+ expect(() => dispatcher.register('op', [hook, control])).toThrow(UnsupportedControlHookError);
+ expect(dispatcher.hasHooks('op')).toBe(false);
+ for (const queue of [false, true]) {
+ queueMode.mockReturnValue(queue);
+ await expect(
+ dispatcher.dispatch('op', 'onComplete', event, [control as SerializedAgentHook]),
+ ).rejects.toThrow(UnsupportedControlHookError);
+ }
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ it.each([
+ { id: 'empty', type: 'onComplete' },
+ { ...hook, handler: 'not a function' },
+ { ...hook, matcher: '' },
+ { ...hook, matcher: '*' },
+ { ...hook, type: 'beforeToolCall', matcher: { identifier: '^fs$' } },
+ { ...hook, type: 'beforeToolCall', matcher: '[' },
+ {
+ ...hook,
+ type: 'beforeToolCall',
+ handler: async () => {},
+ webhook: { url: '/hook', responseHandling: 'toolCall' },
+ },
+ ])('rejects invalid registration %#', (invalid) => {
+ expect(() => new HookDispatcher().register('op', [invalid as AgentHook])).toThrow();
+ });
+ it('rejects corrupt restored configurations instead of stripping controls', async () => {
+ await expect(
+ new HookDispatcher().dispatch('op', 'onComplete', event, [
+ {
+ ...hook,
+ webhook: { url: '/hook', responseHandling: 'futureControl' },
+ } as unknown as SerializedAgentHook,
+ ]),
+ ).rejects.toThrow();
+ });
+ it('matches a restored queue webhook against the combined tool name', async () => {
+ queueMode.mockReturnValue(true);
+ const dispatcher = new HookDispatcher();
+ const stored: SerializedAgentHook[] = [
+ {
+ id: 'tool',
+ type: 'beforeToolCall',
+ matcher: '^fs/readFile$',
+ webhook: { url: 'https://example.com/hook' },
+ },
+ ];
+ const tool = {
+ apiName: 'readFile',
+ assistantMessageId: 'assistant',
+ args: {},
+ callIndex: 0,
+ executor: 'server' as const,
+ identifier: 'other',
+ operationId: 'op',
+ stepIndex: 0,
+ toolCallId: 'call',
+ };
+ await dispatcher.dispatch('op', 'beforeToolCall', tool, stored);
+ expect(fetchMock).not.toHaveBeenCalled();
+ await dispatcher.dispatch('op', 'beforeToolCall', { ...tool, identifier: 'fs' }, stored);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await expect(
+ dispatcher.dispatch('op', 'beforeToolCall', tool, [{ ...stored[0], matcher: '[' }]),
+ ).rejects.toThrow();
+ });
+ it('matches local handlers, HTTP notifications and mock callbacks', async () => {
+ const dispatcher = new HookDispatcher();
+ const handler = vi.fn();
+ dispatcher.register('op', [
+ {
+ id: 'mock',
+ type: 'beforeToolCall',
+ matcher: '^fs/read',
+ handler,
+ },
+ { ...hook, type: 'beforeToolCall', matcher: '^fs/' },
+ ]);
+ const tool = {
+ apiName: 'readFile',
+ args: {},
+ assistantMessageId: 'assistant',
+ callIndex: 0,
+ executor: 'server' as const,
+ identifier: 'other',
+ stepIndex: 0,
+ toolCallId: 'call',
+ };
+ await dispatcher.dispatchBeforeToolCall('op', tool);
+ await dispatcher.dispatch('op', 'beforeToolCall', { ...tool, operationId: 'op' });
+ expect(handler).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ await dispatcher.dispatch('op', 'beforeToolCall', {
+ ...tool,
+ identifier: 'fs',
+ operationId: 'op',
+ });
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('matcher semantics', () => {
+ it.each([undefined, '', '*'])('matches wildcard %#', (matcher) => {
+ expect(matchesHook(matcher, { identifier: 'any', apiName: 'any' })).toBe(true);
+ });
+ it('matches the combined tool name and never retains regex state', () => {
+ const matcher = '^fs/read';
+ for (let i = 0; i < 3; i++)
+ expect(matchesHook(matcher, { identifier: 'fs', apiName: 'readFile' })).toBe(true);
+ expect(matchesHook(matcher, { identifier: 'fs', apiName: 'writeFile' })).toBe(false);
+ expect(matchesHook(matcher, { identifier: 'http', apiName: 'readFile' })).toBe(false);
+ expect(matchesHook(matcher, {})).toBe(false);
+ });
+ it('supports alternation across the combined identifier/apiName boundary', () => {
+ const matcher = '^(fs/readFile|http/get)$';
+ expect(matchesHook(matcher, { identifier: 'fs', apiName: 'readFile' })).toBe(true);
+ expect(matchesHook(matcher, { identifier: 'http', apiName: 'get' })).toBe(true);
+ expect(matchesHook(matcher, { identifier: 'fs', apiName: 'get' })).toBe(false);
+ expect(matchesHook(matcher, { identifier: 'http', apiName: 'readFile' })).toBe(false);
+ expect(matchesHook('undefined/readFile', { apiName: 'readFile' })).toBe(false);
+ });
+});
+
+describe('registration snapshots', () => {
+ it('snapshots the matcher value and webhook configuration', async () => {
+ queueMode.mockReturnValue(false);
+ fetchMock.mockReset().mockImplementation(async () => new Response('{}'));
+ const dispatcher = new HookDispatcher();
+ const source: AgentHook = {
+ id: 'snapshot',
+ type: 'beforeToolCall',
+ matcher: '^fs/',
+ webhook: { url: 'https://example.com/original', headers: { 'X-Version': 'original' } },
+ };
+ dispatcher.register('op', [source]);
+ source.matcher = '^other/';
+ source.webhook!.url = 'https://example.com/changed';
+ source.webhook!.headers!['X-Version'] = 'changed';
+ await dispatcher.dispatch('op', 'beforeToolCall', {
+ apiName: 'read',
+ args: {},
+ assistantMessageId: 'assistant',
+ callIndex: 0,
+ executor: 'server',
+ identifier: 'fs',
+ operationId: 'op',
+ stepIndex: 0,
+ toolCallId: 'call',
+ });
+ expect(fetchMock.mock.calls[0][0]).toBe('https://example.com/original');
+ expect(fetchMock.mock.calls[0][1].headers['x-version']).toBe('original');
+ });
+});
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
new file mode 100644
index 00000000000..b9bb95cf8e9
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.network.test.ts
@@ -0,0 +1,106 @@
+import type { Server } from 'node:http';
+import { createServer } from 'node:http';
+import { inspect } from 'node:util';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { deliverWebhook, executeToolCallWebhook } from '../httpWebhook';
+
+vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));
+
+/** Real socket tests: no fetch mocks. */
+describe('HTTP hook network boundary', () => {
+ let server: Server;
+ let base: string;
+ let requests: string[];
+ beforeEach(async () => {
+ requests = [];
+ server = createServer((req, res) => {
+ requests.push(req.url!);
+ if (req.url === '/redirect') {
+ res.writeHead(302, { Location: `${base}/leaked` });
+ res.end();
+ } else if (req.url?.startsWith('/disconnect')) {
+ req.socket.destroy();
+ } else if (req.url === '/large') {
+ res.writeHead(200);
+ res.end('x'.repeat(100_000));
+ } else if (req.url === '/slow') {
+ res.writeHead(200);
+ res.write('{');
+ } else {
+ res.writeHead(204);
+ res.end();
+ }
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Missing test server address');
+ base = `http://127.0.0.1:${address.port}`;
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', undefined);
+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', undefined);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+ afterEach(async () => {
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+ const config = (url: string) => ({ responseHandling: 'toolCall' as const, url });
+ it.each(['INTERNAL_APP_URL', 'APP_URL'])(
+ 'delivers relative hooks through %s without private-network overrides',
+ async (variable) => {
+ vi.stubEnv('INTERNAL_APP_URL', undefined);
+ vi.stubEnv('APP_URL', undefined);
+ vi.stubEnv(variable, base);
+ vi.stubEnv('QSTASH_TOKEN', undefined);
+ await expect(deliverWebhook({ url: '/hook' }, {})).resolves.toBeUndefined();
+ await expect(
+ deliverWebhook({ url: '/hook', delivery: 'qstash' }, {}),
+ ).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(
+ await executeToolCallWebhook(config(`${base}/disconnect?signature=TEST_QUERY_SECRET`), {}),
+ ).toEqual({ code: 'network_error', status: 'error' });
+ expect(inspect(logger.mock.calls)).not.toContain('TEST_QUERY_SECRET');
+ });
+ it.each(['/large', '/slow'])('ignores successful notification bodies at %s', async (path) => {
+ await expect(
+ deliverWebhook({ url: `${base}${path}`, fallback: 'none', timeout: 0.5 }, {}),
+ ).resolves.toBeUndefined();
+ expect(requests).toEqual([path]);
+ });
+ it.each(['/large', '/slow'])('ignores successful fetch fallback bodies at %s', async (path) => {
+ vi.stubEnv('QSTASH_TOKEN', undefined);
+ await expect(
+ deliverWebhook({ url: `${base}${path}`, delivery: 'qstash', timeout: 0.5 }, {}),
+ ).resolves.toBeUndefined();
+ expect(requests).toEqual([path]);
+ });
+ it('never forwards auth to a redirect target', async () => {
+ expect(
+ await executeToolCallWebhook(
+ { ...config(`${base}/redirect`), headers: { Authorization: 'test-only' } },
+ {},
+ ),
+ ).toMatchObject({ status: 'error' });
+ expect(requests).toEqual(['/redirect']);
+ });
+ it('rejects oversized bodies and bounds body-read time', async () => {
+ expect(await executeToolCallWebhook(config(`${base}/large`), {})).toEqual({
+ status: 'error',
+ code: 'response_too_large',
+ });
+ expect(await executeToolCallWebhook({ ...config(`${base}/slow`), timeout: 0.03 }, {})).toEqual({
+ status: 'error',
+ code: 'timeout',
+ });
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.test.ts
new file mode 100644
index 00000000000..7b00ca583af
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/httpWebhook.test.ts
@@ -0,0 +1,252 @@
+import { inspect } from 'node:util';
+
+import { QstashError } from '@upstash/qstash';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { deliverWebhook, executeToolCallWebhook, resolveWebhookHeaders } from '../httpWebhook';
+
+const { fetchMock, publish } = vi.hoisted(() => ({ fetchMock: vi.fn(), publish: vi.fn() }));
+vi.mock('@/libs/qstash', () => ({
+ OtelQstashClient: class {
+ publishJSON = publish;
+ },
+}));
+beforeEach(() => {
+ vi.stubGlobal('fetch', fetchMock);
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+const config = { responseHandling: 'toolCall' as const, url: 'https://example.com/hooks' };
+
+describe('HTTP hook primitive', () => {
+ beforeEach(() => {
+ fetchMock.mockReset();
+ publish.mockReset();
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+ });
+
+ it('uses fetch without redirects and with a default deadline', async () => {
+ fetchMock.mockResolvedValue(new Response('{}'));
+ expect(await executeToolCallWebhook(config, { args: { value: 1 } })).toMatchObject({
+ status: 'success',
+ });
+ const [, request] = fetchMock.mock.calls[0];
+ expect(request).toMatchObject({
+ method: 'POST',
+ redirect: 'error',
+ body: '{"args":{"value":1}}',
+ });
+ expect(request.signal).toBeInstanceOf(AbortSignal);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+ it.each([200, 204, 205])('accepts empty 2xx %i', async (status) => {
+ fetchMock.mockResolvedValue(new Response(null, { status }));
+ expect(await executeToolCallWebhook(config, {})).toEqual({ status: 'success' });
+ });
+ it.each([301, 400, 500])('rejects status %i without parsing the body', async (status) => {
+ fetchMock.mockResolvedValue(
+ new Response(
+ '{"hookSpecificOutput":{"hookEventName":"beforeToolCall","permissionDecision":"allow"}}',
+ { status },
+ ),
+ );
+ expect(await executeToolCallWebhook(config, {})).toEqual({
+ status: 'error',
+ code: 'http_error',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+ it('returns sanitized errors and never retries', async () => {
+ fetchMock.mockRejectedValue(new Error('secret remote response'));
+ expect(await executeToolCallWebhook(config, {})).toEqual({
+ status: 'error',
+ code: 'network_error',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+ it('rejects oversize before parsing, including whitespace', async () => {
+ fetchMock.mockResolvedValue(new Response('{}' + ' '.repeat(65_535)));
+ expect(await executeToolCallWebhook(config, {})).toEqual({
+ status: 'error',
+ code: 'response_too_large',
+ });
+ });
+ it('times out while waiting and distinguishes cancellation', async () => {
+ fetchMock.mockImplementation(
+ (_url, { signal }) =>
+ new Promise((_, reject) =>
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true }),
+ ),
+ );
+ expect(await executeToolCallWebhook({ ...config, timeout: 0.01 }, {})).toEqual({
+ status: 'error',
+ code: 'timeout',
+ });
+ const controller = new AbortController();
+ const pending = executeToolCallWebhook(config, {}, { signal: controller.signal });
+ controller.abort();
+ expect(await pending).toEqual({ status: 'cancelled' });
+ expect(await executeToolCallWebhook(config, {}, { signal: controller.signal })).toEqual({
+ status: 'cancelled',
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ it('discards a late allow after cancellation even if transport ignores abort', async () => {
+ const controller = new AbortController();
+ fetchMock.mockImplementation(async () => {
+ controller.abort();
+ return new Response(
+ '{"hookSpecificOutput":{"hookEventName":"beforeToolCall","permissionDecision":"allow"}}',
+ );
+ });
+ expect(await executeToolCallWebhook(config, {}, { signal: controller.signal })).toEqual({
+ status: 'cancelled',
+ });
+ });
+ it('refuses controls in the notification path and invalid control config before sending', async () => {
+ await expect(deliverWebhook(config, {})).rejects.toThrow('configuration');
+ expect(await executeToolCallWebhook({ ...config, eventFields: [] }, {})).toEqual({
+ status: 'error',
+ code: 'configuration',
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ it('ignores legacy notification response bodies', async () => {
+ fetchMock.mockResolvedValueOnce(new Response('not json'));
+ fetchMock.mockResolvedValueOnce(new Response(new Uint8Array([0xff])));
+ await expect(
+ deliverWebhook({ url: config.url, fallback: 'none' }, {}),
+ ).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');
+ const webhook = {
+ ...config,
+ allowedEnvVars: ['HOOK_TOKEN'],
+ headers: { 'Authorization': 'Bearer ${HOOK_TOKEN}', 'X-Static': 'value' },
+ };
+ expect(resolveWebhookHeaders(webhook).authorization).toBe('Bearer first-secret');
+ vi.stubEnv('HOOK_TOKEN', 'rotated-secret');
+ expect(resolveWebhookHeaders(webhook).authorization).toBe('Bearer rotated-secret');
+ expect(webhook.headers.Authorization).toBe('Bearer ${HOOK_TOKEN}');
+ expect(() => resolveWebhookHeaders({ ...webhook, allowedEnvVars: [] })).toThrow(
+ 'configuration',
+ );
+ vi.stubEnv('HOOK_TOKEN', undefined);
+ expect(() => resolveWebhookHeaders(webhook)).toThrow('configuration');
+ });
+ it.each<Record<string, string>>([
+ { Host: 'internal' },
+ { 'Content-Length': '1' },
+ { 'Upstash-Callback': 'evil' },
+ { 'X-Key': '${NOPE}' },
+ { 'X-Key': 'bad\r\nsecret' },
+ { 'X-Key': '${broken' },
+ ])('rejects unsafe headers %#', (headers) => {
+ expect(() => resolveWebhookHeaders({ ...config, headers })).toThrow('configuration');
+ });
+ it('forwards templates and timeout to QStash; fallback:none never sends unsigned fetch', async () => {
+ vi.stubEnv('QSTASH_TOKEN', 'test-token');
+ vi.stubEnv('HOOK_TOKEN', 'secret');
+ const webhook = {
+ url: config.url,
+ delivery: 'qstash' as const,
+ timeout: 4,
+ fallback: 'none' as const,
+ headers: { Authorization: 'Bearer ${HOOK_TOKEN}' },
+ allowedEnvVars: ['HOOK_TOKEN'],
+ };
+ await deliverWebhook(webhook, { value: 1 });
+ expect(publish.mock.calls[0][0]).toMatchObject({
+ headers: { authorization: 'Bearer secret' },
+ timeout: 4,
+ });
+ publish.mockRejectedValue(new Error('remote secret'));
+ await expect(deliverWebhook(webhook, {})).rejects.toThrow('network_error');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ it('missing QStash token falls back once, never retries a failed fetch', async () => {
+ vi.stubEnv('QSTASH_TOKEN', undefined);
+ fetchMock.mockRejectedValue(new Error('offline'));
+ await expect(deliverWebhook({ url: config.url, delivery: 'qstash' }, {})).rejects.toThrow(
+ 'network_error',
+ );
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(publish).not.toHaveBeenCalled();
+ });
+ it('preserves the missing-token configuration diagnosis without unsigned fallback', async () => {
+ vi.stubEnv('QSTASH_TOKEN', undefined);
+ await expect(
+ deliverWebhook({ url: config.url, delivery: 'qstash', fallback: 'none' }, {}),
+ ).rejects.toMatchObject({
+ code: 'configuration',
+ message: expect.stringContaining('QSTASH_TOKEN not available'),
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ it.each([401, 429, 503])(
+ 'preserves QStash HTTP %i without exposing SDK response data',
+ async (status) => {
+ vi.stubEnv('QSTASH_TOKEN', 'private-token');
+ const sdkError = new QstashError('private-response private-token private-header', status);
+ Object.assign(sdkError, { headers: { Authorization: 'private-header' } });
+ publish.mockRejectedValue(sdkError);
+ const error = await deliverWebhook(
+ { url: config.url, delivery: 'qstash', fallback: 'none' },
+ {},
+ ).catch((error: unknown) => error);
+ expect(error).toMatchObject({
+ code: 'http_error',
+ status,
+ message: expect.stringContaining(`QStash publish failed (HTTP ${status})`),
+ });
+ expect(inspect(error)).not.toMatch(/private-response|private-token|private-header/);
+ expect(fetchMock).not.toHaveBeenCalled();
+ },
+ );
+ it('logs the QStash failure even when fetch fallback succeeds', async () => {
+ vi.stubEnv('QSTASH_TOKEN', 'private-token');
+ publish.mockRejectedValue(new QstashError('private-response', 503));
+ fetchMock.mockResolvedValue(new Response(null, { status: 204 }));
+ const logger = vi.spyOn(console, 'error').mockImplementation(() => {});
+ await expect(
+ deliverWebhook({ url: config.url, delivery: 'qstash' }, {}),
+ ).resolves.toBeUndefined();
+ expect(logger).toHaveBeenCalledWith(
+ '[HookDispatcher] QStash delivery failed, falling back to fetch',
+ expect.objectContaining({ code: 'http_error', status: 503 }),
+ );
+ expect(inspect(logger.mock.calls)).not.toContain('private-response');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('credential and response boundaries', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+ it('adds automatic deployment bypass only for the configured application origin', async () => {
+ publish.mockReset().mockResolvedValue({ messageId: 'test' });
+ vi.stubEnv('QSTASH_TOKEN', 'test-token');
+ vi.stubEnv('APP_URL', 'https://app.example.com');
+ vi.stubEnv('INTERNAL_APP_URL', undefined);
+ vi.stubEnv('VERCEL_AUTOMATION_BYPASS_SECRET', 'private-bypass');
+ await deliverWebhook({ delivery: 'qstash', url: 'https://external.example.com/hook' }, {});
+ expect(publish.mock.calls[0][0].headers).not.toHaveProperty('x-vercel-protection-bypass');
+ await deliverWebhook({ delivery: 'qstash', url: '/hook' }, {});
+ expect(publish.mock.calls[1][0].headers['x-vercel-protection-bypass']).toBe('private-bypass');
+ });
+ it('reports invalid UTF-8 as a protocol error', async () => {
+ fetchMock.mockResolvedValue(new Response(new Uint8Array([0xc3, 0x28])));
+ expect(await executeToolCallWebhook(config, {})).toEqual({
+ code: 'invalid_response',
+ status: 'error',
+ });
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts b/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
new file mode 100644
index 00000000000..f7358ff8d69
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts
@@ -0,0 +1,215 @@
+import type { ToolCallHookExecutionResult } from '@lobechat/types';
+import {
+ AGENT_HOOK_RESPONSE_MAX_BYTES,
+ agentHookWebhookSchema,
+ parseToolCallHookResponse,
+} from '@lobechat/types';
+import { readBlobWithLimit } from '@lobechat/utils/readBlobWithLimit';
+import { QstashError } from '@upstash/qstash';
+
+import { OtelQstashClient } from '@/libs/qstash';
+
+import type { AgentHookWebhook } from './types';
+
+class HookHttpError extends Error {
+ readonly status?: number;
+
+ constructor(
+ public readonly code:
+ | 'configuration'
+ | 'http_error'
+ | 'invalid_response'
+ | 'network_error'
+ | 'response_too_large'
+ | 'timeout',
+ diagnostic?: { message: string; status?: number },
+ ) {
+ super(`Hook HTTP request failed: ${code}${diagnostic ? `: ${diagnostic.message}` : ''}`);
+ this.name = 'HookHttpError';
+ this.status = diagnostic?.status;
+ }
+}
+
+function resolveUrl(url: string): string {
+ try {
+ const resolved = new URL(url, process.env.INTERNAL_APP_URL || process.env.APP_URL || undefined);
+ if (
+ !['http:', 'https:'].includes(resolved.protocol) ||
+ resolved.username ||
+ resolved.password
+ ) {
+ throw new Error('Invalid webhook configuration');
+ }
+ return resolved.href;
+ } catch {
+ throw new HookHttpError('configuration');
+ }
+}
+
+function isApplicationOrigin(url: string): boolean {
+ return [process.env.INTERNAL_APP_URL, process.env.APP_URL].some((base) => {
+ if (!base) return false;
+ try {
+ return new URL(base).origin === new URL(url).origin;
+ } catch {
+ return false;
+ }
+ });
+}
+
+/** Only explicitly allowlisted variables are expanded; errors never contain their values. */
+export function resolveWebhookHeaders(webhook: AgentHookWebhook): Record<string, string> {
+ const headers = new Headers({ 'Content-Type': 'application/json' });
+ const allowed = new Set(webhook.allowedEnvVars ?? []);
+ try {
+ for (const [name, template] of Object.entries(webhook.headers ?? {})) {
+ if (
+ /^(?:host|content-length|connection|transfer-encoding|trailer|upgrade|proxy-.*|sec-.*|upstash-.*)$/i.test(
+ name,
+ )
+ ) {
+ throw new Error('Invalid webhook configuration');
+ }
+ const value = template.replaceAll(/\$\{([^}]*)\}/g, (_, variable: string) => {
+ if (!allowed.has(variable) || process.env[variable] === undefined)
+ throw new Error('Invalid webhook configuration');
+ return process.env[variable]!;
+ });
+ if (value.includes('${') || /[\r\n\0]/.test(value))
+ throw new Error('Invalid webhook configuration');
+ headers.set(name, value);
+ }
+ return Object.fromEntries(headers.entries());
+ } catch {
+ throw new HookHttpError('configuration');
+ }
+}
+
+async function fetchWebhook<T>(
+ webhook: AgentHookWebhook,
+ payload: Record<string, unknown>,
+ handleResponse: (response: Response, signal: AbortSignal) => Promise<T>,
+ signal?: AbortSignal,
+): Promise<T> {
+ const timeout = AbortSignal.timeout(Math.ceil((webhook.timeout ?? 30) * 1000));
+ const combinedSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
+ try {
+ combinedSignal.throwIfAborted();
+ const response = await fetch(resolveUrl(webhook.url), {
+ body: JSON.stringify(payload),
+ headers: resolveWebhookHeaders(webhook),
+ method: 'POST',
+ redirect: 'error',
+ signal: combinedSignal,
+ });
+ combinedSignal.throwIfAborted();
+ if (response.status < 200 || response.status >= 300) {
+ await response.body?.cancel();
+ throw new HookHttpError('http_error');
+ }
+ return await handleResponse(response, combinedSignal);
+ } catch (error) {
+ if (signal?.aborted) throw error;
+ if (timeout.aborted) throw new HookHttpError('timeout');
+ if (error instanceof HookHttpError) throw error;
+ throw new HookHttpError('network_error');
+ }
+}
+
+async function discardNotificationBody(response: Response): Promise<void> {
+ try {
+ await response.body?.cancel();
+ } catch {
+ // A cleanup failure must not turn an accepted notification into a retry.
+ console.error('[HookDispatcher] Failed to discard notification response body');
+ }
+}
+
+async function readControlBody(response: Response, signal: AbortSignal): Promise<ArrayBuffer> {
+ const body = await readBlobWithLimit(response, AGENT_HOOK_RESPONSE_MAX_BYTES).catch(
+ (error: unknown) => {
+ if (error instanceof RangeError) throw new HookHttpError('response_too_large');
+ throw error;
+ },
+ );
+ const buffer = await body.arrayBuffer();
+ signal.throwIfAborted();
+ return buffer;
+}
+
+/** Notification transport. A control config must never be sent through a response-ignoring path. */
+export async function deliverWebhook(
+ webhook: AgentHookWebhook,
+ payload: Record<string, unknown>,
+): Promise<void> {
+ const parsed = agentHookWebhookSchema.safeParse(webhook);
+ if (!parsed.success || webhook.responseHandling === 'toolCall')
+ throw new HookHttpError('configuration');
+ if (webhook.delivery !== 'qstash') {
+ await fetchWebhook(webhook, payload, discardNotificationBody);
+ return;
+ }
+
+ const url = resolveUrl(webhook.url);
+ const headers = resolveWebhookHeaders(webhook);
+ try {
+ if (!process.env.QSTASH_TOKEN)
+ throw new HookHttpError('configuration', { message: 'QSTASH_TOKEN not available' });
+ const client = new OtelQstashClient({ token: process.env.QSTASH_TOKEN });
+ await client.publishJSON({
+ body: payload,
+ headers: {
+ ...headers,
+ ...(isApplicationOrigin(url) &&
+ process.env.VERCEL_AUTOMATION_BYPASS_SECRET && {
+ 'x-vercel-protection-bypass': process.env.VERCEL_AUTOMATION_BYPASS_SECRET,
+ }),
+ },
+ timeout: webhook.timeout ?? 30,
+ url,
+ });
+ } catch (error) {
+ // Keep safe diagnostics, never the SDK message/cause, headers or remote response text.
+ const status = error instanceof QstashError ? error.status : undefined;
+ const failure =
+ error instanceof HookHttpError
+ ? error
+ : status !== undefined
+ ? new HookHttpError('http_error', {
+ message: `QStash publish failed (HTTP ${status})`,
+ status,
+ })
+ : new HookHttpError('network_error', { message: 'QStash publish failed' });
+ if (webhook.fallback === 'none') throw failure;
+ console.error('[HookDispatcher] QStash delivery failed, falling back to fetch', failure);
+ await fetchWebhook(webhook, payload, discardNotificationBody);
+ }
+}
+
+/**
+ * C1 preparation primitive. No retries, side effects on tools, or application of decisions.
+ * The caller supplies the full authoritative event and handles cancellation before onError.
+ */
+export async function executeToolCallWebhook(
+ webhook: AgentHookWebhook,
+ payload: Record<string, unknown>,
+ options: { signal?: AbortSignal } = {},
+): Promise<ToolCallHookExecutionResult> {
+ if (options.signal?.aborted) return { status: 'cancelled' };
+ const parsed = agentHookWebhookSchema.safeParse(webhook);
+ if (!parsed.success || webhook.responseHandling !== 'toolCall') {
+ return { code: 'configuration', status: 'error' };
+ }
+ try {
+ const body = await fetchWebhook(parsed.data, payload, readControlBody, options.signal);
+ if (options.signal?.aborted) return { status: 'cancelled' };
+ try {
+ return parseToolCallHookResponse(new TextDecoder('utf-8', { fatal: true }).decode(body));
+ } catch {
+ return { code: 'invalid_response', status: 'error' };
+ }
+ } catch (error) {
+ if (options.signal?.aborted) return { status: 'cancelled' };
+ return { code: error instanceof HookHttpError ? error.code : 'network_error', status: 'error' };
+ }
+}
diff --git a/apps/server/src/services/agentRuntime/hooks/index.ts b/apps/server/src/services/agentRuntime/hooks/index.ts
index 8a1e83ce7e2..fa1cd129382 100644
--- a/apps/server/src/services/agentRuntime/hooks/index.ts
+++ b/apps/server/src/services/agentRuntime/hooks/index.ts
@@ -1,9 +1,18 @@
-export { CriticalHookDeliveryError, HookDispatcher, hookDispatcher } from './HookDispatcher';
+export {
+ CriticalHookDeliveryError,
+ HookDispatcher,
+ hookDispatcher,
+ parseSerializedHooks,
+ UnsupportedControlHookError,
+} from './HookDispatcher';
+export { executeToolCallWebhook } from './httpWebhook';
+export { matchesHook } from './matcher';
export type {
AgentHook,
AgentHookEvent,
AgentHookType,
AgentHookWebhook,
AgentHookWebhookPayload,
+ NotificationWebhook,
SerializedHook,
} from './types';
diff --git a/apps/server/src/services/agentRuntime/hooks/matcher.ts b/apps/server/src/services/agentRuntime/hooks/matcher.ts
new file mode 100644
index 00000000000..3dd743f9ac6
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/hooks/matcher.ts
@@ -0,0 +1,10 @@
+import type { AgentHookMatcher } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+
+/** Match the combined tool name; registration/restoration validates the regex first. */
+export function matchesHook(matcher: AgentHookMatcher | undefined, event: unknown): boolean {
+ if (!matcher || matcher === '*') return true;
+ if (!isRecord(event) || typeof event.identifier !== 'string' || typeof event.apiName !== 'string')
+ return false;
+ return new RegExp(matcher).test(`${event.identifier}/${event.apiName}`);
+}
diff --git a/apps/server/src/services/agentRuntime/hooks/types.ts b/apps/server/src/services/agentRuntime/hooks/types.ts
index 54895233ca0..f46dfeb2b32 100644
--- a/apps/server/src/services/agentRuntime/hooks/types.ts
+++ b/apps/server/src/services/agentRuntime/hooks/types.ts
@@ -6,7 +6,11 @@
*/
import type { AgentHookEvent, AgentHookType, AnyHookEvent } from '@lobechat/agent-runtime';
-import type { AgentHookWebhookConfig, SerializedAgentHook } from '@lobechat/types';
+import type {
+ AgentHookMatcher,
+ AgentHookWebhookConfig,
+ SerializedAgentHook,
+} from '@lobechat/types';
export type {
AfterCallAgentHookEvent,
@@ -33,59 +37,38 @@ export type {
export type AgentHookWebhookPayload = Partial<AnyHookEvent> &
Record<string, unknown> & { userEmail?: string };
-/**
- * Webhook delivery configuration for production mode.
- *
- * Runtime-precise refinement of the serialized wire shape
- * ({@link AgentHookWebhookConfig} in `@lobechat/types`, used for persistence /
- * zod validation): the shared `body` / `delivery` / `url` are inherited, while
- * `eventFields` is extended with tool-result and email fields and the server-only
- * `fallback` policy is added.
- */
-export interface AgentHookWebhook extends Omit<AgentHookWebhookConfig, 'eventFields'> {
- /** Event fields to include in the webhook payload. Defaults to all serializable event fields. */
- eventFields?: (keyof AgentHookEvent | 'result' | 'mocked' | 'userEmail')[];
+/** Same schema and type in memory and persisted state, including fallback and header templates. */
+export type AgentHookWebhook = AgentHookWebhookConfig;
- /**
- * Behavior when QStash delivery fails (publish error or missing
- * QSTASH_TOKEN). 'fetch' (default, legacy) retries as a plain unsigned
- * POST; 'none' throws instead. Use 'none' for endpoints behind QStash
- * signature auth β€” an unsigned fallback can never authenticate there, so
- * it only masks the delivery failure as a silently-dropped 401.
- */
- fallback?: 'fetch' | 'none';
-}
-
-/**
- * Hook definition β€” consumers register these with execAgent
- */
-export interface AgentHook {
- /** Handler function for local mode (called in-process) */
- handler: (event: AgentHookEvent) => Promise<void>;
+type HookHandler = (event: AgentHookEvent) => Promise<void>;
+export type NotificationWebhook = AgentHookWebhook & {
+ onError?: 'continue';
+ responseHandling?: 'ignore';
+};
- /** Unique hook identifier (for logging, debugging, idempotency) */
+/** Control hooks are webhook-only and synchronous. Runtime support is gated by registration. */
+export type AgentHook = {
id: string;
-
- /** Hook lifecycle point */
- type: AgentHookType;
-
- /** Webhook config for production mode (if omitted, hook only works in local mode) */
- webhook?: AgentHookWebhook;
-}
+ matcher?: AgentHookMatcher;
+} & (
+ | {
+ handler?: never;
+ type: 'beforeToolCall';
+ webhook: AgentHookWebhook & { delivery?: 'fetch'; responseHandling: 'toolCall' };
+ }
+ | {
+ handler: HookHandler;
+ type: AgentHookType;
+ webhook?: NotificationWebhook;
+ }
+ | {
+ handler?: never;
+ type: AgentHookType;
+ webhook: NotificationWebhook;
+ }
+);
// ── Serialized Hook (for Redis persistence) ──────────────
-/**
- * Serialized hook config stored in AgentState.host.hooks (and on
- * `topic.metadata.runningOperation.hooks`). Only contains webhook info β€”
- * handler functions can't be serialized.
- *
- * Runtime-precise refinement of the wire shape ({@link SerializedAgentHook} in
- * `@lobechat/types`): `type` is narrowed to `AgentHookType` and `webhook` to
- * {@link AgentHookWebhook}. A persisted hook read back off topic metadata casts
- * up to this.
- */
-export interface SerializedHook extends Omit<SerializedAgentHook, 'type' | 'webhook'> {
- type: AgentHookType;
- webhook: AgentHookWebhook;
-}
+/** Webhook-only configuration persisted on the operation; validated again before dispatch. */
+export type SerializedHook = SerializedAgentHook;
diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
index 093689577e3..97eca1f4d0a 100644
--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts
@@ -766,7 +766,7 @@ describe('AiAgentService.execSubAgent', () => {
const completion = execAgentSpy.mock.calls[0][0].hooks?.find(
(h) => h.id === 'thread-completion',
);
- await completion!.handler({
+ await completion!.handler!({
finalState: {
cost: { total: 0.25 },
messages: [{ content: 'part 4', role: 'assistant' }],
diff --git a/apps/server/src/services/bot/createBotCompletionHook.ts b/apps/server/src/services/bot/createBotCompletionHook.ts
index 5d7b9904506..ede43c48427 100644
--- a/apps/server/src/services/bot/createBotCompletionHook.ts
+++ b/apps/server/src/services/bot/createBotCompletionHook.ts
@@ -1,6 +1,6 @@
import type { ChatTopicBotContext } from '@lobechat/types';
-import type { AgentHookWebhook } from '@/server/services/agentRuntime/hooks/types';
+import type { NotificationWebhook } from '@/server/services/agentRuntime/hooks/types';
const BOT_CALLBACK_URL = '/api/agent/webhooks/bot-callback';
@@ -16,7 +16,7 @@ export const createBotCompletionWebhook = ({
body,
userId,
workspaceId,
-}: CreateBotCompletionHookParams): AgentHookWebhook => ({
+}: CreateBotCompletionHookParams): NotificationWebhook => ({
body: {
applicationId: botContext.applicationId,
messengerInstallationKey: botContext.messengerInstallationKey,
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
index e3fbbf8447b..128850191ee 100644
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ b/packages/database/src/models/__tests__/topic.test.ts
@@ -1197,7 +1197,7 @@ describe('TopicModel', () => {
const hooks = [
{
id: 'hook-old',
- type: 'onComplete',
+ type: 'onComplete' as const,
webhook: { url: '/callback' },
},
];
@@ -1352,7 +1352,7 @@ describe('TopicModel', () => {
const childHooks = [
{
id: 'hook-child',
- type: 'onComplete',
+ type: 'onComplete' as const,
webhook: { url: '/child-callback' },
},
];
diff --git a/packages/types/src/agentHook.test.ts b/packages/types/src/agentHook.test.ts
new file mode 100644
index 00000000000..5e6525372f8
--- /dev/null
+++ b/packages/types/src/agentHook.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ agentHookTypeSchema,
+ agentHookWebhookSchema,
+ serializedAgentHookSchema,
+} from './agentHook';
+import { parseToolCallHookResponse, resolveToolCallHookErrorPolicy } from './agentHookResponse';
+
+const control = {
+ id: 'policy',
+ type: 'beforeToolCall',
+ webhook: { responseHandling: 'toolCall', url: 'https://example.com' },
+};
+const response = (output: Record<string, unknown>) =>
+ JSON.stringify({ hookSpecificOutput: { hookEventName: 'beforeToolCall', ...output } });
+
+describe('serialized hook contract', () => {
+ it('round trips all fields including legacy fallback without expanding secrets', () => {
+ const hook = {
+ ...control,
+ matcher: '^fs/read.*',
+ webhook: {
+ ...control.webhook,
+ allowedEnvVars: ['HOOK_KEY'],
+ headers: { Authorization: 'Bearer ${HOOK_KEY}' },
+ timeout: 2,
+ onError: 'block',
+ fallback: 'none',
+ delivery: 'fetch',
+ },
+ };
+ const persisted = JSON.stringify(hook);
+ expect(serializedAgentHookSchema.parse(JSON.parse(persisted))).toEqual(hook);
+ });
+ it('accepts every legacy hook and notification body/selection', () => {
+ for (const type of agentHookTypeSchema.options) {
+ expect(
+ serializedAgentHookSchema.safeParse({
+ id: type,
+ type,
+ webhook: {
+ url: '/api/hook',
+ body: { custom: true },
+ eventFields: ['operationId'],
+ fallback: 'none',
+ },
+ }).success,
+ ).toBe(true);
+ }
+ });
+ it.each([
+ { ...control, type: 'afterToolCall' },
+ { ...control, type: 'unknown' },
+ { ...control, matcher: '[' },
+ { ...control, matcher: { identifier: '^fs$', apiName: '^read' } },
+ ...[
+ { delivery: 'qstash' },
+ { eventFields: [] },
+ { body: {} },
+ { timeout: 0 },
+ { timeout: -1 },
+ { timeout: Infinity },
+ { timeout: 2_147_484 },
+ { url: 'file:///etc/passwd' },
+ { url: '//evil.example/path' },
+ { url: 'https://name:[email protected]' },
+ { surprise: true },
+ ].map((webhook) => ({ ...control, webhook: { ...control.webhook, ...webhook } })),
+ ])('rejects invalid persisted configuration %#', (hook) => {
+ expect(serializedAgentHookSchema.safeParse(hook).success).toBe(false);
+ });
+ it.each(['', '*', '^fs/readFile$'])(
+ 'round trips a string matcher %j on every tool event',
+ (matcher) => {
+ for (const type of ['beforeToolCall', 'afterToolCall', 'onToolCallError']) {
+ const hook = { id: 'tool', matcher, type, webhook: { url: '/hook' } };
+ expect(serializedAgentHookSchema.parse(hook)).toEqual(hook);
+ }
+ },
+ );
+ it.each(['', '*', '^fs/readFile$'])('rejects a matcher %j on every non-tool event', (matcher) => {
+ for (const type of agentHookTypeSchema.options.filter(
+ (name) => !['beforeToolCall', 'afterToolCall', 'onToolCallError'].includes(name),
+ )) {
+ expect(
+ serializedAgentHookSchema.safeParse({
+ id: 'notification',
+ matcher,
+ type,
+ webhook: { url: '/hook' },
+ }).success,
+ ).toBe(false);
+ }
+ });
+ it('disallows blocking notification errors', () => {
+ expect(agentHookWebhookSchema.safeParse({ url: '/hook', onError: 'block' }).success).toBe(
+ false,
+ );
+ });
+});
+
+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' },
+ };
+ expect(parseToolCallHookResponse(response(decision))).toEqual({
+ decision: { hookEventName: 'beforeToolCall', ...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 },
+ ].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({
+ status: 'success',
+ });
+ expect(parseToolCallHookResponse('{}' + ' '.repeat(65_535))).toEqual({
+ status: 'error',
+ code: 'response_too_large',
+ });
+ expect(
+ parseToolCallHookResponse(response({ permissionDecisionReason: 'η•Œ'.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' });
+ expect(resolveToolCallHookErrorPolicy('block')).toEqual({ action: 'block' });
+ });
+});
diff --git a/packages/types/src/agentHook.ts b/packages/types/src/agentHook.ts
index d8952857192..ddd5a53b102 100644
--- a/packages/types/src/agentHook.ts
+++ b/packages/types/src/agentHook.ts
@@ -1,32 +1,105 @@
import { z } from 'zod';
-/**
- * Serialized webhook config for an agent lifecycle hook β€” the wire shape
- * persisted on a running operation and delivered in queue mode.
- *
- * This is the transport view. The server's runtime `AgentHookWebhook` is a
- * richer superset (its `eventFields` is keyed to `AgentHookEvent`); reading a
- * persisted hook back casts up to it.
- */
-export const agentHookWebhookSchema = z.object({
- body: z.record(z.string(), z.unknown()).optional(),
- delivery: z.enum(['fetch', 'qstash']).optional(),
- eventFields: z.array(z.string()).optional(),
- url: z.string(),
-});
+export const agentHookTypeSchema = z.enum([
+ 'beforeStep',
+ 'afterStep',
+ 'onComplete',
+ 'onError',
+ 'beforeToolCall',
+ 'afterToolCall',
+ 'onToolCallError',
+ 'beforeHumanIntervention',
+ 'afterHumanIntervention',
+ 'onStopByHumanIntervention',
+ 'beforeCompact',
+ 'afterCompact',
+ 'onCompactError',
+ 'beforeCallAgent',
+ 'afterCallAgent',
+ 'onCallAgentError',
+]);
-/**
- * Serialized agent lifecycle hook (onComplete / onError / …). Only hooks
- * carrying a webhook are serializable β€” handler closures can't cross a process
- * boundary β€” so this is what gets persisted (e.g. on
- * `topic.metadata.runningOperation.hooks`) and replayed through the shared
- * hookDispatcher by every terminal site.
- */
-export const serializedAgentHookSchema = z.object({
- id: z.string(),
- type: z.string(),
- webhook: agentHookWebhookSchema,
-});
+/** Regex against `${identifier}/${apiName}`; omitted, empty or * matches every tool. */
+export const agentHookMatcherSchema = z.string().refine((pattern) => {
+ if (!pattern || pattern === '*') return true;
+ try {
+ new RegExp(pattern);
+ return true;
+ } catch {
+ return false;
+ }
+}, 'Invalid hook matcher regular expression');
+/** Persist templates only; environment values are resolved immediately before sending. */
+export const agentHookWebhookSchema = z
+ .strictObject({
+ allowedEnvVars: z.array(z.string().regex(/^[A-Z_]\w*$/i)).optional(),
+ body: z.record(z.string(), z.unknown()).optional(),
+ delivery: z.enum(['fetch', 'qstash']).optional(),
+ eventFields: z.array(z.string()).optional(),
+ fallback: z.enum(['fetch', 'none']).optional(),
+ headers: z.record(z.string(), z.string()).optional(),
+ onError: z.enum(['continue', 'block']).optional(),
+ responseHandling: z.enum(['ignore', 'toolCall']).optional(),
+ timeout: z.number().positive().max(2_147_483.647).optional(),
+ url: z
+ .string()
+ .min(1)
+ .refine((value) => {
+ if (value.includes('\\')) return false;
+ if (value.startsWith('/') && !value.startsWith('//')) return true;
+ try {
+ const url = new URL(value);
+ return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password;
+ } catch {
+ return false;
+ }
+ }, 'Webhook URL must be HTTP(S) or an application-relative path without credentials'),
+ })
+ .superRefine((webhook, ctx) => {
+ const control = webhook.responseHandling === 'toolCall';
+ if (control && webhook.delivery === 'qstash') {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'toolCall response handling requires fetch delivery',
+ });
+ }
+ if (!control && webhook.onError === 'block') {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'onError:block requires toolCall response handling',
+ });
+ }
+ if (control && (webhook.eventFields !== undefined || webhook.body !== undefined)) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Control hooks cannot filter or override the event payload',
+ });
+ }
+ });
+
+export const serializedAgentHookSchema = z
+ .strictObject({
+ id: z.string(),
+ matcher: agentHookMatcherSchema.optional(),
+ type: agentHookTypeSchema,
+ webhook: agentHookWebhookSchema,
+ })
+ .superRefine((hook, ctx) => {
+ if (
+ hook.matcher !== undefined &&
+ !['beforeToolCall', 'afterToolCall', 'onToolCallError'].includes(hook.type)
+ ) {
+ ctx.addIssue({ code: 'custom', message: 'Matchers are only supported for tool events' });
+ }
+ if (hook.webhook.responseHandling === 'toolCall' && hook.type !== 'beforeToolCall') {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'toolCall response handling requires beforeToolCall',
+ });
+ }
+ });
+
+export type AgentHookMatcher = z.infer<typeof agentHookMatcherSchema>;
export type AgentHookWebhookConfig = z.infer<typeof agentHookWebhookSchema>;
export type SerializedAgentHook = z.infer<typeof serializedAgentHookSchema>;
diff --git a/packages/types/src/agentHookResponse.ts b/packages/types/src/agentHookResponse.ts
new file mode 100644
index 00000000000..8abd2a53ca1
--- /dev/null
+++ b/packages/types/src/agentHookResponse.ts
@@ -0,0 +1,59 @@
+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(),
+});
+
+export type ToolCallHookDecision = z.infer<typeof toolCallHookDecisionSchema>;
+export type ToolCallHookParseResult =
+ | { 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. */
+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);
+ if (!parsed.success) return { code: 'invalid_response', status: 'error' };
+ return { decision: parsed.data.hookSpecificOutput, status: 'success' };
+}
+
+/** C1 must branch on cancelled before applying onError; cancellation never grants permission. */
+export type ToolCallHookExecutionResult =
+ | ToolCallHookParseResult
+ | { status: 'cancelled' }
+ | {
+ code: 'configuration' | 'http_error' | 'network_error' | 'timeout';
+ status: 'error';
+ };
+
+export type ToolCallHookErrorPolicyResult = { action: 'continue' | 'block' };
+
+export function resolveToolCallHookErrorPolicy(
+ onError: 'continue' | 'block' = 'continue',
+): ToolCallHookErrorPolicyResult {
+ return { action: onError };
+}
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 1a22522524d..2091d4ce5d3 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -2,6 +2,7 @@ export * from './agent';
export * from './agentExecution';
export * from './agentGroup';
export * from './agentHook';
+export * from './agentHookResponse';
export * from './agentOperation';
export * from './aiChat';
export * from './aiProvider';