🤯 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): support beforeToolCall allow/deny at execution (#20132)
Bryan6dc20f6a0526
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 3d27e664525..163cb034e2b 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as ContextEngineering from '@/server/modules/Mecha/ContextEngineering';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { HookDispatcher } from '@/server/services/agentRuntime/hooks';import * as ClientToolDispatch from '../dispatchClientTool';import { createRuntimeExecutors, type RuntimeExecutorContext } from '../RuntimeExecutors';@@ -6022,11 +6023,25 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {});describe('call_tool hooks', () => {+ it('invokes each local before handler once across observation and mock dispatch', async () => {+ const dispatcher = new HookDispatcher();+ const handler = vi.fn();+ dispatcher.register('op-123', [{ id: 'observe-once', type: 'beforeToolCall', handler }]);+ await createRuntimeExecutors({ ...ctx, hookDispatcher: dispatcher }).call_tool!(+ createToolInstruction(),+ createToolState(),+ );+ expect(handler).toHaveBeenCalledTimes(1);+ expect(mockToolExecutionService.executeTool).toHaveBeenCalledTimes(1);+ });it.each([false, true])('keeps runtime owner identity in shared-session tool hooks (throws: %s)',async (throws) => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};if (throws)@@ -6052,10 +6067,14 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {);expect(ctx.userId).toBe('user-123');const identity = expect.objectContaining({ userId: 'user-123' });- expect(mockDispatcher.dispatchBeforeToolCall).toHaveBeenCalledWith('op-123', identity);- expect(mockDispatcher.dispatch).toHaveBeenCalledWith(+ expect(mockDispatcher.evaluateToolCall).toHaveBeenCalledWith(+ 'op-123',+ identity,+ undefined,+ undefined,+ );+ expect(mockDispatcher.dispatchBeforeToolCall).toHaveBeenCalledWith('op-123',- 'beforeToolCall',identity,undefined,);@@ -6071,6 +6090,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should preserve native identity and structured results across tool notifications', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};const toolResult = {@@ -6131,11 +6153,6 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {expect(mockDispatcher.dispatchBeforeToolCall).toHaveBeenCalledWith('op-123',expect.objectContaining(identity),- );- expect(mockDispatcher.dispatch).toHaveBeenCalledWith(- 'op-123',- 'beforeToolCall',- expect.objectContaining(identity),undefined,);expect(mockDispatcher.dispatch).toHaveBeenCalledWith(@@ -6159,6 +6176,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should report structured blocked results as unsuccessful notifications, not exceptions', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};const toolResult = {@@ -6195,6 +6215,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should correlate repeated tool names in a batch by native call ids', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};const tool = createToolInstruction().payload.toolCalling;@@ -6233,6 +6256,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should retain client routing and structured client results in notifications', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};const result = {@@ -6275,6 +6301,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should dispatch beforeToolCall and afterToolCall hooks', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};@@ -6290,6 +6319,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {callIndex: 1,identifier: 'twitter',}),+ undefined,);// afterToolCall dispatched via dispatch()@@ -6314,6 +6344,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {const controller = new AbortController();const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockImplementation(async () => {controller.abort();return null;@@ -6343,6 +6376,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {// webhook consumer would see `afterToolCall` after `onComplete`.const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};@@ -6374,6 +6410,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should skip real execution when beforeToolCall returns mock', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue({isMocked: true,result: { content: '{"mocked":true}', success: true },@@ -6411,6 +6450,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should preserve failed mock results without executing the real tool', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue({isMocked: true,result: { content: 'fixture error', error: 'fixture error', success: false },@@ -6448,6 +6490,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};@@ -6474,6 +6519,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should derive callIndex from state.usage.tools.byTool', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};@@ -6487,6 +6535,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {expect(mockDispatcher.dispatchBeforeToolCall).toHaveBeenCalledWith('op-123',expect.objectContaining({ callIndex: 1 }),+ undefined,);// Second call: state reflects 1 prior call → callIndex = 2@@ -6505,6 +6554,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {expect(mockDispatcher.dispatchBeforeToolCall).toHaveBeenLastCalledWith('op-123',expect.objectContaining({ callIndex: 2 }),+ undefined,);});@@ -6521,6 +6571,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should dispatch beforeCompact and afterCompact hooks', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};@@ -6559,6 +6612,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should dispatch beforeHumanIntervention hook', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ evaluateToolCall: vi.fn().mockResolvedValue({+ status: 'allow',+ }),dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),};diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.tsindex 775d4fa80eb..fc80fb01b7f 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts@@ -113,6 +113,32 @@ export class ServerToolTransport implements ToolTransport {);}+ async beforeToolCall(+ call: ChatToolPayload,+ context: ToolRunContext,+ ): Promise<ToolRunExecution | undefined> {+ const decision = await this.ctx.hookDispatcher?.evaluateToolCall(+ this.ctx.operationId,+ buildToolCallHookContext(call, context, this.ctx),+ context.state.host?.hooks,+ context.abortSignal,+ );+ if (context.abortSignal?.aborted || decision?.status === 'cancelled')+ return this.abortedBeforeLaunch();+ if (decision?.status === 'blocked') {+ const reason = decision.reason ?? 'Blocked by beforeToolCall hook.';+ const result = {+ content: reason,+ error: 'hook_denied',+ executionTime: 0,+ state: { reason, type: 'blocked' },+ success: false,+ };+ await this.dispatchAfterToolCall(call, context, result, false);+ return { attempts: 0, mocked: false, result };+ }+ }+async run(chatToolPayload: ChatToolPayload, context: ToolRunContext): Promise<ToolRunExecution> {const { operationId, serverDB, stepIndex, streamManager, toolExecutionService, userId } =this.ctx;@@ -134,6 +160,7 @@ export class ServerToolTransport implements ToolTransport {try {const hookResult = await this.dispatchBeforeToolCall(chatToolPayload, context);+ if (context.abortSignal?.aborted) return this.abortedBeforeLaunch();let toolCallMocked = false;if (isDeviceToolIdentifier(chatToolPayload.identifier) && !hookResult?.isMocked) {@@ -368,11 +395,7 @@ export class ServerToolTransport implements ToolTransport {if (!hookDispatcher) return null;const event = buildToolCallHookContext(chatToolPayload, context, this.ctx);- hookDispatcher- .dispatch(operationId, 'beforeToolCall', event, context.state.host?.hooks)- .catch(() => {});-- return hookDispatcher.dispatchBeforeToolCall(operationId, event);+ return hookDispatcher.dispatchBeforeToolCall(operationId, event, context.state.host?.hooks);}private async dispatchAfterToolCall(diff --git a/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.tsnew file mode 100644index 00000000000..436499e2e2f--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts@@ -0,0 +1,906 @@+import type { AgentRuntimeHost, AgentState, ToolCallHookEvent } from '@lobechat/agent-runtime';+import {+ AgentRuntime,+ createAgentRuntimeExecutors,+ GeneralChatAgent,+} from '@lobechat/agent-runtime';+import type { ChatToolPayload } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { AgentHook } from '@/server/services/agentRuntime/hooks';+import { HookDispatcher } from '@/server/services/agentRuntime/hooks';++import type { RuntimeExecutorContext } from '../context';+import { ServerToolTransport } from './ServerToolTransport';++const { dispatchClient, fetchHook, getEmailsByIds, queueMode } = vi.hoisted(() => ({+ dispatchClient: vi.fn(),+ fetchHook: vi.fn(),+ getEmailsByIds: vi.fn(),+ queueMode: vi.fn(),+}));+vi.mock('../dispatchClientTool', () => ({ dispatchClientTool: dispatchClient }));+vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds } }));+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: queueMode }));+vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));+vi.mock('@/database/models/agent', () => ({+ AgentModel: class {+ getAgentVisibility = async () => 'private';+ },+}));+vi.mock('../executorHelpers', () => ({+ archiveRuntimeToolResult: async (result: unknown) => result,+ buildServerAgentMemberRunner: () => undefined,+ buildServerVirtualSubAgentRunner: () => undefined,+ GEN_AI_FUNCTION_TOOL_TYPE: 'function',+ isOperationInterrupted: async () => false,+ log: () => {},+ registerWorkFromIntent: vi.fn(),+ TOOL_MAX_RETRIES: 2,+ TOOL_PRICING: { 'fs/write': 5 },+}));++const call = (id = 'native-1'): ChatToolPayload => ({+ id,+ apiName: 'write',+ identifier: 'fs',+ arguments: '{"path":"a"}',+ type: 'builtin',+});+const control = (id = 'control', onError: 'continue' | 'block' = 'continue'): AgentHook => ({+ id,+ type: 'beforeToolCall',+ webhook: { url: `https://hooks.example/${id}`, responseHandling: 'toolCall', onError },+});+const response = (permissionDecision: 'allow' | 'deny', permissionDecisionReason?: string) =>+ new Response(+ JSON.stringify({+ hookSpecificOutput: {+ hookEventName: 'beforeToolCall',+ permissionDecision,+ permissionDecisionReason,+ },+ }),+ );++function setup(hooks: AgentHook[], signal?: AbortSignal, restore = false) {+ const registered = new HookDispatcher();+ registered.register('op', hooks);+ const dispatcher = restore ? new HookDispatcher() : registered;+ const execute = vi.fn().mockResolvedValue({ content: 'executed', success: true });+ const rows: Record<string, unknown>[] = [];+ const state: AgentState = {+ cost: {+ calculatedAt: '',+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ },+ createdAt: '',+ lastModified: '',+ messages: [],+ operationId: 'op',+ status: 'running',+ stepCount: 0,+ origin: { agentId: 'agent', topicId: 'topic' },+ // Serialize to model a worker boundary, not merely an in-memory clone.+ // eslint-disable-next-line unicorn/prefer-structured-clone+ host: { hooks: JSON.parse(JSON.stringify(registered.getSerializedHooks('op') ?? [])) },+ userInterventionConfig: { approvalMode: 'auto-run' },+ };+ const transport = new ServerToolTransport({+ operationId: 'op',+ stepIndex: 1,+ userId: 'user',+ hookDispatcher: dispatcher,+ abortSignal: signal,+ serverDB: {},+ streamManager: { sendToolExecute: vi.fn() },+ toolExecutionService: { executeTool: execute },+ } as unknown as RuntimeExecutorContext);+ const host: AgentRuntimeHost = {+ operation: { operationId: 'op', stepIndex: 1, agentId: 'agent', abortSignal: signal },+ transports: {+ tools: transport,+ messages: {+ createToolMessage: vi.fn(async (row) => {+ rows.push(row);+ return { ...row, id: `row-${rows.length}` };+ }),+ query: vi.fn(async () => rows),+ updateToolMessage: vi.fn(),+ updateToolIntervention: vi.fn(),+ update: vi.fn(),+ findToolMessageIdByToolCallId: vi.fn(),+ } as unknown as AgentRuntimeHost['transports']['messages'],+ stream: { publishEvent: vi.fn(), publishChunk: vi.fn() },+ },+ };+ const executors = createAgentRuntimeExecutors(host);+ const runtime = new AgentRuntime(new GeneralChatAgent({ operationId: 'op' }), {+ executors,+ });+ const step = (calls = [call()]) =>+ runtime.step(state, {+ phase: 'llm_result',+ payload: { hasToolsCalling: true, parentMessageId: 'assistant', toolsCalling: calls },+ });+ return { dispatcher, execute, executors, host, rows, runtime, state, step };+}++beforeEach(() => {+ vi.stubGlobal('fetch', fetchHook);+ getEmailsByIds.mockReset().mockResolvedValue([]);+ fetchHook.mockReset().mockImplementation(async () => response('allow'));+ queueMode.mockReturnValue(false);+ dispatchClient.mockReset().mockResolvedValue({ content: 'client result', success: true });+});+afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('beforeToolCall control pipeline', () => {+ it.each([false, true])(+ 'uses the runtime account for tool hooks and execution after state restoration, queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ getEmailsByIds.mockResolvedValue([{ id: 'user', email: '[email protected]' }]);+ const fixture = setup(+ [+ control(),+ {+ id: 'after',+ type: 'afterToolCall',+ webhook: { url: 'https://hooks.example/after' },+ },+ ],+ undefined,+ queue,+ );+ fixture.state.origin!.userId = 'origin-owner';+ fixture.state.principal = {+ actor: {+ shareVisitor: {+ agentId: 'agent',+ shareId: 'share-1',+ visitorUserId: 'visitor-1',+ },+ },+ };+ // Restore the trusted state through its persistence wire format.+ // eslint-disable-next-line unicorn/prefer-structured-clone+ Object.assign(fixture.state, JSON.parse(JSON.stringify(fixture.state)));++ await fixture.step([{ ...call(), arguments: '{"path":"a","userId":"untrusted-input"}' }]);++ expect(fetchHook).toHaveBeenCalledTimes(2);+ for (const [, request] of fetchHook.mock.calls) {+ expect(JSON.parse(request.body)).toMatchObject({+ userId: 'user',+ userEmail: '[email protected]',+ args: { userId: 'untrusted-input' },+ });+ }+ expect(fixture.execute).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ userId: 'user' }),+ );+ expect(fixture.state.origin?.userId).toBe('origin-owner');+ expect(getEmailsByIds).toHaveBeenCalledExactlyOnceWith({}, ['user']);+ },+ );++ it.each([false, true])(+ 'denies before mock/execution and persists attempts=0, queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ fetchHook.mockImplementation(async () => response('deny'));+ const mock = vi.fn(async (event) => {+ (event as ToolCallHookEvent).mock({ content: 'mock', success: true });+ });+ const after = vi.fn();+ const fixture = setup(+ [+ control(),+ { id: 'mock', type: 'beforeToolCall', handler: mock },+ { id: 'after', type: 'afterToolCall', handler: after },+ ],+ undefined,+ queue,+ );+ const result = await fixture.step();+ expect(result.newState.status).toBe('running');+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(mock).not.toHaveBeenCalled();+ expect(fixture.rows).toEqual([+ expect.objectContaining({+ pluginState: { reason: 'Blocked by beforeToolCall hook.', type: 'blocked' },+ tool_call_id: 'native-1',+ }),+ ]);+ expect(fixture.host.transports.stream.publishEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'tool_end',+ data: expect.objectContaining({+ attempts: 0,+ result: expect.objectContaining({ success: false }),+ }),+ }),+ );+ expect(result.newState.cost?.total ?? 0).toBe(0);+ expect(fetchHook).toHaveBeenCalledTimes(1);+ if (!queue)+ expect(after).toHaveBeenCalledWith(+ expect.objectContaining({+ mocked: false,+ result: expect.objectContaining({+ success: false,+ state: { reason: 'Blocked by beforeToolCall hook.', type: 'blocked' },+ }),+ }),+ );+ },+ );++ it.each([+ { mode: 'single', failure: 'deny', reason: 'Workspace policy forbids this write.' },+ { mode: 'batch', failure: 'deny', reason: 'Workspace policy forbids this write.' },+ { mode: 'single', failure: 'error', reason: 'hook_control_error' },+ { mode: 'batch', failure: 'error', reason: 'hook_control_error' },+ ])(+ 'preserves the $failure rejection reason in a new $mode tool card',+ async ({ mode, failure, reason }) => {+ fetchHook.mockImplementation(async () =>+ failure === 'deny' ? response('deny', reason) : new Response('invalid JSON'),+ );+ const fixture = setup([control('control', 'block')]);+ const result =+ mode === 'single'+ ? await fixture.executors.call_tool!(+ { type: 'call_tool', payload: { parentMessageId: 'assistant', toolCalling: call() } },+ fixture.state,+ )+ : await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: { parentMessageId: 'assistant', toolsCalling: [call()] },+ },+ fixture.state,+ );+ expect(fixture.rows).toEqual([+ expect.objectContaining({+ content: reason,+ pluginError: 'hook_denied',+ pluginState: { type: 'blocked', reason },+ pluginIntervention: { status: 'rejected', rejectedReason: reason },+ }),+ ]);+ expect(result.events).toContainEqual(+ expect.objectContaining({+ type: 'tool_result',+ result: expect.objectContaining({ error: 'hook_denied', success: false }),+ }),+ );+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(result.newState.cost?.total).toBe(0);+ },+ );++ it.each(['single', 'batch'] as const)(+ 'preserves the rejection reason when reusing an approved %s row',+ async (mode) => {+ const reason = 'Approval does not override this policy.';+ fetchHook.mockImplementation(async () => response('deny', reason));+ const fixture = setup([control()]);+ await fixture.runtime.step(fixture.state, {+ phase: 'human_approved_tool',+ payload:+ mode === 'single'+ ? {+ approvedToolCall: call(),+ parentMessageId: 'pending-row',+ skipCreateToolMessage: true,+ }+ : {+ approvedToolCalls: [call()],+ parentMessageId: 'assistant',+ toolMessageIds: { 'native-1': 'pending-row' },+ },+ });+ expect(fixture.host.transports.messages.updateToolMessage).toHaveBeenCalledWith(+ 'pending-row',+ expect.objectContaining({+ content: reason,+ pluginError: 'hook_denied',+ pluginState: { type: 'blocked', reason },+ }),+ );+ expect(fixture.host.transports.messages.updateToolIntervention).toHaveBeenCalledWith(+ 'pending-row',+ { status: 'rejected', rejectedReason: reason },+ );+ expect(fixture.rows).toHaveLength(0);+ expect(fixture.execute).not.toHaveBeenCalled();+ },+ );++ it('cancels during email lookup before HTTP or tool execution', async () => {+ let resolveEmail!: (rows: { id: string; email: string }[]) => void;+ getEmailsByIds.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveEmail = resolve;+ }),+ );+ const abort = new AbortController();+ const fixture = setup([control()], abort.signal);+ const pending = fixture.step();+ await vi.waitFor(() => expect(getEmailsByIds).toHaveBeenCalledTimes(1));+ abort.abort();+ const result = await pending;+ resolveEmail([{ id: 'user', email: '[email protected]' }]);+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(fetchHook).not.toHaveBeenCalled();+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(fixture.rows).toEqual([+ expect.objectContaining({+ tool_call_id: 'native-1',+ pluginIntervention: { status: 'aborted' },+ }),+ ]);+ expect(result.events.some((event) => event.type === 'human_approve_required')).toBe(false);+ });++ it('does not consult control before product approval', async () => {+ const fixture = setup([control()]);+ fixture.state.userInterventionConfig = { approvalMode: 'manual' };+ const result = await fixture.step();+ expect(result.newState.status).toBe('waiting_for_human');+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(fetchHook).not.toHaveBeenCalled();+ });++ it('allow does not bypass the product tool allow-list', async () => {+ const fixture = setup([control()]);+ const runtime = new AgentRuntime(+ new GeneralChatAgent({ operationId: 'op', allowedToolNames: ['other/tool'] }),+ {+ executors: fixture.executors,+ },+ );+ const result = await runtime.step(fixture.state, {+ phase: 'llm_result',+ payload: { hasToolsCalling: true, toolsCalling: [call()], parentMessageId: 'assistant' },+ });+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(fetchHook).not.toHaveBeenCalled();+ expect(result.events).toContainEqual(+ expect.objectContaining({+ type: 'tool_result',+ result: expect.objectContaining({ state: { reason: 'tool_not_allowed', type: 'blocked' } }),+ }),+ );+ });++ it('applies ordered controls and stops at deny, before observers', async () => {+ fetchHook.mockResolvedValueOnce(response('allow')).mockResolvedValueOnce(response('deny'));+ const observer = vi.fn();+ const fixture = setup([+ { id: 'observer', type: 'beforeToolCall', handler: observer },+ control('one'),+ control('two'),+ control('three'),+ ]);+ await fixture.step();+ expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([+ 'https://hooks.example/one',+ 'https://hooks.example/two',+ ]);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).not.toHaveProperty('originalArgs');+ expect(observer).not.toHaveBeenCalled();+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({+ toolCallId: 'native-1',+ args: { path: 'a' },+ });+ });++ it('checks each ordered lane member at execution entry and only blocks its denied member', async () => {+ const order: string[] = [];+ fetchHook.mockImplementation(async (_url, init) => {+ const id = JSON.parse(init.body).toolCallId;+ order.push(id);+ return response(id === 'native-2' ? 'deny' : 'allow');+ });+ const fixture = setup([control()]);+ fixture.state.toolManifestMap = { fs: { api: [{ name: 'write', ordered: true }] } };+ fixture.execute.mockImplementation(async () => {+ order.push('execute');+ return { content: 'ok', success: true };+ });+ const result = await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: {+ parentMessageId: 'assistant',+ toolsCalling: [call(), call('native-2'), call('native-3')],+ },+ },+ fixture.state,+ );+ expect(order).toEqual(['native-1', 'execute', 'native-2', 'native-3', 'execute']);+ expect(fixture.execute).toHaveBeenCalledTimes(2);+ expect(result.events.filter((event) => event.type === 'tool_result')).toHaveLength(3);+ expect(result.newState.cost?.total).toBe(10);+ });++ it.each([false, true])(+ 'delivers observe/mock once and webhook-only in queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ const handler = vi.fn();+ const fixture = setup([+ control(),+ {+ id: 'dual',+ type: 'beforeToolCall',+ handler,+ webhook: { url: 'https://hooks.example/dual' },+ },+ { id: 'http', type: 'beforeToolCall', webhook: { url: 'https://hooks.example/http' } },+ ]);+ await fixture.step();+ expect(handler).toHaveBeenCalledTimes(queue ? 0 : 1);+ expect(fetchHook.mock.calls.map(([url]) => url)).toEqual(+ queue+ ? [+ 'https://hooks.example/control',+ 'https://hooks.example/dual',+ 'https://hooks.example/http',+ ]+ : ['https://hooks.example/control', 'https://hooks.example/http'],+ );+ expect(fixture.execute).toHaveBeenCalledTimes(1);+ },+ );++ it('runs an in-memory mock once after control and skips real effects', async () => {+ const handler = vi.fn(async (event) => {+ (event as ToolCallHookEvent).mock({ content: 'mock', success: true });+ });+ const fixture = setup([control(), { id: 'mock', type: 'beforeToolCall', handler }]);+ const result = await fixture.step();+ expect(handler).toHaveBeenCalledTimes(1);+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(result.events).toContainEqual(+ expect.objectContaining({+ type: 'tool_result',+ result: expect.objectContaining({ content: 'mock' }),+ }),+ );+ });++ it('checks control once outside internal tool retries', async () => {+ const handler = vi.fn();+ const fixture = setup([control(), { id: 'observe', type: 'beforeToolCall', handler }]);+ fixture.execute.mockResolvedValueOnce({+ content: '',+ success: false,+ error: { kind: 'retry' },+ });+ await fixture.step();+ expect(fixture.execute).toHaveBeenCalledTimes(2);+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('aborts waiting for an uncooperative webhook and a late allow cannot launch', async () => {+ let release!: (value: Response) => void;+ fetchHook.mockImplementation(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ );+ const abort = new AbortController();+ const fixture = setup([control()], abort.signal);+ const pending = fixture.step();+ await vi.waitFor(() => expect(fetchHook).toHaveBeenCalledTimes(1));+ abort.abort();+ await pending;+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(fixture.rows[0].pluginIntervention).toEqual({ status: 'aborted' });+ release(response('allow'));+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(fixture.execute).not.toHaveBeenCalled();+ });++ it.each([false, true])(+ 'never allows deny with unsupported additionalContext, queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ fetchHook.mockImplementation(+ async () =>+ new Response(+ JSON.stringify({+ hookSpecificOutput: {+ hookEventName: 'beforeToolCall',+ permissionDecision: 'deny',+ permissionDecisionReason: 'explicit denial',+ additionalContext: 'context',+ },+ }),+ ),+ );+ const fixture = setup([control()]);+ await fixture.step();+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(fixture.rows[0].content).toBe('explicit denial');+ },+ );++ it.each(['constructor', '__proto__'])('checks controls for native id %s', async (id) => {+ fetchHook.mockImplementation(async () => response('deny'));+ const fixture = setup([control()]);+ await fixture.step([call(id)]);+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(fixture.rows[0].pluginState).toEqual({+ reason: 'Blocked by beforeToolCall hook.',+ type: 'blocked',+ });+ await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: { parentMessageId: 'assistant', toolsCalling: [call(id)] },+ },+ fixture.state,+ );+ expect(fetchHook).toHaveBeenCalledTimes(2);+ expect(fixture.rows).toHaveLength(2);+ expect(fixture.execute).not.toHaveBeenCalled();+ });++ it.each(['updatedInput', 'additionalContext'] as const)(+ 'routes unsupported %s through onError',+ async (field) => {+ fetchHook.mockImplementation(+ async () =>+ new Response(+ JSON.stringify({+ hookSpecificOutput: {+ hookEventName: 'beforeToolCall',+ permissionDecision: 'allow',+ [field]: field === 'updatedInput' ? { path: 'b' } : 'context',+ },+ }),+ ),+ );+ const blocked = setup([control('block', 'block')]);+ await blocked.step();+ expect(blocked.execute).not.toHaveBeenCalled();+ expect(blocked.rows[0].content).toBe('unsupported_control_response');+ expect(blocked.rows[0].pluginIntervention).toEqual({+ status: 'rejected',+ rejectedReason: 'unsupported_control_response',+ });+ const continued = setup([control()]);+ await continued.step();+ expect(continued.execute).toHaveBeenCalledTimes(1);+ expect(continued.execute.mock.calls[0][0].arguments).toBe('{"path":"a"}');+ },+ );++ it.each([false, true])('does not await an ordinary HTTP observation, queue=%s', async (queue) => {+ queueMode.mockReturnValue(queue);+ let release!: (value: Response) => void;+ fetchHook.mockImplementation((url) =>+ url.endsWith('/observe')+ ? new Promise<Response>((resolve) => {+ release = resolve;+ })+ : Promise.resolve(response('allow')),+ );+ const fixture = setup(+ [+ control(),+ {+ id: 'observe',+ type: 'beforeToolCall',+ webhook: { url: 'https://hooks.example/observe', fallback: 'none' },+ },+ ],+ undefined,+ queue,+ );+ const pending = fixture.step();+ try {+ await vi.waitFor(() => expect(fixture.execute).toHaveBeenCalledTimes(1));+ expect((await pending).events).toContainEqual(+ expect.objectContaining({ type: 'tool_result' }),+ );+ } finally {+ release(response('allow'));+ await pending;+ }+ });++ it('lets an independent batch lane execute while another control is pending', async () => {+ let release!: (value: Response) => void;+ fetchHook.mockImplementation((_url, init) =>+ JSON.parse(init.body).toolCallId === 'slow'+ ? new Promise<Response>((resolve) => {+ release = resolve;+ })+ : Promise.resolve(response('allow')),+ );+ const fixture = setup([control()]);+ const pending = fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: { parentMessageId: 'assistant', toolsCalling: [call('slow'), call('fast')] },+ },+ fixture.state,+ );+ try {+ await vi.waitFor(() =>+ expect(fixture.execute).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ id: 'fast' }),+ expect.anything(),+ ),+ );+ } finally {+ release(response('deny'));+ await pending;+ }+ expect(fixture.rows).toHaveLength(2);+ expect(fixture.execute).toHaveBeenCalledTimes(1);+ });++ it('settles a denied client sibling while forwarding only allowed client calls', async () => {+ fetchHook.mockImplementation(async (_url, init) =>+ response(JSON.parse(init.body).toolCallId === 'denied' ? 'deny' : 'allow'),+ );+ const fixture = setup([control()]);+ fixture.state.toolSourceMap = { fs: 'client' };+ const result = await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: {+ parentMessageId: 'assistant',+ toolsCalling: [+ call('denied'),+ call('allowed'),+ { ...call('server'), identifier: 'other' },+ ],+ },+ },+ fixture.state,+ );+ expect(fetchHook).toHaveBeenCalledTimes(3);+ expect(fixture.execute).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ id: 'server' }),+ expect.anything(),+ );+ expect(result.events).toContainEqual(+ expect.objectContaining({+ type: 'tool_result',+ id: 'denied',+ result: expect.objectContaining({ success: false }),+ }),+ );+ expect(fixture.host.transports.stream.publishChunk).toHaveBeenCalledWith(+ expect.objectContaining({ chunkType: 'tools_calling', toolsCalling: [call('allowed')] }),+ );+ });++ it('checks controls when an approved tool reaches execution', async () => {+ const fixture = setup([control()]);+ fetchHook.mockImplementation(async () => response('deny'));+ await fixture.runtime.step(fixture.state, {+ phase: 'human_approved_tool',+ payload: { approvedToolCall: call(), parentMessageId: 'assistant' },+ });+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(fixture.rows[0].pluginState).toEqual({+ reason: 'Blocked by beforeToolCall hook.',+ type: 'blocked',+ });+ });+ it.each(['single', 'batch'] as const)(+ 'does not forward a denied legacy client tool in %s mode',+ async (mode) => {+ fetchHook.mockImplementation(async () => response('deny'));+ const fixture = setup([control()]);+ fixture.state.toolSourceMap = { fs: 'client' };+ const clientCall = { ...call(), executor: 'client' as const };+ const result =+ mode === 'single'+ ? await fixture.executors.call_tool!(+ {+ type: 'call_tool',+ payload: { parentMessageId: 'assistant', toolCalling: clientCall },+ },+ fixture.state,+ )+ : await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: { parentMessageId: 'assistant', toolsCalling: [clientCall] },+ },+ fixture.state,+ );+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(result.newState.status).toBe('running');+ expect(fixture.rows[0].pluginState).toEqual({+ reason: 'Blocked by beforeToolCall hook.',+ type: 'blocked',+ });+ },+ );++ it('hands an allowed legacy client call off only after its control returns', async () => {+ let release!: (value: Response) => void;+ fetchHook.mockImplementation(+ () =>+ new Promise<Response>((resolve) => {+ release = resolve;+ }),+ );+ const fixture = setup([control()]);+ fixture.state.toolSourceMap = { fs: 'client' };+ const pending = fixture.step();+ await vi.waitFor(() => expect(fetchHook).toHaveBeenCalledTimes(1));+ expect(fixture.host.transports.stream.publishChunk).not.toHaveBeenCalled();+ release(response('allow'));+ await pending;+ expect(fixture.host.transports.stream.publishChunk).toHaveBeenCalledWith(+ expect.objectContaining({ chunkType: 'tools_calling', toolsCalling: [call()] }),+ );+ expect(fixture.execute).not.toHaveBeenCalled();+ });++ it.each(['single', 'batch'] as const)(+ 'controls Gateway dispatch before client side effects in %s mode',+ async (mode) => {+ const fixture = setup([control()]);+ const clientCall = { ...call(), executor: 'client' as const };+ const invoke = () =>+ mode === 'single'+ ? fixture.executors.call_tool!(+ {+ type: 'call_tool',+ payload: { parentMessageId: 'assistant', toolCalling: clientCall },+ },+ fixture.state,+ )+ : fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: { parentMessageId: 'assistant', toolsCalling: [clientCall] },+ },+ fixture.state,+ );+ fetchHook.mockImplementation(async () => response('deny'));+ await invoke();+ expect(dispatchClient).not.toHaveBeenCalled();+ expect(fixture.execute).not.toHaveBeenCalled();+ fetchHook.mockImplementation(async () => response('allow'));+ await invoke();+ expect(dispatchClient).toHaveBeenCalledExactlyOnceWith(clientCall, expect.anything());+ expect(fixture.execute).not.toHaveBeenCalled();+ },+ );++ it.each(['continue', 'block'] as const)(+ 'applies onError=%s to a timed-out control without retry',+ async (policy) => {+ fetchHook.mockImplementation(+ (_url, init) =>+ new Promise((_resolve, reject) => {+ init.signal.addEventListener(+ 'abort',+ () => reject(new DOMException('timeout', 'AbortError')),+ { once: true },+ );+ }),+ );+ const hook = control('timeout', policy);+ hook.webhook!.timeout = 0.001;+ const fixture = setup([hook]);+ await fixture.step();+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(fixture.execute).toHaveBeenCalledTimes(policy === 'block' ? 0 : 1);+ },+ );++ it('does not reuse a native call id from a previous assistant turn', async () => {+ const fixture = setup([control()]);+ await fixture.step();+ fixture.execute.mockClear();+ fetchHook.mockClear();+ fetchHook.mockImplementation(async () => response('deny'));+ await fixture.step();+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(fixture.execute).not.toHaveBeenCalled();+ });++ it('reports critical observation failure without blocking a mock or HTTP sibling', async () => {+ const report = vi.spyOn(console, 'error').mockImplementation(() => {});+ fetchHook+ .mockRejectedValueOnce(new Error('network unavailable'))+ .mockResolvedValueOnce(response('allow'));+ const fixture = setup([+ {+ id: 'mock',+ type: 'beforeToolCall',+ handler: async (event) => {+ (event as ToolCallHookEvent).mock({ content: 'mock', success: true });+ },+ },+ {+ id: 'critical',+ type: 'beforeToolCall',+ webhook: { url: 'https://hooks.example/critical', fallback: 'none' },+ },+ { id: 'sibling', type: 'beforeToolCall', webhook: { url: 'https://hooks.example/sibling' } },+ ]);+ const result = await fixture.step();+ await vi.waitFor(() => expect(fetchHook).toHaveBeenCalledTimes(2));+ expect(report).toHaveBeenCalledWith(+ '[HookDispatcher] Critical webhook delivery failed',+ expect.objectContaining({+ operationId: 'op',+ hookId: 'critical',+ hookType: 'beforeToolCall',+ }),+ expect.anything(),+ );+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(fixture.rows).toHaveLength(1);+ expect(result.events).toContainEqual(+ expect.objectContaining({+ type: 'tool_result',+ result: expect.objectContaining({ content: 'mock' }),+ }),+ );+ });+ it('settles an already-approved row when the refreshed control denies it', async () => {+ const fixture = setup([control()]);+ fetchHook.mockImplementation(async () => response('deny'));+ const result = await fixture.runtime.step(fixture.state, {+ phase: 'human_approved_tool',+ payload: {+ approvedToolCall: call(),+ parentMessageId: 'pending-tool-row',+ skipCreateToolMessage: true,+ },+ });+ expect(fixture.execute).not.toHaveBeenCalled();+ expect(fixture.rows).toHaveLength(0);+ expect(fixture.host.transports.messages.updateToolMessage).toHaveBeenCalledWith(+ 'pending-tool-row',+ expect.objectContaining({+ pluginState: { reason: 'Blocked by beforeToolCall hook.', type: 'blocked' },+ }),+ );+ expect(fixture.host.transports.messages.updateToolIntervention).toHaveBeenCalledWith(+ 'pending-tool-row',+ { rejectedReason: 'Blocked by beforeToolCall hook.', status: 'rejected' },+ );+ expect(result.events).toContainEqual(expect.objectContaining({ type: 'tool_result' }));+ });+});diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.tsindex a3efad157e1..adfb8a97d4b 100644--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts@@ -3,13 +3,14 @@ import type { SerializedAgentHook } from '@lobechat/types';import {agentHookMatcherSchema,agentHookTypeSchema,+ resolveToolCallHookErrorPolicy,serializedAgentHookSchema,} from '@lobechat/types';import debug from 'debug';import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';-import { deliverWebhook } from './httpWebhook';+import { deliverWebhook, executeToolCallWebhook } from './httpWebhook';import { matchesHook } from './matcher';import type {AgentHook,@@ -35,20 +36,9 @@ export class CriticalHookDeliveryError extends Error {export { deliverWebhook } from './httpWebhook';-export class UnsupportedControlHookError extends Error {- constructor() {- super('toolCall hooks are unsupported until the tool preparation pipeline is integrated');- this.name = 'UnsupportedControlHookError';- }-}--/** Validate persisted configurations before selecting an event, never silently discard controls. */+/** Validate persisted configurations on every worker restore. */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;- });+ return hooks.map((hook) => serializedAgentHookSchema.parse(hook));}/**@@ -82,6 +72,17 @@ export class HookDispatcher {* runtime-precise {@link SerializedHook} once the type / webhook are checked.*/serializedHooks?: SerializedAgentHook[],+ ): Promise<void> {+ return this.dispatchHooks(operationId, type, event, serializedHooks);+ }++ private async dispatchHooks(+ operationId: string,+ type: AgentHookType,+ event: AnyHookEvent,+ serializedHooks?: SerializedAgentHook[],+ stopAfterHandler?: () => boolean,+ consumer?: 'handler' | 'webhook',): Promise<void> {const isQueueMode = isQueueAgentRuntimeEnabled();const restored = serializedHooks ? parseSerializedHooks(serializedHooks) : undefined;@@ -91,9 +92,18 @@ export class HookDispatcher {? (restored ?? this.getSerializedHooks(operationId) ?? []): (registered ?? restored ?? []);let criticalError: CriticalHookDeliveryError | undefined;- for (const hook of hooks.filter((h) => h.type === type && matchesHook(h.matcher, event))) {+ for (const hook of hooks.filter(+ (h) =>+ h.type === type &&+ h.webhook?.responseHandling !== 'toolCall' &&+ matchesHook(h.matcher, event),+ )) {const handler = 'handler' in hook ? hook.handler : undefined;const useHandler = !isQueueMode && !!handler;+ if (consumer === 'handler' && !useHandler) continue;+ if (consumer === 'webhook' && useHandler) continue;+ // Preserve first-mock handler semantics without dropping independent HTTP callbacks.+ if (useHandler && stopAfterHandler?.()) continue;try {if (useHandler) {await handler(event as AgentHookEvent);@@ -102,7 +112,10 @@ export class HookDispatcher {hookId: hook.id,hookType: type,});- if (payload) await deliverWebhook(hook.webhook, payload);+ if (payload) {+ delete payload.mock;+ await deliverWebhook(hook.webhook, payload);+ }}} catch (error) {if (!useHandler && hook.webhook?.fallback === 'none') {@@ -127,50 +140,98 @@ export class HookDispatcher {if (criticalError) throw criticalError;}- /**- * Dispatch beforeToolCall hooks with mock support.- * Returns mock result if any handler called event.mock(), otherwise null.- */+ /** Ordered synchronous controls. Cancellation never goes through onError. */+ async evaluateToolCall(+ operationId: string,+ event: Omit<ToolCallHookEvent, 'mock'>,+ 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 ?? []);+ for (const hook of hooks) {+ if (signal?.aborted) return { status: 'cancelled' };+ if (+ hook.type !== 'beforeToolCall' ||+ hook.webhook?.responseHandling !== 'toolCall' ||+ !matchesHook(hook.matcher, event)+ )+ continue;+ const payload = await this.buildWebhookPayload(+ event,+ {},+ { hookId: hook.id, hookType: 'beforeToolCall' },+ { signal },+ );+ if (!payload || signal?.aborted) return { status: 'cancelled' };+ const response = await executeToolCallWebhook(hook.webhook, payload, { signal });+ if (signal?.aborted || response.status === 'cancelled') return { status: 'cancelled' };+ // An explicit deny is authoritative even when extra fields are unsupported.+ if (response.status === 'success' && response.decision?.permissionDecision === 'deny') {+ return {+ status: 'blocked',+ reason: response.decision.permissionDecisionReason ?? 'Blocked by beforeToolCall hook.',+ };+ }+ // This entry supports allow/deny only; unsupported responses follow onError.+ const unsupported =+ response.status === 'success' &&+ (response.decision?.updatedInput !== undefined ||+ response.decision?.additionalContext !== undefined);+ if (response.status === 'error' || unsupported) {+ if (resolveToolCallHookErrorPolicy(hook.webhook.onError).action === 'block') {+ return {+ status: 'blocked',+ reason: unsupported ? 'unsupported_control_response' : 'hook_control_error',+ };+ }+ continue;+ }+ }+ return signal?.aborted ? { status: 'cancelled' } : { status: 'allow' };+ }++ /** Deliver each observation once; only local handlers can supply a mock. */async dispatchBeforeToolCall(operationId: string,event: Omit<ToolCallHookEvent, 'mock' | 'operationId'>,- ): Promise<{- isMocked: true;- result: ToolRunResult;- } | null> {- 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;+ serializedHooks?: SerializedAgentHook[],+ ): Promise<{ isMocked: true; result: ToolRunResult } | null> {let mockedResult: ToolRunResult | undefined;-const toolCallEvent: ToolCallHookEvent = {...event,mock: (result) => {- if (isMocked) return false;- isMocked = true;+ if (mockedResult) return false;mockedResult = result;return true;},operationId,};-- for (const hook of hooks) {- try {- log('[%s][beforeToolCall] Dispatching: %s', operationId, hook.id);- await hook.handler?.(toolCallEvent as any);- } catch {- log('[%s][beforeToolCall] Hook error (non-fatal): %s', operationId, hook.id);- }- if (isMocked) break;- }-- return isMocked && mockedResult ? { isMocked: true, result: mockedResult } : null;+ // Observations never become a tool-execution prerequisite. The normal+ // dispatcher retains critical failure reporting and independent siblings.+ void this.dispatchHooks(+ operationId,+ 'beforeToolCall',+ toolCallEvent,+ serializedHooks,+ undefined,+ 'webhook',+ ).catch((error: unknown) => {+ log('[%s][beforeToolCall] Observation delivery rejected: %O', operationId, error);+ });+ // Legacy local handlers can supply an asynchronous mock. Invoke them once;+ // the first mock stops only handlers, not the independent HTTP observation.+ await this.dispatchHooks(+ operationId,+ 'beforeToolCall',+ toolCallEvent,+ serializedHooks,+ () => !!mockedResult,+ 'handler',+ );+ return mockedResult ? { isMocked: true, result: mockedResult } : null;}/**@@ -248,10 +309,8 @@ export class HookDispatcher {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();- }+ if (parsed.webhook.responseHandling === 'toolCall' && hook.handler)+ throw new Error('Control hooks cannot have a handler');return { ...parsed, handler: hook.handler } as AgentHook;} else if (!hook.handler) {throw new Error('A hook requires a handler or webhook');diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.tsindex bfe2d5666b7..40edf4e70df 100644--- a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts@@ -935,12 +935,7 @@ describe('HookDispatcher', () => {stepIndex: 0,});- // In local mode this would return the mock, but hooks are still in-memory- // so it should still work (dispatchBeforeToolCall doesn't check queue mode)- expect(result).toEqual({- isMocked: true,- result: { content: '{"mocked":true}', success: true },- });+ expect(result).toBeNull();});it('should not affect other hook types when beforeToolCall is registered', async () => {diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.tsindex 084b5718995..170284c985f 100644--- a/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.ts+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/contract.test.ts@@ -1,7 +1,7 @@import type { SerializedAgentHook } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { HookDispatcher, UnsupportedControlHookError } from '../HookDispatcher';+import { HookDispatcher } from '../HookDispatcher';import { matchesHook } from '../matcher';import type { AgentHook, AgentHookEvent } from '../types';@@ -87,20 +87,18 @@ describe('hook registration and restoration', () => {dispatcher.register('op', [serialized]);expect(dispatcher.getSerializedHooks('op')).toEqual([serialized]);});- it('blocks unsupported controls on registration atomically and on restore before event selection', async () => {+ it('registers/restores controls but ordinary dispatch never delivers them', 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);+ dispatcher.register('op', [control]);+ expect(dispatcher.getSerializedHooks('op')).toEqual([control]);for (const queue of [false, true]) {queueMode.mockReturnValue(queue);- await expect(- dispatcher.dispatch('op', 'onComplete', event, [control as SerializedAgentHook]),- ).rejects.toThrow(UnsupportedControlHookError);+ await dispatcher.dispatch('op', 'beforeToolCall', event, [control as SerializedAgentHook]);}expect(fetchMock).not.toHaveBeenCalled();});diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/controlWebhookPayload.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/controlWebhookPayload.test.tsnew file mode 100644index 00000000000..e0988d9cdfb--- /dev/null+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/controlWebhookPayload.test.ts@@ -0,0 +1,121 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { HookDispatcher } from '../HookDispatcher';+import type { AgentHook } from '../types';++const { fetchHook, getEmailsByIds } = vi.hoisted(() => ({+ fetchHook: vi.fn(),+ getEmailsByIds: vi.fn(),+}));+vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds } }));+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: () => false }));+vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));++const event = {+ apiName: 'write',+ args: { path: 'effective' },+ assistantMessageId: 'assistant',+ callIndex: 0,+ executor: 'server' as const,+ identifier: 'fs',+ operationId: 'op',+ stepIndex: 0,+ toolCallId: 'native',+ userId: 'visitor',+ userEmail: '[email protected]',+};+function setup(onError: 'continue' | 'block' = 'continue') {+ const hook: AgentHook = {+ id: 'control',+ type: 'beforeToolCall',+ webhook: {+ url: 'https://hooks.example/control',+ responseHandling: 'toolCall',+ onError,+ },+ };+ const dispatcher = new HookDispatcher();+ dispatcher.register('op', [hook]);+ return dispatcher;+}++beforeEach(() => {+ vi.stubGlobal('fetch', fetchHook);+ getEmailsByIds.mockReset().mockResolvedValue([{ id: 'visitor', email: '[email protected]' }]);+ fetchHook.mockReset().mockImplementation(+ async () =>+ new Response(+ JSON.stringify({+ hookSpecificOutput: { hookEventName: 'beforeToolCall', permissionDecision: 'allow' },+ }),+ ),+ );+});+afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('control webhook payload enrichment', () => {+ it('enriches authoritative controls without applying body overrides or projections', async () => {+ expect(await setup().evaluateToolCall('op', event)).toEqual({+ status: 'allow',+ });+ expect(getEmailsByIds).toHaveBeenCalledWith({}, ['visitor']);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({+ ...event,+ userEmail: '[email protected]',+ hookId: 'control',+ hookType: 'beforeToolCall',+ });+ });++ it.each(['continue', 'block'] as const)(+ 'omits failed email enrichment without invoking control onError=%s',+ async (policy) => {+ getEmailsByIds.mockRejectedValue(new Error('database unavailable'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ expect(await setup(policy).evaluateToolCall('op', event)).toMatchObject({ status: 'allow' });+ expect(getEmailsByIds).toHaveBeenCalledTimes(1);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).not.toHaveProperty('userEmail');+ expect(fetchHook).toHaveBeenCalledTimes(1);+ },+ );++ it('does not look up email or send HTTP after prior cancellation', async () => {+ const abort = new AbortController();+ abort.abort();+ expect(await setup().evaluateToolCall('op', event, undefined, abort.signal)).toMatchObject({+ status: 'cancelled',+ });+ expect(getEmailsByIds).not.toHaveBeenCalled();+ expect(fetchHook).not.toHaveBeenCalled();+ });++ it('cancels an email waiter without sending HTTP or cancelling its sibling', async () => {+ let resolveEmail!: (rows: { id: string; email: string }[]) => void;+ getEmailsByIds.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveEmail = resolve;+ }),+ );+ const dispatcher = setup();+ const abort = new AbortController();+ const cancelled = dispatcher.evaluateToolCall('op', event, undefined, abort.signal);+ const sibling = dispatcher.evaluateToolCall('op', { ...event, toolCallId: 'sibling' });+ await vi.waitFor(() => expect(getEmailsByIds).toHaveBeenCalledTimes(1));+ abort.abort();+ expect(await cancelled).toMatchObject({ status: 'cancelled' });+ expect(fetchHook).not.toHaveBeenCalled();+ resolveEmail([{ id: 'visitor', email: '[email protected]' }]);+ expect(await sibling).toMatchObject({ status: 'allow' });+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({+ toolCallId: 'sibling',+ userEmail: '[email protected]',+ });+ });+});diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/webhookUserEmail.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/webhookUserEmail.test.tsindex b23ca675c10..ce67a526fd4 100644--- a/apps/server/src/services/agentRuntime/hooks/__tests__/webhookUserEmail.test.ts+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/webhookUserEmail.test.ts@@ -7,13 +7,15 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }import { HookDispatcher, hookDispatcher } from '../HookDispatcher';import type {AfterToolCallHookEvent,+ AgentHook,AgentHookEvent,AgentHookType,SerializedHook,} from '../types';import { createWebhookPayloadBuilder } from '../webhookPayload';-const { getEmailsByIds, publishJSON } = vi.hoisted(() => ({+const { getEmailsByIds, publishJSON, queueMode } = vi.hoisted(() => ({+ queueMode: { enabled: true },getEmailsByIds: vi.fn(),publishJSON: vi.fn(),}));@@ -21,7 +23,9 @@ vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds } }));vi.mock('@/database/server', () => ({getServerDB: async () => ({}),}));-vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: () => true }));+vi.mock('@/server/services/queue/impls', () => ({+ isQueueAgentRuntimeEnabled: () => queueMode.enabled,+}));vi.mock('@upstash/qstash', () => ({Client: class {publishJSON = publishJSON;@@ -67,6 +71,7 @@ afterAll(async () => {);});beforeEach(() => {+ queueMode.enabled = true;dispatcher = new HookDispatcher();received.length = 0;getEmailsByIds@@ -488,3 +493,58 @@ describe('webhook tool results', () => {expect(payload?.result).toEqual(result);});});++describe('before-tool observation identity', () => {+ it.each([false, true])(+ 'delivers final payload identity while preserving mock short-circuiting (queue=%s)',+ async (isQueue) => {+ queueMode.enabled = isQueue;+ const first = vi.fn((event) => event.mock({ content: 'mocked', success: true }));+ const skipped = vi.fn();+ const hooks: AgentHook[] = [+ { id: 'first-mock', type: 'beforeToolCall', handler: first },+ { id: 'later-handler', type: 'beforeToolCall', handler: skipped },+ ...['owner-notification', 'sibling'].map((id): AgentHook => ({+ id,+ type: 'beforeToolCall',+ webhook: { url, body: { userId: 'owner' } },+ })),+ ];+ dispatcher.register('run', hooks);+ const serialized = dispatcher.getSerializedHooks('run');+ if (isQueue) dispatcher = new HookDispatcher(); // Cold worker has only persisted hooks.+ const toolEvent = {+ ...event,+ apiName: 'write',+ args: {},+ assistantMessageId: 'assistant',+ callIndex: 0,+ stepIndex: 0,+ executor: 'server' as const,+ identifier: 'fs',+ toolCallId: 'native',+ };+ const result = await dispatcher.dispatchBeforeToolCall('run', toolEvent, serialized);+ expect(result).toEqual(+ isQueue ? null : { isMocked: true, result: { content: 'mocked', success: true } },+ );+ expect(first).toHaveBeenCalledTimes(isQueue ? 0 : 1);+ expect(skipped).not.toHaveBeenCalled();+ await vi.waitFor(() => expect(received).toHaveLength(2));+ for (const payload of received) {+ expect(payload).toMatchObject({ userId: 'owner', userEmail: '[email protected]' });+ expect(payload).not.toHaveProperty('mock');+ expect(payload).not.toHaveProperty('deliveryContext');+ expect(payload).not.toHaveProperty('ownerUserId');+ }+ // A later delivery reuses the final identity email without invoking skipped handlers.+ await dispatcher.dispatchBeforeToolCall('run', toolEvent, serialized);+ await vi.waitFor(() => expect(received).toHaveLength(4));+ expect(received[2]).toMatchObject({ userId: 'owner', userEmail: '[email protected]' });+ expect(received[3]).toMatchObject({ userId: 'owner', userEmail: '[email protected]' });+ expect(getEmailsByIds).toHaveBeenCalledTimes(1);+ expect(skipped).not.toHaveBeenCalled();+ expect(JSON.stringify(serialized)).not.toContain('ownerUserId');+ },+ );+});diff --git a/apps/server/src/services/agentRuntime/hooks/index.ts b/apps/server/src/services/agentRuntime/hooks/index.tsindex fa1cd129382..7b5f1bfdadf 100644--- a/apps/server/src/services/agentRuntime/hooks/index.ts+++ b/apps/server/src/services/agentRuntime/hooks/index.ts@@ -3,7 +3,6 @@ export {HookDispatcher,hookDispatcher,parseSerializedHooks,- UnsupportedControlHookError,} from './HookDispatcher';export { executeToolCallWebhook } from './httpWebhook';export { matchesHook } from './matcher';diff --git a/apps/server/src/services/agentRuntime/hooks/types.ts b/apps/server/src/services/agentRuntime/hooks/types.tsindex f46dfeb2b32..ea9a39f7d7d 100644--- a/apps/server/src/services/agentRuntime/hooks/types.ts+++ b/apps/server/src/services/agentRuntime/hooks/types.ts@@ -46,7 +46,7 @@ export type NotificationWebhook = AgentHookWebhook & {responseHandling?: 'ignore';};-/** Control hooks are webhook-only and synchronous. Runtime support is gated by registration. */+/** Control hooks are webhook-only and synchronous. Evaluated at tool execution entry, after product permission and approval. */export type AgentHook = {id: string;matcher?: AgentHookMatcher;diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex ba14e4066ea..7def6d10bf2 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -489,6 +489,9 @@ const createToolMessage = async ({parentId: parentMessageId,plugin: tool as any,pluginError: result.error,+ ...(result.state?.type === 'blocked' && {+ pluginIntervention: { rejectedReason: result.state.reason, status: 'rejected' },+ }),pluginState: result.state,role: 'tool',threadId: host.operation.threadId ?? state.origin?.threadId,@@ -517,6 +520,12 @@ const updateExistingToolMessage = async ({pluginError: result.error,pluginState: result.state,});+ if (result.state?.type === 'blocked') {+ await host.transports.messages.updateToolIntervention(toolMessageId, {+ rejectedReason: result.state.reason,+ status: 'rejected',+ });+ }} catch (error) {await publishError(host, error, TOOL_MESSAGE_PERSIST_PHASE);throw markPersistFatal(error);@@ -582,55 +591,43 @@ export const callTool =type: 'tool_start',});- if (runContext.toolSource === 'client' && !tools.canRunClientTools) {- // Parking is only meaningful if something will come back for it. Once the- // operation is aborted nothing resumes this run, so the pause would leave- // the call with no row at all — settle it instead.- if (host.operation.abortSignal?.aborted) {- return settleAbortedCall({- events,- existingToolMessageId: payload.skipCreateToolMessage- ? payload.parentMessageId- : undefined,+ try {+ const intercepted = await raceToolAbort(+ () => tools.beforeToolCall?.(tool, runContext) ?? Promise.resolve(undefined),+ host.operation.abortSignal,+ );+ if (host.operation.abortSignal?.aborted) throw new ToolAbortedError();+ if (!intercepted && runContext.toolSource === 'client' && !tools.canRunClientTools) {+ const paused = await pauseForTools({host,- parentMessageId: payload.parentMessageId,+ instruction,+ reason: 'client_tool_execution',state,- tool,+ toolsCalling: [tool],});- }- const paused = await pauseForTools({- host,- instruction,- reason: 'client_tool_execution',- state,- toolsCalling: [tool],- });+ // Stop can arrive while the chunk is being published. Do not return a+ // parked state after that asynchronous gap: no client result will ever+ // resume an operation that has already been interrupted.+ if (host.operation.abortSignal?.aborted) {+ return settleAbortedCall({+ events,+ existingToolMessageId: payload.skipCreateToolMessage+ ? payload.parentMessageId+ : undefined,+ host,+ parentMessageId: payload.parentMessageId,+ state,+ tool,+ });+ }- // Stop can arrive while the chunk is being published. Do not return a- // parked state after that asynchronous gap: no client result will ever- // resume an operation that has already been interrupted.- if (host.operation.abortSignal?.aborted) {- return settleAbortedCall({- events,- existingToolMessageId: payload.skipCreateToolMessage- ? payload.parentMessageId- : undefined,- host,- parentMessageId: payload.parentMessageId,- state,- tool,- });+ return paused;}- return paused;- }-- try {- const execution = await raceToolAbort(- () => tools.run(tool, runContext),- host.operation.abortSignal,- );+ const execution =+ intercepted ??+ (await raceToolAbort(() => tools.run(tool, runContext), host.operation.abortSignal));if (execution.interrupted) {// The transport bailed after creating its optimistic row but before a@@ -668,7 +665,10 @@ export const callTool =executionTime,isSuccess,attempts: execution.attempts,- maxAttempts: (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,+ maxAttempts:+ executionResult.state?.type === 'blocked'+ ? 0+ : (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,payload,phase: TOOL_EXECUTION_PHASE,result: redactResultForEvents(executionResult),@@ -729,7 +729,8 @@ export const callTool =type: 'tool_result',});- const toolCost = tools.getCost?.(runContext.toolName) ?? 0;+ const toolCost =+ executionResult.state?.type === 'blocked' ? 0 : (tools.getCost?.(runContext.toolName) ?? 0);const { usage, cost } = UsageCounter.accumulateTool({cost: newState.cost,executionTime,@@ -861,7 +862,11 @@ export const callToolsBatch =const serverTools: ChatToolPayload[] = [];for (const tool of toolsCalling) {- if (resolveToolSource(state, tool) === 'client' && !tools.canRunClientTools)+ if (+ !tools.beforeToolCall &&+ resolveToolSource(state, tool) === 'client' &&+ !tools.canRunClientTools+ )clientTools.push(tool);else serverTools.push(tool);}@@ -922,7 +927,9 @@ export const callToolsBatch =const toolsToExecute = serverTools.length > 0 ? serverTools : toolsCalling;const runOne = async (tool: ChatToolPayload) => {- const existingMessageId = existingToolMessageIds[tool.id];+ const existingMessageId = Object.hasOwn(existingToolMessageIds, tool.id)+ ? existingToolMessageIds[tool.id]+ : undefined;const runContext = createRunContext({host,mode: 'batch',@@ -941,10 +948,18 @@ export const callToolsBatch =});try {- const execution = await raceToolAbort(- () => tools.run(tool, runContext),+ const intercepted = await raceToolAbort(+ () => tools.beforeToolCall?.(tool, runContext) ?? Promise.resolve(undefined),host.operation.abortSignal,);+ if (host.operation.abortSignal?.aborted) throw new ToolAbortedError();+ if (!intercepted && runContext.toolSource === 'client' && !tools.canRunClientTools) {+ clientTools.push(tool);+ return;+ }+ const execution =+ intercepted ??+ (await raceToolAbort(() => tools.run(tool, runContext), host.operation.abortSignal));if (execution.interrupted) {abortedTools.push(tool);@@ -967,7 +982,10 @@ export const callToolsBatch =executionTime,isSuccess,attempts: execution.attempts,- maxAttempts: (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,+ maxAttempts:+ executionResult.state?.type === 'blocked'+ ? 0+ : (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,payload: { parentMessageId, toolCalling: tool },phase: TOOL_EXECUTION_PHASE,result: redactResultForEvents(executionResult),@@ -1018,7 +1036,10 @@ export const callToolsBatch =type: 'tool_result',});- const toolCost = tools.getCost?.(runContext.toolName) ?? 0;+ const toolCost =+ executionResult.state?.type === 'blocked'+ ? 0+ : (tools.getCost?.(runContext.toolName) ?? 0);resultEntry.usageParams = {executionTime,success: isSuccess,@@ -1059,8 +1080,8 @@ export const callToolsBatch =}),);- // Client tools in a mixed batch never entered `toolsToExecute` — they were- // waiting for the pause below to hand them to the client. Once the operation+ // Allowed client tools are waiting for the pause below to hand them to the+ // client; they have not launched any work. Once the operation// is aborted that pause parks calls into a run nothing will resume, so their// tool_call_ids would keep no rows at all. Settle them alongside the ones// caught mid-flight, and skip the pause entirely.diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.tsindex b00446b83ce..1b9d0d5bf76 100644--- a/packages/agent-runtime/src/transport/tool.ts+++ b/packages/agent-runtime/src/transport/tool.ts@@ -138,6 +138,11 @@ export interface ToolRunContext {* client adapter wraps `internal_invokeDifferentTypePlugin`.*/export interface ToolTransport {+ /** Execution-entry control; a returned result settles this call without launching it. */+ beforeToolCall?: (+ call: ChatToolPayload,+ context: ToolRunContext,+ ) => Promise<ToolRunExecution | undefined>;/** This runtime can execute tools whose source is the client directly. */canRunClientTools?: boolean;getCost?: (toolName: string) => number;