🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent): configure webhook hooks with server environment variables (#20196)
Bryanf807f94c936f
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 163cb034e2b..e3aaa0fd96b 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -6023,6 +6023,43 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {});describe('call_tool hooks', () => {+ it.each(['allow', 'deny'] as const)(+ 'applies env-configured %s before executing the tool',+ async (permissionDecision) => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'http://webhook-service/ingress');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-env-secret');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'beforeToolCall, afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(+ async () =>+ new Response(+ JSON.stringify({+ hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision },+ }),+ ),+ );+ try {+ const dispatcher = new HookDispatcher();+ dispatcher.register('op-123', []);+ const serialized = JSON.stringify(dispatcher.getSerializedHooks('op-123'));+ const persisted = JSON.parse(serialized);+ await createRuntimeExecutors({ ...ctx, hookDispatcher: new HookDispatcher() })+ .call_tool!(createToolInstruction(), createToolState({ host: { hooks: persisted } }));+ expect(mockToolExecutionService.executeTool).toHaveBeenCalledTimes(+ permissionDecision === 'allow' ? 1 : 0,+ );+ expect(+ fetchSpy.mock.calls.map(([, init]) => JSON.parse(String(init?.body)).hookType),+ ).toEqual(['beforeToolCall', 'afterToolCall']);+ expect(JSON.parse(String(fetchSpy.mock.calls[1][1]?.body)).mocked).toBe(false);+ } finally {+ fetchSpy.mockRestore();+ vi.unstubAllEnvs();+ }+ },+ );+it('invokes each local before handler once across observation and mock dispatch', async () => {const dispatcher = new HookDispatcher();const handler = vi.fn();diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex 48c032dc93e..93676d03bfd 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -17,6 +17,7 @@ import type { LobeChatDatabase } from '@/database/type';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime/AgentRuntimeCoordinator';import { CompletionLifecycle } from './CompletionLifecycle';+import { getServerHooks } from './hooks/serverHooks';import type { SerializedHook } from './hooks/types';import { OperationTraceRecorder } from './OperationTraceRecorder';import { createDefaultSnapshotStore } from './snapshotStore';@@ -455,7 +456,11 @@ export class AbandonOperationService {// run the hooks belong to, the same rule `heteroFinish` applies.if (settled.ownershipUnproven) return;const serializedHooks = settled.hooks ?? readDurableHooks(op.metadata);- if (!serializedHooks?.length) return;+ if (+ !serializedHooks?.length &&+ !getServerHooks().some((hook) => hook.type === 'onComplete' || hook.type === 'onError')+ )+ return;try {await new CompletionLifecycle(this.db, op.userId, op.workspaceId ?? undefined, {diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex e3b97e3db19..0252875f77d 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -271,6 +271,7 @@ describe('AgentRuntimeService', () => {});afterEach(() => {+ vi.unstubAllEnvs();delete process.env.AGENT_RUNTIME_BASE_URL;hookDispatcher.unregister('test-operation-1');});@@ -498,6 +499,34 @@ describe('AgentRuntimeService', () => {initialMessages: [],};+ it.each([undefined, 'parent-operation'])(+ 'persists only caller hooks for a run with parent %s',+ async (parentOperationId) => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'http://webhook-service/ingress');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-env-secret');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'beforeToolCall, afterToolCall, beforeToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');+ const hooks = [+ {+ id: 'internal-callback',+ type: 'afterToolCall' as const,+ webhook: { url: 'http://webhook-service/internal' },+ },+ ];+ await service.createOperation({+ ...mockParams,+ autoStart: false,+ parentOperationId,+ hooks,+ });+ const state = await mockCoordinator.loadAgentState(mockParams.operationId);+ expect(state.host.hooks).toEqual(hooks);+ expect(JSON.stringify(state.host.hooks)).not.toContain('synthetic-env-secret');+ expect(hookDispatcher.hasHooks(mockParams.operationId)).toBe(true);+ },+ );+it.each([undefined, false, true])('persists the snapshot opt-in for resumed steps (%s)',async (includeFinalState) => {diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 6c47dd52361..1ef05b0fdd2 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -1385,10 +1385,9 @@ export class AgentRuntimeService {await this.coordinator.saveAgentState(operationId, initialState as any);// Register external hooks- if (hooks && hooks.length > 0) {- hookDispatcher.register(operationId, hooks);- hooksRegistered = true;-+ hookDispatcher.register(operationId, hooks ?? []);+ hooksRegistered = hookDispatcher.hasHooks(operationId);+ if (hooksRegistered) {// Persist webhook configs to state metadata for production modeconst serializedHooks = hookDispatcher.getSerializedHooks(operationId);if (serializedHooks && serializedHooks.length > 0) {diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex 432b52e2f93..c10e093f735 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { MessageModel } from '@/database/models/message';import { TopicModel } from '@/database/models/topic';@@ -206,6 +206,15 @@ describe('AbandonOperationService', () => {});describe('no-state lifecycle hooks', () => {+ const configureEnvironmentHooks = (events: string) => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'http://webhook-service/ingress');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-abandon-token');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', events);+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'ignore');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'continue');+ };+ afterEach(() => vi.unstubAllEnvs());+const taskHook = {id: 'task-on-complete',type: 'onComplete',@@ -291,6 +300,51 @@ describe('AbandonOperationService', () => {expect(completeOperationMock).not.toHaveBeenCalled();});++ it.each(['onComplete', 'onError', 'onComplete,onError'])(+ 'runs the lifecycle for current environment events %s without persisted hooks',+ async (events) => {+ configureEnvironmentHooks(events);+ await abandon(runningRow());++ expect(completeOperationMock).toHaveBeenCalledTimes(1);+ expect(completeOperationMock).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'op_x', serializedHooks: undefined }),+ 'error',+ { skipErrorMessageWrite: true },+ );+ },+ );++ it('does not start terminal dispatch for tool-only environment events', async () => {+ configureEnvironmentHooks('beforeToolCall,afterToolCall,onToolCallError');+ await abandon(runningRow());+ expect(completeOperationMock).not.toHaveBeenCalled();+ });++ it('does not start terminal dispatch after environment hooks are disabled', async () => {+ configureEnvironmentHooks('onComplete,onError');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', undefined);+ await abandon(runningRow());+ expect(completeOperationMock).not.toHaveBeenCalled();+ });++ it.each(['conflict', 'failed'])(+ 'does not dispatch environment hooks when topic settlement is %s',+ async (settlement) => {+ configureEnvironmentHooks('onComplete,onError');+ if (settlement === 'conflict') {+ topicSettleRunningOperationMock.mockResolvedValue({+ activeOperationId: 'op_newer',+ status: 'conflict',+ });+ } else {+ topicSettleRunningOperationMock.mockRejectedValue(new Error('db unavailable'));+ }+ await abandon(runningRow());+ expect(completeOperationMock).not.toHaveBeenCalled();+ },+ );});describe('no-state row pre-claimed by the caller', () => {diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.tsindex 51544953d73..b4899f18aad 100644--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts@@ -12,6 +12,7 @@ import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';import { deliverWebhook, executeToolCallWebhook } from './httpWebhook';import { matchesHook } from './matcher';+import { getServerHooks, mergeServerHooks } from './serverHooks';import type {AgentHook,AgentHookEvent,@@ -36,9 +37,9 @@ export class CriticalHookDeliveryError extends Error {export { deliverWebhook } from './httpWebhook';-/** Validate persisted configurations on every worker restore. */+/** Discard legacy environment hooks and validate caller configs on every worker restore. */export function parseSerializedHooks(hooks: SerializedAgentHook[]): SerializedHook[] {- return hooks.map((hook) => serializedAgentHookSchema.parse(hook));+ return mergeServerHooks(hooks, []).map((hook) => serializedAgentHookSchema.parse(hook));}/**@@ -57,6 +58,15 @@ export class HookDispatcher {*/private hooks: Map<string, AgentHook[]> = new Map();+ /** Shared by normal dispatch and tool control, including cold-worker recovery. */+ private resolveHooks(operationId: string, serializedHooks?: SerializedAgentHook[]) {+ const restored = serializedHooks ? parseSerializedHooks(serializedHooks) : undefined;+ const hooks: (AgentHook | SerializedHook)[] = isQueueAgentRuntimeEnabled()+ ? (restored ?? this.getSerializedHooks(operationId) ?? [])+ : (this.hooks.get(operationId) ?? restored ?? []);+ return mergeServerHooks(hooks, getServerHooks());+ }+/*** Dispatch hooks for a given event type*@@ -85,12 +95,7 @@ export class HookDispatcher {consumer?: 'handler' | 'webhook',): Promise<void> {const isQueueMode = isQueueAgentRuntimeEnabled();- const restored = serializedHooks ? parseSerializedHooks(serializedHooks) : undefined;-- const registered = this.hooks.get(operationId);- const hooks: (AgentHook | SerializedHook)[] = isQueueMode- ? (restored ?? this.getSerializedHooks(operationId) ?? [])- : (registered ?? restored ?? []);+ const hooks = this.resolveHooks(operationId, serializedHooks);let criticalError: CriticalHookDeliveryError | undefined;for (const hook of hooks.filter((h) =>@@ -147,10 +152,7 @@ export class HookDispatcher {serializedHooks?: SerializedAgentHook[],signal?: AbortSignal,): Promise<{ status: 'allow' | 'blocked' | 'cancelled'; reason?: string }> {- const restored = serializedHooks ? parseSerializedHooks(serializedHooks) : undefined;- const hooks = isQueueAgentRuntimeEnabled()- ? (restored ?? this.getSerializedHooks(operationId) ?? [])- : (this.hooks.get(operationId) ?? restored ?? []);+ const hooks = this.resolveHooks(operationId, serializedHooks);for (const hook of hooks) {if (signal?.aborted) return { status: 'cancelled' };if (@@ -269,7 +271,7 @@ export class HookDispatcher {* announced twice, and one they cannot announce must not vanish.*/canDeliver(operationId: string, type: AgentHookType): boolean {- const hooks = this.hooks.get(operationId)?.filter((hook) => hook.type === type) ?? [];+ const hooks = this.resolveHooks(operationId).filter((hook) => hook.type === type);return isQueueAgentRuntimeEnabled() ? hooks.some((hook) => hook.webhook) : hooks.length > 0;}@@ -281,6 +283,8 @@ export class HookDispatcher {* In production mode: caller should persist getSerializedHooks() to state.host.hooks*/register(operationId: string, hooks: AgentHook[]): void {+ const existing = this.hooks.get(operationId) || [];+ hooks = mergeServerHooks([...existing, ...hooks], getServerHooks());if (hooks.length === 0) return;// Validate the entire batch before mutating registration state.@@ -315,8 +319,7 @@ export class HookDispatcher {hook.matcher !== undefined ? agentHookMatcherSchema.parse(hook.matcher) : undefined,};});- const existing = this.hooks.get(operationId) || [];- this.hooks.set(operationId, [...existing, ...validatedHooks]);+ this.hooks.set(operationId, mergeServerHooks(validatedHooks, []));log('[%s] Registered %d hooks: %s',diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.tsnew file mode 100644index 00000000000..78159a775d2--- /dev/null+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.ts@@ -0,0 +1,333 @@+// @vitest-environment node+import { createServer } from 'node:http';+import type { AddressInfo } from 'node:net';++import { serializedAgentHookSchema } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { HookDispatcher } from '../HookDispatcher';+import { getServerHooks } from '../serverHooks';+import type { AgentHook, ToolCallHookEvent } from '../types';++const { queueMode } = vi.hoisted(() => ({ queueMode: vi.fn(() => false) }));+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: queueMode }));+vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));+vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds: async () => [] } }));+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));++const event: Omit<ToolCallHookEvent, 'mock'> = {+ apiName: 'read',+ assistantMessageId: 'synthetic-message',+ args: { path: 'synthetic.txt' },+ callIndex: 0,+ identifier: 'files',+ executor: 'server',+ operationId: 'synthetic-op',+ stepIndex: 0,+ toolCallId: 'synthetic-tool-call',+ userId: 'synthetic-user',+};++describe('environment hooks through real HTTP transport', () => {+ const requests: { authorization?: string; body: Record<string, unknown>; path?: string }[] = [];+ let response: unknown;+ const receiver = createServer(async (request, reply) => {+ const chunks: Buffer[] = [];+ for await (const chunk of request) chunks.push(Buffer.from(chunk));+ requests.push({+ authorization: request.headers.authorization,+ body: JSON.parse(Buffer.concat(chunks).toString()),+ path: request.url,+ });+ reply.setHeader('content-type', 'application/json');+ reply.end(JSON.stringify(response));+ });+ let url: string;++ beforeEach(async () => {+ requests.length = 0;+ response = {+ hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'allow' },+ };+ queueMode.mockReturnValue(false);+ await new Promise<void>((resolve) => receiver.listen(0, '127.0.0.1', resolve));+ url = `http://127.0.0.1:${(receiver.address() as AddressInfo).port}/ingress`;+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', url);+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-secret-one');+ vi.stubEnv(+ 'AGENT_HOOK_WEBHOOK_EVENTS',+ 'beforeToolCall, afterToolCall, onToolCallError,beforeToolCall',+ );+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');+ });+ afterEach(async () => {+ receiver.closeAllConnections();+ await new Promise<void>((resolve, reject) =>+ receiver.close((error) => (error ? reject(error) : resolve())),+ );+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+ });++ it.each([false, true])(+ 'uses current config without persisting environment hooks in queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ const dispatcher = new HookDispatcher();+ dispatcher.register(event.operationId, []);+ dispatcher.register(event.operationId, []);+ const saved = JSON.stringify(dispatcher.getSerializedHooks(event.operationId));+ expect(saved).not.toContain('synthetic-secret-one');+ expect(JSON.parse(saved)).toEqual([]);+ const hooks = getServerHooks().map((hook) => serializedAgentHookSchema.parse(hook));+ expect(hooks).toHaveLength(3);+ expect(hooks[0].webhook).toEqual({+ allowedEnvVars: ['AGENT_HOOK_WEBHOOK_TOKEN'],+ delivery: 'fetch',+ headers: { Authorization: 'Bearer ${AGENT_HOOK_WEBHOOK_TOKEN}' },+ onError: 'block',+ responseHandling: 'toolCall',+ url,+ });+ for (const hook of hooks.slice(1))+ expect(hook.webhook).toMatchObject({ onError: 'continue', responseHandling: 'ignore' });++ // A cold worker uses its current configuration, ignoring legacy snapshot copies.+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-secret-two');+ const cold = new HookDispatcher();+ const restored = [...hooks, ...hooks];+ await cold.dispatchBeforeToolCall(event.operationId, event, restored);+ expect(requests).toHaveLength(0);+ expect(await cold.evaluateToolCall(event.operationId, event, restored)).toMatchObject({+ status: 'allow',+ });+ response = {+ hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'deny' },+ };+ expect(await cold.evaluateToolCall(event.operationId, event, restored)).toMatchObject({+ status: 'blocked',+ });+ await cold.dispatch(+ event.operationId,+ 'afterToolCall',+ { ...event, executionTimeMs: 1, mocked: true, result: { content: 'safe', success: true } },+ restored,+ );+ await cold.dispatch(+ event.operationId,+ 'onToolCallError',+ { ...event, error: 'synthetic' },+ restored,+ );+ expect(requests).toHaveLength(4);+ expect(requests.map((request) => request.body.hookType)).toEqual([+ 'beforeToolCall',+ 'beforeToolCall',+ 'afterToolCall',+ 'onToolCallError',+ ]);+ expect(+ requests.every((request) => request.authorization === 'Bearer synthetic-secret-two'),+ ).toBe(true);+ expect(requests[2].body).toMatchObject({ mocked: true, result: { content: 'safe' } });+ expect(JSON.stringify(requests.map((request) => request.body))).not.toContain(+ 'synthetic-secret',+ );+ expect(queueMode()).toBe(queue);+ },+ );++ it('preserves caller handlers and internal callbacks and prevents same-ID replacement', async () => {+ const dispatcher = new HookDispatcher();+ const handler = vi.fn();+ const original: AgentHook[] = [+ { id: 'internal-callback', type: 'afterToolCall', webhook: { url: `${url}/internal` } },+ { id: 'caller-handler', type: 'afterToolCall', handler },+ ];+ dispatcher.register(event.operationId, original);+ const id = 'server-env-webhook:beforeToolCall';+ const replacement = vi.fn();+ dispatcher.register(event.operationId, [{ id, type: 'beforeToolCall', handler: replacement }]);+ await dispatcher.dispatchBeforeToolCall(event.operationId, event);+ expect(replacement).not.toHaveBeenCalled();+ await dispatcher.dispatch(event.operationId, 'afterToolCall', {+ ...event,+ executionTimeMs: 1,+ result: { content: 'ok', success: true },+ });+ expect(handler).toHaveBeenCalledTimes(1);+ expect(requests.map((request) => request.path)).toEqual(['/ingress/internal', '/ingress']);+ expect(dispatcher.getSerializedHooks(event.operationId)).toEqual([original[0]]);+ });++ describe.each([false, true])('configuration changes in queue=%s', (queue) => {+ it.each([false, true])(+ 'removes unselected events and switches the endpoint (cold=%s)',+ async (cold) => {+ queueMode.mockReturnValue(queue);+ const original: AgentHook = {+ id: 'internal-callback',+ type: 'afterToolCall',+ webhook: { url: `${url}/internal` },+ };+ const legacy = [original, ...getServerHooks()].map((hook) =>+ serializedAgentHookSchema.parse(hook),+ );+ const registered = new HookDispatcher();+ registered.register(event.operationId, [original]);+ const dispatcher = cold ? new HookDispatcher() : registered;++ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', `${url}/new`);+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'ignore');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'continue');+ response = {+ hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'deny' },+ };+ expect(await dispatcher.evaluateToolCall(event.operationId, event, legacy)).toEqual({+ status: 'allow',+ });+ expect(dispatcher.canDeliver(event.operationId, 'beforeToolCall')).toBe(false);+ await dispatcher.dispatch(+ event.operationId,+ 'onToolCallError',+ { ...event, error: 'test' },+ legacy,+ );+ expect(requests).toHaveLength(0);+ await dispatcher.dispatch(+ event.operationId,+ 'afterToolCall',+ { ...event, result: { content: 'ok', success: true }, mocked: false },+ legacy,+ );+ expect(requests.map((request) => request.path)).toEqual([+ '/ingress/internal',+ '/ingress/new',+ ]);+ },+ );++ it.each([false, true])(+ 'disables environment hooks when URL is removed (cold=%s)',+ async (cold) => {+ queueMode.mockReturnValue(queue);+ const original: AgentHook = {+ id: 'internal-callback',+ type: 'afterToolCall',+ webhook: { url: `${url}/internal` },+ };+ const legacy = [original, ...getServerHooks()].map((hook) =>+ serializedAgentHookSchema.parse(hook),+ );+ const registered = new HookDispatcher();+ registered.register(event.operationId, [original]);+ const dispatcher = cold ? new HookDispatcher() : registered;+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', undefined);+ response = {+ hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'deny' },+ };+ expect(await dispatcher.evaluateToolCall(event.operationId, event, legacy)).toEqual({+ status: 'allow',+ });+ expect(dispatcher.canDeliver(event.operationId, 'beforeToolCall')).toBe(false);+ await dispatcher.dispatch(+ event.operationId,+ 'afterToolCall',+ { ...event, result: { content: 'ok', success: true }, mocked: false },+ legacy,+ );+ expect(requests.map((request) => request.path)).toEqual(['/ingress/internal']);+ },+ );+ });++ it('rejects invalid deployment configuration instead of silently registering nothing', () => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'beforeToolCall,...');+ const dispatcher = new HookDispatcher();+ expect(() => dispatcher.register(event.operationId, [])).toThrow('AGENT_HOOK_WEBHOOK_EVENTS');+ expect(dispatcher.hasHooks(event.operationId)).toBe(false);+ });++ it('keeps local mock callbacks alongside environment controls', async () => {+ const dispatcher = new HookDispatcher();+ const handler = vi.fn(async (hookEvent) => {+ (hookEvent as ToolCallHookEvent).mock({ content: 'local mock', success: true });+ });+ dispatcher.register(event.operationId, [{ id: 'local-mock', type: 'beforeToolCall', handler }]);+ expect(await dispatcher.evaluateToolCall(event.operationId, event)).toMatchObject({+ status: 'allow',+ });+ expect(await dispatcher.dispatchBeforeToolCall(event.operationId, event)).toEqual({+ isMocked: true,+ result: { content: 'local mock', success: true },+ });+ expect(handler).toHaveBeenCalledTimes(1);+ expect(requests).toHaveLength(1);+ });++ it('defaults to notifications whose response cannot deny a tool', async () => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', undefined);+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', undefined);+ response = {+ hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'deny' },+ };+ const dispatcher = new HookDispatcher();+ dispatcher.register(event.operationId, []);+ expect(await dispatcher.evaluateToolCall(event.operationId, event)).toMatchObject({+ status: 'allow',+ });+ expect(requests).toHaveLength(0);+ expect(await dispatcher.dispatchBeforeToolCall(event.operationId, event)).toBeNull();+ await vi.waitFor(() => expect(requests).toHaveLength(1));+ });++ it('applies current server configuration to an older snapshot without losing its callback', async () => {+ const cold = new HookDispatcher();+ const restored = [+ {+ id: 'internal-callback',+ type: 'afterToolCall' as const,+ webhook: { url: `${url}/internal` },+ },+ ];+ response = {+ hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'deny' },+ };+ expect(await cold.evaluateToolCall(event.operationId, event, restored)).toMatchObject({+ status: 'blocked',+ });+ await cold.dispatch(+ event.operationId,+ 'afterToolCall',+ { ...event, executionTimeMs: 1, result: { content: 'ok', success: true } },+ restored,+ );+ expect(requests.map((request) => request.path)).toEqual([+ '/ingress',+ '/ingress/internal',+ '/ingress',+ ]);+ });++ it.each(['continue', 'block'] as const)(+ 'applies onError=%s to an invalid control response without leaking credentials',+ async (onError) => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', onError);+ response = { invalid: 'synthetic-secret-two' };+ const log = vi.spyOn(console, 'error');+ const dispatcher = new HookDispatcher();+ dispatcher.register(event.operationId, []);+ const result = await dispatcher.evaluateToolCall(event.operationId, event);+ expect(result.status).toBe(onError === 'block' ? 'blocked' : 'allow');+ expect(+ JSON.stringify({+ result,+ logs: log.mock.calls,+ state: dispatcher.getSerializedHooks(event.operationId),+ }),+ ).not.toContain('synthetic-secret');+ },+ );+});diff --git a/apps/server/src/services/agentRuntime/hooks/serverHooks.ts b/apps/server/src/services/agentRuntime/hooks/serverHooks.tsnew file mode 100644index 00000000000..71be4e43058--- /dev/null+++ b/apps/server/src/services/agentRuntime/hooks/serverHooks.ts@@ -0,0 +1,42 @@+import { getAgentHookConfig } from '@lobechat/env/agentHook';++import type { AgentHook, SerializedHook } from './types';++const SERVER_HOOK_PREFIX = 'server-env-webhook:';++/** Generate only template-bearing webhook configs; each event has a stable reserved ID. */+export function getServerHooks(): AgentHook[] {+ const env = getAgentHookConfig();+ if (!env.AGENT_HOOK_WEBHOOK_URL) return [];+ const webhook = {+ allowedEnvVars: ['AGENT_HOOK_WEBHOOK_TOKEN'],+ delivery: 'fetch' as const,+ headers: { Authorization: 'Bearer ${AGENT_HOOK_WEBHOOK_TOKEN}' },+ url: env.AGENT_HOOK_WEBHOOK_URL,+ };+ return env.AGENT_HOOK_WEBHOOK_EVENTS!.map((type): AgentHook => {+ const id = `${SERVER_HOOK_PREFIX}${type}`;+ if (type === 'beforeToolCall' && env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolCall') {+ return {+ id,+ type,+ webhook: {+ ...webhook,+ onError: env.AGENT_HOOK_WEBHOOK_ON_ERROR,+ responseHandling: 'toolCall',+ },+ };+ }+ return { id, type, webhook: { ...webhook, onError: 'continue', responseHandling: 'ignore' } };+ });+}++/** Replace all environment hooks with current configuration, preserving unrelated callbacks. */+export function mergeServerHooks<T extends AgentHook | SerializedHook>(+ hooks: T[],+ configured: T[],+): T[] {+ const reserved = new Map(configured.map((hook) => [hook.id, hook]));+ const retained = hooks.filter((hook) => !hook.id.startsWith(SERVER_HOOK_PREFIX));+ return [...retained, ...reserved.values()];+}diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.tsindex d40a0401dfa..b68a784f5c2 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts@@ -344,7 +344,7 @@ export const dispatchHeteroAgent = async (// Hooks belong to this operation's lifecycle. Persist their serializable// form on the durable operation row before dispatch; runningOperation below// remains a compatibility mirror for older terminal consumers.- if (hooks?.length) hookDispatcher.register(operationId, hooks);+ hookDispatcher.register(operationId, hooks ?? []);const serializedHooks = hookDispatcher.getSerializedHooks(operationId);// Persist a first-class agent_operations row for the hetero run. The id isdiff --git a/packages/env/src/__tests__/agentHook.test.ts b/packages/env/src/__tests__/agentHook.test.tsnew file mode 100644index 00000000000..458364018f8--- /dev/null+++ b/packages/env/src/__tests__/agentHook.test.ts@@ -0,0 +1,65 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getAgentHookConfig } from '../agentHook';++beforeEach(() => {+ for (const name of ['URL', 'TOKEN', 'EVENTS', 'RESPONSE_HANDLING', 'ON_ERROR'])+ vi.stubEnv(`AGENT_HOOK_WEBHOOK_${name}`, undefined);+});+afterEach(() => vi.unstubAllEnvs());++const enable = () => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'http://webhook-service/ingress');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-env-secret');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'beforeToolCall, afterToolCall, onToolCallError');+};++describe('server hook environment', () => {+ it('is disabled by default', () => {+ expect(getAgentHookConfig().AGENT_HOOK_WEBHOOK_URL).toBeUndefined();+ });++ it('normalizes and validates existing event names with notification defaults', () => {+ enable();+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', ' beforeToolCall, ,afterToolCall,beforeToolCall, ');+ expect(getAgentHookConfig()).toMatchObject({+ AGENT_HOOK_WEBHOOK_EVENTS: ['beforeToolCall', 'afterToolCall'],+ AGENT_HOOK_WEBHOOK_ON_ERROR: 'continue',+ AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING: 'ignore',+ AGENT_HOOK_WEBHOOK_URL: 'http://webhook-service/ingress',+ });+ });++ it.each([+ ['TOKEN', undefined],+ ['TOKEN', ' '],+ ['EVENTS', undefined],+ ['EVENTS', ' , , '],+ ['EVENTS', 'beforeToolCall,...'],+ ['EVENTS', 'onUserPrompt'],+ ['URL', 'ftp://webhook-service/ingress'],+ ['URL', ''],+ ['RESPONSE_HANDLING', 'invalid'],+ ['ON_ERROR', 'invalid'],+ ['ON_ERROR', 'block'],+ ])('rejects invalid %s without exposing the token', (name, value) => {+ enable();+ vi.stubEnv(`AGENT_HOOK_WEBHOOK_${name}`, value);+ let error: unknown;+ try {+ getAgentHookConfig();+ } catch (caught) {+ error = caught;+ }+ expect(error).toBeInstanceOf(Error);+ expect(String(error)).toContain('AGENT_HOOK_WEBHOOK');+ expect(String(error)).not.toContain('synthetic-env-secret');+ });++ it('requires beforeToolCall for control', () => {+ enable();+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');+ expect(() => getAgentHookConfig()).toThrow('beforeToolCall');+ });+});diff --git a/packages/env/src/agentHook.ts b/packages/env/src/agentHook.tsnew file mode 100644index 00000000000..c9597b1bb4d--- /dev/null+++ b/packages/env/src/agentHook.ts@@ -0,0 +1,67 @@+import { agentHookTypeSchema, agentHookWebhookSchema } from '@lobechat/types';+import { createEnv } from '@t3-oss/env-core';+import { z } from 'zod';++/** Server-only deployment hooks. Secrets are validated here, never copied into hook state. */+export const getAgentHookConfig = () => {+ const env = createEnv({+ onValidationError: (issues) => {+ // Do not log Zod inputs or environment values (especially the token).+ throw new Error(+ `Invalid Agent Hook environment: ${issues.map((issue) => issue.path?.join('.')).join(', ')}`,+ );+ },+ runtimeEnv: {+ AGENT_HOOK_WEBHOOK_EVENTS: process.env.AGENT_HOOK_WEBHOOK_EVENTS,+ AGENT_HOOK_WEBHOOK_ON_ERROR: process.env.AGENT_HOOK_WEBHOOK_ON_ERROR,+ AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING: process.env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING,+ AGENT_HOOK_WEBHOOK_TOKEN: process.env.AGENT_HOOK_WEBHOOK_TOKEN,+ AGENT_HOOK_WEBHOOK_URL: process.env.AGENT_HOOK_WEBHOOK_URL,+ },+ server: {+ AGENT_HOOK_WEBHOOK_EVENTS: z.preprocess(+ (value) =>+ typeof value === 'string'+ ? [+ ...new Set(+ value+ .split(',')+ .map((event) => event.trim())+ .filter(Boolean),+ ),+ ]+ : value,+ z.array(agentHookTypeSchema).min(1).optional(),+ ),+ AGENT_HOOK_WEBHOOK_ON_ERROR: z.enum(['continue', 'block']).default('continue'),+ AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING: z.enum(['ignore', 'toolCall']).default('ignore'),+ AGENT_HOOK_WEBHOOK_TOKEN: z+ .string()+ .refine((token) => token.trim().length > 0)+ .optional(),+ AGENT_HOOK_WEBHOOK_URL: agentHookWebhookSchema.shape.url.optional(),+ },+ });++ if (env.AGENT_HOOK_WEBHOOK_URL !== undefined) {+ if (!env.AGENT_HOOK_WEBHOOK_TOKEN)+ throw new Error('AGENT_HOOK_WEBHOOK_URL requires non-empty AGENT_HOOK_WEBHOOK_TOKEN');+ if (!env.AGENT_HOOK_WEBHOOK_EVENTS?.length)+ throw new Error('AGENT_HOOK_WEBHOOK_URL requires non-empty AGENT_HOOK_WEBHOOK_EVENTS');+ }+ if (+ env.AGENT_HOOK_WEBHOOK_ON_ERROR === 'block' &&+ env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING !== 'toolCall'+ )+ throw new Error(+ 'AGENT_HOOK_WEBHOOK_ON_ERROR=block requires AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING=toolCall',+ );+ if (+ env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolCall' &&+ !env.AGENT_HOOK_WEBHOOK_EVENTS?.includes('beforeToolCall')+ )+ throw new Error(+ 'AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING=toolCall requires beforeToolCall in AGENT_HOOK_WEBHOOK_EVENTS',+ );+ return env;+};