Skip to content

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

✨ feat(agent-runtime): enrich tool hook events with call context and results (#20127)

Bryane482c2e36334
diff --git a/.agents/skills/agent-runtime-hooks/SKILL.md b/.agents/skills/agent-runtime-hooks/SKILL.md
index 6c942f960d7..ad465810044 100644
--- a/.agents/skills/agent-runtime-hooks/SKILL.md
+++ b/.agents/skills/agent-runtime-hooks/SKILL.md
@@ -6,7 +6,7 @@ user-invocable: false
# Agent Runtime Hooks
-Lifecycle hooks for observing and intercepting agent execution. Hooks are registered per-operation via `execAgent({ hooks })` and dispatched by `HookDispatcher`.
+Register lifecycle hooks through `execAgent({ hooks })`. `HookDispatcher` stores them per operation and dispatches them in registration order.
## Hook Types
@@ -37,7 +37,7 @@ execAgent({ hooks })
β”‚ β”‚
β”‚ β”œβ”€ [callAgent] (via execSubAgentTask)
β”‚ β”‚ β”œβ”€ beforeCallAgent ── Before sub-agent starts
- β”‚ β”‚ β”œβ”€ afterCallAgent ─── After sub-agent completes
+ β”‚ β”‚ β”œβ”€ afterCallAgent ─── After creation/start returns
β”‚ β”‚ └─ onCallAgentError ── Sub-agent failed
β”‚ β”‚
β”‚ └─ afterStep ──────────── After step completes
@@ -50,156 +50,89 @@ execAgent({ hooks })
## Key Files
-| File | Role |
-| --------------------------------------------------------------- | ------------------------------------------------------ |
-| `packages/agent-runtime/src/types/hooks.ts` | Type definitions (AgentHookType, all event interfaces) |
-| `apps/server/src/services/agentRuntime/hooks/types.ts` | Server-side types (AgentHook, re-exports) |
-| `apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts` | Registration, dispatch, dispatchBeforeToolCall |
-| `apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts` | Tool/Compact/HumanIntervention hook dispatch |
-| `apps/server/src/services/agentRuntime/AgentRuntimeService.ts` | Step hooks + HumanIntervention resume/reject |
-| `apps/server/src/services/aiAgent/subAgentRuns.ts` | CallAgent hook dispatch |
-
-## Registration Flow
+| File | Role |
+| ---------------------------------------------------------------------- | --------------------------------------------------------- |
+| `packages/agent-runtime/src/types/hooks.ts` | Event types and required/optional fields |
+| `apps/server/src/services/agentRuntime/hooks/types.ts` | Registration and webhook types |
+| `apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts` | Registration, dispatch, local mocks, HTTP/QStash delivery |
+| `apps/server/src/services/agentRuntime/hooks/webhookPayload.ts` | Event projection and email enrichment |
+| `apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.ts` | Shared tool-event context builder |
+| `apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts` | Tool notifications and execution results |
+| `apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts` | Tool, compression and human-intervention execution |
+| `apps/server/src/services/agentRuntime/AgentRuntimeService.ts` | Step events and human-intervention continuation |
+| `apps/server/src/services/agentRuntime/CompletionLifecycle.ts` | Terminal events |
+| `apps/server/src/services/aiAgent/subAgentRuns.ts` | Sub-agent events |
+
+## Registration
```ts
const hooks: AgentHook[] = [
- { id: 'my-hook', type: 'afterStep', handler: async (event) => { ... } },
+ {
+ id: 'observe-step',
+ type: 'afterStep',
+ handler: async (event) => {
+ console.log(event.operationId, event.stepIndex);
+ },
+ },
];
await aiAgentService.execAgent({ agentId, prompt, hooks });
-// Internally: hookDispatcher.register(operationId, hooks)
-// Cleanup: hookDispatcher.unregister(operationId)
-```
-
-## Hook Reference
-
-### Step Level
-
-**`beforeStep`** β€” Before each step. `event: AgentHookEvent`
-**`afterStep`** β€” After each step. `event: AgentHookEvent` (content, toolsCalling, totalCost, etc.)
-**`onComplete`** β€” Terminal state. `event: AgentHookEvent` (reason: done/error/interrupted/max\_steps/cost\_limit)
-**`onError`** β€” Error occurred. `event: AgentHookEvent` (errorMessage, errorDetail)
-
-### Tool Call Level
-
-**`beforeToolCall`** β€” Before tool executes. **Supports mocking** via `event.mock()`.
-
-```ts
-// event: ToolCallHookEvent
-{
- (identifier, apiName, args, callIndex, stepIndex, operationId, mock);
-}
-// Mock example:
-event.mock({ content: '{"error":"rate limited"}' });
-```
-
-Dispatch method: `hookDispatcher.dispatchBeforeToolCall()` (returns mock result or null).
-
-**`afterToolCall`** β€” After tool completes. Observation only.
-
-```ts
-// event: AfterToolCallHookEvent
-{
- (identifier, apiName, args, callIndex, content, success, mocked, executionTimeMs, stepIndex);
-}
-```
-
-**`onToolCallError`** β€” Tool threw an exception (catch block, not just `success=false`).
-
-```ts
-// event: ToolCallErrorHookEvent
-{
- (identifier, apiName, args, callIndex, error, stepIndex);
-}
-```
-
-### Human Intervention
-
-**`beforeHumanIntervention`** β€” Before agent pauses for approval.
-
-```ts
-// event: BeforeHumanInterventionHookEvent
-{ operationId, stepIndex, pendingTools: [{ identifier, apiName }] }
-```
-
-**`afterHumanIntervention`** β€” After approve/reject, agent resumes.
-
-```ts
-// event: AfterHumanInterventionHookEvent
-{ operationId, action: 'approve' | 'reject' | 'rejectAndContinue', toolCallId?, rejectionReason? }
```
-**`onStopByHumanIntervention`** β€” User rejected, agent halted.
-
-```ts
-// event: StopByHumanInterventionHookEvent
-{ operationId, toolCallId?, rejectionReason? }
-```
+Local dispatch awaits in-process handlers. Queue dispatch uses serialized webhook configuration from `state.host.hooks` or registered hooks. Completion cleans up registrations through `hookDispatcher.unregister(operationId)`.
-### Context Compression
+## Events
-**`beforeCompact`** β€” Before compression starts.
+| Event | Timing and payload |
+| --------------------------- | ------------------------------------------------------------------------------------------ |
+| `beforeStep` | Before a step; `AgentHookEvent` |
+| `afterStep` | After a step; content, tool calls/results and usage totals |
+| `onComplete` | Terminal state; reason such as `done`, `error`, `interrupted`, `max_steps` or `cost_limit` |
+| `onError` | Operation error; `errorMessage`, `errorDetail` and available error metadata |
+| `beforeToolCall` | Before tool execution; shared tool context and local `mock()` callback |
+| `afterToolCall` | After tool execution; structured `result` and `mocked` |
+| `onToolCallError` | Tool execution throws; shared tool context and `error` |
+| `beforeHumanIntervention` | Before approval; `pendingTools`, `operationId`, `stepIndex` |
+| `afterHumanIntervention` | Approval decision and continuation; `action`, optional `toolCallId` and `rejectionReason` |
+| `onStopByHumanIntervention` | Human rejection stops the run; optional `toolCallId` and `rejectionReason` |
+| `beforeCompact` | Before compression; `messageCount`, `tokenCount`, `stepIndex` |
+| `afterCompact` | After compression; `groupId`, `messagesBefore`, `messagesAfter`, `summary` |
+| `onCompactError` | Compression error; `error`, `tokenCount`, `stepIndex` |
+| `beforeCallAgent` | Before sub-agent creation; `agentId`, `instruction` |
+| `afterCallAgent` | Creation/start returns; `agentId`, `subOperationId`, `success`, optional `threadId` |
+| `onCallAgentError` | Sub-agent call fails; `agentId`, `error` |
-```ts
-// event: BeforeCompactHookEvent
-{
- (operationId, stepIndex, messageCount, tokenCount);
-}
-```
+CallAgent events dispatch on the parent operation identified by `parentOperationId`. An isolated child supplies `threadId`; shared group members use the shared conversation. Child completion is reported by the child's `onComplete` event.
-**`afterCompact`** β€” After compression completes.
+## Tool Context
-```ts
-// event: AfterCompactHookEvent
-{
- (operationId, stepIndex, groupId, messagesBefore, messagesAfter, summary);
-}
-```
+Use `buildToolCallHookContext()` for the three tool events.
-**`onCompactError`** β€” Compression failed.
+- Required fields: native `toolCallId`, `assistantMessageId`, `identifier`, `apiName`, effective `args`, `callIndex`, `stepIndex`, `operationId` and `executor`.
+- Optional associations come from the run context: agent, topic, session, thread, group, task, workspace, document, source/tool message and parent operation IDs.
+- `userId` uses `runtime.userId ?? origin.userId`.
+- `toolSource` identifies the tool's origin; `executor` identifies the server/client dispatch route. `executionTarget` and `activeDeviceId` describe the run's execution plan and device selection.
+- `afterToolCall.result` carries `content`, `success`, optional `executionTime` and error/state data such as `state.type: 'blocked'`. `mocked` marks results supplied by a local hook.
-```ts
-// event: CompactErrorHookEvent
-{
- (operationId, stepIndex, tokenCount, error);
-}
-```
+Sandbox and MCP tools use the same event path. Filter with `identifier`, `apiName` or `toolSource`.
-### Sub-Agent (CallAgent)
+### Local Mocking
-**`beforeCallAgent`** β€” Before calling sub-agent. Dispatched on **parent** operation.
+`dispatchBeforeToolCall()` exposes `event.mock(result)`. The first accepted mock wins and short-circuits the remaining mock handlers. The method returns `{ isMocked: true, result }` for a mock, or `null` to continue execution.
```ts
-// event: BeforeCallAgentHookEvent
-{
- (operationId, agentId, instruction);
-}
+event.mock({ content: '{"items":[]}', success: true });
```
-**`afterCallAgent`** β€” Sub-agent completed. Dispatched on **parent** operation.
+Tool observation payloads use `BeforeToolCallObservationEvent`; the callback belongs to the local handler event.
-```ts
-// event: AfterCallAgentHookEvent
-{
- (operationId, agentId, subOperationId, threadId, success);
-}
-```
+## Webhook Payloads
-**`onCallAgentError`** β€” Sub-agent failed. Dispatched on **parent** operation.
+`createWebhookPayloadBuilder()` selects `eventFields`, adds `hookId`/`hookType`, then merges `webhook.body`. The body determines the final value of overlapping fields. Tool-result payloads use `redactResultForEvents()` to trim raw skill Work data; Work registration retains the full in-process result. `finalState` is available to local handlers; serialized payloads carry the event's data fields.
-```ts
-// event: CallAgentErrorHookEvent
-{
- (operationId, agentId, error);
-}
-```
+When email is selected, the builder resolves `userEmail` from the final effective `userId`, replacing supplied email values. Email-only projections use the event ID. An explicit invalid ID, missing email or lookup error leaves email omitted.
-Note: CallAgent hooks require `parentOperationId` in `ExecSubAgentTaskParams`.
+Email queries share a per-dispatcher cache of up to 1,000 users for five minutes. Query timeouts belong to the database layer. The builder's optional fourth `{ signal }` argument lets a waiter cancel independently; cancellation returns `undefined` so the caller can stop delivery. Fetch and QStash use the enriched payload.
-## Design Notes
+## Delivery Errors
-- **Fire-and-forget**: All handlers return `Promise<void>`. Errors are non-fatal.
-- **Exception**: `beforeToolCall` supports mock via `event.mock()` β€” uses `dispatchBeforeToolCall()` which returns the mock result.
-- **Sequential**: Same-type hooks run in registration order.
-- **Local only**: `beforeToolCall` mock only works in local mode (in-memory hooks). Webhook mode does not support mocking.
-- **Scoped per operation**: Auto-cleaned via `hookDispatcher.unregister()` on completion.
-- **Sandbox/MCP**: No separate hooks β€” they go through `executeTool`, so `beforeToolCall`/`afterToolCall` cover them. Use `event.identifier` to filter.
+Dispatch awaits each handler or webhook. Ordinary errors are logged and dispatch continues. Webhooks with `fallback: 'none'` accumulate a `CriticalHookDeliveryError`, which is thrown after sibling hooks have run. QStash delivery defaults to a fetch fallback; use `fallback: 'none'` for QStash-signed endpoints.
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 17fdd86049b..3d27e664525 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -8,6 +8,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 * as ClientToolDispatch from '../dispatchClientTool';
import { createRuntimeExecutors, type RuntimeExecutorContext } from '../RuntimeExecutors';
import type { StreamEvent } from '../StreamEventManager';
import { VISIBLE_OUTPUT_END_PUBLISHED_STEP_INDEX_METADATA_KEY } from '../visibleOutputEnd';
@@ -6021,6 +6022,256 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
});
describe('call_tool hooks', () => {
+ it.each([false, true])(
+ 'keeps runtime owner identity in shared-session tool hooks (throws: %s)',
+ async (throws) => {
+ const mockDispatcher = {
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
+ };
+ if (throws)
+ mockToolExecutionService.executeTool.mockRejectedValue(new Error('Tool failed'));
+ const state = createToolState({
+ principal: {
+ actor: {
+ shareVisitor: {
+ agentId: 'shared-agent',
+ shareId: 'share-1',
+ visitorUserId: 'visitor-1',
+ },
+ },
+ },
+ });
+
+ await createRuntimeExecutors({ ...ctx, hookDispatcher: mockDispatcher as any })
+ .call_tool!(createToolInstruction(), state);
+
+ expect(mockToolExecutionService.executeTool).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ userId: 'user-123' }),
+ );
+ expect(ctx.userId).toBe('user-123');
+ const identity = expect.objectContaining({ userId: 'user-123' });
+ expect(mockDispatcher.dispatchBeforeToolCall).toHaveBeenCalledWith('op-123', identity);
+ expect(mockDispatcher.dispatch).toHaveBeenCalledWith(
+ 'op-123',
+ 'beforeToolCall',
+ identity,
+ undefined,
+ );
+ expect(mockDispatcher.dispatch).toHaveBeenCalledWith(
+ 'op-123',
+ throws ? 'onToolCallError' : 'afterToolCall',
+ identity,
+ undefined,
+ );
+ },
+ );
+
+ it('should preserve native identity and structured results across tool notifications', async () => {
+ const mockDispatcher = {
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
+ };
+ const toolResult = {
+ content: 'device output',
+ deviceExecutionTime: 17,
+ executionTime: 23,
+ state: { files: ['output.txt'], nested: { count: 1 } },
+ success: true,
+ };
+ mockToolExecutionService.executeTool.mockResolvedValue(toolResult);
+ const state = createToolState({
+ binding: { device: { id: 'device-1' } },
+ origin: {
+ agentId: 'child-agent',
+ documentId: 'document-1',
+ groupId: 'group-1',
+ lineage: { isSubAgent: true, parentOperationId: 'parent-operation' },
+ sessionId: 'session-1',
+ sourceMessageId: 'user-message',
+ taskId: 'task-1',
+ threadId: 'thread-1',
+ topicId: 'child-topic',
+ workspaceId: 'workspace-1',
+ },
+ plan: { execution: { deviceId: 'device-1', kind: 'device', target: 'device' } },
+ });
+ const instruction = createToolInstruction();
+ instruction.payload.toolCalling = { ...instruction.payload.toolCalling, source: 'mcp' };
+
+ await createRuntimeExecutors({ ...ctx, hookDispatcher: mockDispatcher as any }).call_tool!(
+ instruction,
+ state,
+ );
+
+ const identity = {
+ activeDeviceId: 'device-1',
+ userId: 'user-123',
+ agentId: 'child-agent',
+ apiName: 'search_tweets',
+ args: { query: 'test' },
+ assistantMessageId: 'parent-msg',
+ documentId: 'document-1',
+ executionTarget: 'device',
+ executor: 'server',
+ groupId: 'group-1',
+ identifier: 'twitter',
+ operationId: 'op-123',
+ parentOperationId: 'parent-operation',
+ sessionId: 'session-1',
+ sourceMessageId: 'user-message',
+ taskId: 'task-1',
+ threadId: 'thread-1',
+ toolCallId: 'tc-1',
+ toolSource: 'mcp',
+ topicId: 'child-topic',
+ workspaceId: 'workspace-1',
+ };
+ expect(mockDispatcher.dispatchBeforeToolCall).toHaveBeenCalledWith(
+ 'op-123',
+ expect.objectContaining(identity),
+ );
+ expect(mockDispatcher.dispatch).toHaveBeenCalledWith(
+ 'op-123',
+ 'beforeToolCall',
+ expect.objectContaining(identity),
+ undefined,
+ );
+ expect(mockDispatcher.dispatch).toHaveBeenCalledWith(
+ 'op-123',
+ 'afterToolCall',
+ expect.objectContaining({
+ ...identity,
+ mocked: false,
+ result: toolResult,
+ }),
+ undefined,
+ );
+ const after = mockDispatcher.dispatch.mock.calls.find(
+ ([, type]) => type === 'afterToolCall',
+ )![2];
+ for (const key of ['content', 'success', 'executionTimeMs']) {
+ expect(after).not.toHaveProperty(key);
+ }
+ });
+
+ it('should report structured blocked results as unsuccessful notifications, not exceptions', async () => {
+ const mockDispatcher = {
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
+ };
+ const toolResult = {
+ content: 'Tool unavailable in this scope',
+ executionTime: 0,
+ state: { reason: 'tool_not_allowed', type: 'blocked' },
+ success: false,
+ };
+ mockToolExecutionService.executeTool.mockResolvedValue(toolResult);
+
+ await createRuntimeExecutors({ ...ctx, hookDispatcher: mockDispatcher as any }).call_tool!(
+ createToolInstruction(),
+ createToolState(),
+ );
+
+ expect(mockDispatcher.dispatch).toHaveBeenCalledWith(
+ 'op-123',
+ 'afterToolCall',
+ expect.objectContaining({
+ mocked: false,
+ result: toolResult,
+ toolCallId: 'tc-1',
+ }),
+ undefined,
+ );
+ expect(
+ mockDispatcher.dispatch.mock.calls.some(([, type]) => type === 'onToolCallError'),
+ ).toBe(false);
+ const before = mockDispatcher.dispatchBeforeToolCall.mock.calls[0][1];
+ expect(before.parentOperationId).toBeUndefined();
+ expect(before.rootOperationId).toBeUndefined();
+ });
+
+ it('should correlate repeated tool names in a batch by native call ids', async () => {
+ const mockDispatcher = {
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
+ };
+ const tool = createToolInstruction().payload.toolCalling;
+ await createRuntimeExecutors({ ...ctx, hookDispatcher: mockDispatcher as any })
+ .call_tools_batch!(
+ {
+ payload: {
+ parentMessageId: 'batch-assistant',
+ toolsCalling: [tool, { ...tool, arguments: '{"query":"second"}', id: 'tc-2' }],
+ },
+ type: 'call_tools_batch',
+ },
+ createToolState(),
+ );
+
+ const afterEvents = mockDispatcher.dispatch.mock.calls
+ .filter(([, type]) => type === 'afterToolCall')
+ .map(([, , event]) => event);
+ expect(afterEvents).toHaveLength(2);
+ expect(afterEvents).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ args: { query: 'test' },
+ assistantMessageId: 'batch-assistant',
+ toolCallId: 'tc-1',
+ }),
+ expect.objectContaining({
+ args: { query: 'second' },
+ assistantMessageId: 'batch-assistant',
+ toolCallId: 'tc-2',
+ }),
+ ]),
+ );
+ });
+
+ it('should retain client routing and structured client results in notifications', async () => {
+ const mockDispatcher = {
+ dispatch: vi.fn().mockResolvedValue(undefined),
+ dispatchBeforeToolCall: vi.fn().mockResolvedValue(null),
+ };
+ const result = {
+ content: 'client result',
+ executionTime: 11,
+ state: { path: 'client.txt' },
+ success: true,
+ };
+ const dispatchClient = vi
+ .spyOn(ClientToolDispatch, 'dispatchClientTool')
+ .mockResolvedValue(result);
+ const instruction = createToolInstruction();
+ instruction.payload.toolCalling = {
+ ...instruction.payload.toolCalling,
+ executor: 'client',
+ source: 'mcp',
+ };
+
+ await createRuntimeExecutors({
+ ...ctx,
+ hookDispatcher: mockDispatcher as any,
+ streamManager: { ...ctx.streamManager, sendToolExecute: vi.fn() },
+ }).call_tool!(instruction, createToolState());
+
+ expect(dispatchClient).toHaveBeenCalledOnce();
+ expect(mockToolExecutionService.executeTool).not.toHaveBeenCalled();
+ expect(mockDispatcher.dispatch).toHaveBeenCalledWith(
+ 'op-123',
+ 'afterToolCall',
+ expect.objectContaining({
+ executor: 'client',
+ result,
+ toolCallId: 'tc-1',
+ toolSource: 'mcp',
+ }),
+ undefined,
+ );
+ });
+
it('should dispatch beforeToolCall and afterToolCall hooks', async () => {
const mockDispatcher = {
dispatch: vi.fn().mockResolvedValue(undefined),
@@ -6049,7 +6300,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
apiName: 'search_tweets',
identifier: 'twitter',
mocked: false,
- success: true,
+ result: expect.objectContaining({ success: true }),
}),
undefined,
);
@@ -6141,7 +6392,10 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
expect(mockDispatcher.dispatch).toHaveBeenCalledWith(
'op-123',
'afterToolCall',
- expect.objectContaining({ mocked: true, success: true }),
+ expect.objectContaining({
+ mocked: true,
+ result: expect.objectContaining({ success: true }),
+ }),
undefined,
);
@@ -6175,7 +6429,16 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
expect(mockDispatcher.dispatch).toHaveBeenCalledWith(
'op-123',
'afterToolCall',
- expect.objectContaining({ mocked: true, success: false }),
+ expect.objectContaining({
+ mocked: true,
+ result: {
+ content: 'fixture error',
+ error: 'fixture error',
+ executionTime: 0,
+ success: false,
+ },
+ toolCallId: 'tc-1',
+ }),
undefined,
);
});
@@ -6198,8 +6461,11 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
'onToolCallError',
expect.objectContaining({
apiName: 'search_tweets',
+ args: { query: 'test' },
error: 'Connection refused',
identifier: 'twitter',
+ assistantMessageId: 'parent-msg',
+ toolCallId: 'tc-1',
}),
undefined,
);
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index a76fd7b5dfe..775d4fa80eb 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -1,5 +1,7 @@
import type {
+ AfterToolCallHookEvent,
AgentState,
+ ToolCallErrorHookEvent,
ToolRunContext,
ToolRunExecution,
ToolTransport,
@@ -41,6 +43,7 @@ import {
import { resolveRunActiveDeviceId } from '../executors/resolveRunActiveDeviceId';
import { resolveRunProjectSkills } from '../executors/resolveRunProjectSkills';
import { resolveToolTimeoutMs } from '../resolveToolTimeout';
+import { buildToolCallHookContext } from './toolCallHookContext';
export class ServerToolTransport implements ToolTransport {
maxRetries = TOOL_MAX_RETRIES;
@@ -88,7 +91,7 @@ export class ServerToolTransport implements ToolTransport {
error: unknown,
context: ToolRunContext,
): Promise<void> {
- const { hookDispatcher, operationId, stepIndex, userId } = this.ctx;
+ const { hookDispatcher, operationId, stepIndex } = this.ctx;
if (hookDispatcher) {
hookDispatcher
@@ -96,15 +99,9 @@ export class ServerToolTransport implements ToolTransport {
operationId,
'onToolCallError',
{
- apiName: chatToolPayload.apiName,
- args: context.parsedArgs,
- callIndex: context.callIndex,
+ ...buildToolCallHookContext(chatToolPayload, context, this.ctx),
error: error instanceof Error ? error.message : String(error),
- identifier: chatToolPayload.identifier,
- operationId,
- stepIndex,
- userId,
- },
+ } satisfies ToolCallErrorHookEvent,
context.state.host?.hooks,
)
.catch(() => {});
@@ -367,33 +364,15 @@ export class ServerToolTransport implements ToolTransport {
}
private async dispatchBeforeToolCall(chatToolPayload: ChatToolPayload, context: ToolRunContext) {
- const { hookDispatcher, operationId, stepIndex, userId } = this.ctx;
+ const { hookDispatcher, operationId } = this.ctx;
if (!hookDispatcher) return null;
+ const event = buildToolCallHookContext(chatToolPayload, context, this.ctx);
hookDispatcher
- .dispatch(
- operationId,
- 'beforeToolCall',
- {
- apiName: chatToolPayload.apiName,
- args: context.parsedArgs,
- callIndex: context.callIndex,
- identifier: chatToolPayload.identifier,
- operationId,
- stepIndex,
- userId,
- },
- context.state.host?.hooks,
- )
+ .dispatch(operationId, 'beforeToolCall', event, context.state.host?.hooks)
.catch(() => {});
- return hookDispatcher.dispatchBeforeToolCall(operationId, {
- apiName: chatToolPayload.apiName,
- args: context.parsedArgs,
- callIndex: context.callIndex,
- identifier: chatToolPayload.identifier,
- stepIndex,
- });
+ return hookDispatcher.dispatchBeforeToolCall(operationId, event);
}
private async dispatchAfterToolCall(
@@ -402,7 +381,7 @@ export class ServerToolTransport implements ToolTransport {
result: ToolRunExecution['result'],
mocked: boolean,
) {
- const { hookDispatcher, operationId, stepIndex, userId } = this.ctx;
+ const { hookDispatcher, operationId } = this.ctx;
if (!hookDispatcher) return;
// A tool that outlives an abort still finishes in the background β€” we cannot
@@ -418,18 +397,10 @@ export class ServerToolTransport implements ToolTransport {
operationId,
'afterToolCall',
{
- apiName: chatToolPayload.apiName,
- args: context.parsedArgs,
- callIndex: context.callIndex,
- content: result.content,
- executionTimeMs: result.executionTime ?? 0,
- identifier: chatToolPayload.identifier,
+ ...buildToolCallHookContext(chatToolPayload, context, this.ctx),
mocked,
- operationId,
- stepIndex,
- success: result.success,
- userId,
- },
+ result,
+ } satisfies AfterToolCallHookEvent,
context.state.host?.hooks,
)
.catch(() => {});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.test.ts b/apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.test.ts
new file mode 100644
index 00000000000..326e24f7736
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.test.ts
@@ -0,0 +1,160 @@
+import type {
+ AfterToolCallHookEvent,
+ BeforeToolCallObservationEvent,
+ ToolCallErrorHookEvent,
+ ToolCallHookEvent,
+ ToolRunContext,
+ ToolRunResult,
+} from '@lobechat/agent-runtime';
+import { AgentRuntime } from '@lobechat/agent-runtime';
+import type { ChatToolPayload, ToolExecutor } from '@lobechat/types';
+import { describe, expect, expectTypeOf, it, vi } from 'vitest';
+
+import { buildToolCallHookContext } from './toolCallHookContext';
+
+const call: ChatToolPayload = {
+ apiName: 'search',
+ arguments: '{"query":"original"}',
+ executor: 'client',
+ id: 'native-call-id',
+ identifier: 'search-tool',
+ source: 'mcp',
+ type: 'default',
+};
+
+const createContext = (): ToolRunContext => ({
+ callIndex: 7,
+ effectiveManifestMap: {},
+ mode: 'single',
+ operationId: 'op-1',
+ parentMessageId: 'assistant-1',
+ parsedArgs: { query: 'effective' },
+ state: AgentRuntime.createInitialState({ operationId: 'op-1', status: 'running', stepCount: 1 }),
+ stepIndex: 1,
+ toolMessageId: 'resumed-tool-message',
+ toolName: 'search-tool/search',
+});
+
+const runtime = {
+ operationId: 'op-1',
+ stepIndex: 1,
+ streamManager: { sendToolExecute: vi.fn() },
+ topicId: 'runtime-topic',
+ userId: 'user-1',
+ workspaceId: 'runtime-workspace',
+};
+
+describe('buildToolCallHookContext', () => {
+ it.each([
+ {
+ originUser: 'origin-owner',
+ runtimeUser: undefined,
+ visitor: 'visitor-1',
+ user: 'origin-owner',
+ },
+ {
+ originUser: 'origin-owner',
+ runtimeUser: 'runtime-owner',
+ visitor: 'visitor-1',
+ user: 'runtime-owner',
+ },
+ {
+ originUser: 'origin-owner',
+ runtimeUser: 'runtime-owner',
+ visitor: undefined,
+ user: 'runtime-owner',
+ },
+ {
+ originUser: 'origin-owner',
+ runtimeUser: undefined,
+ visitor: undefined,
+ user: 'origin-owner',
+ },
+ {
+ originUser: undefined,
+ runtimeUser: undefined,
+ visitor: 'visitor-1',
+ user: undefined,
+ },
+ {
+ originUser: undefined,
+ runtimeUser: undefined,
+ visitor: undefined,
+ user: undefined,
+ },
+ ])(
+ 'resolves hook userId to the runtime owner $user',
+ ({ originUser, runtimeUser, visitor, user }) => {
+ const context = createContext();
+ context.state.origin = { userId: originUser };
+ if (visitor) {
+ context.state.principal = {
+ actor: {
+ shareVisitor: { agentId: 'shared-agent', shareId: 'share-1', visitorUserId: visitor },
+ },
+ };
+ }
+
+ const event = buildToolCallHookContext(call, context, { ...runtime, userId: runtimeUser });
+
+ expect(event.userId).toBe(user);
+ expect(context.state.origin?.userId).toBe(originUser);
+ },
+ );
+
+ it('reports invocation args and native call and message identifiers', () => {
+ const context = createContext();
+ const event = buildToolCallHookContext(call, context, runtime);
+
+ expect(event.args).toEqual({ query: 'effective' });
+ expect(event.toolCallId).toBe('native-call-id');
+ expect(event.callIndex).toBe(7);
+ expect(event.assistantMessageId).toBe('assistant-1');
+ expect(event.toolMessageId).toBe('resumed-tool-message');
+ });
+
+ it('reports the client route only when the server can forward to the client', () => {
+ expect(buildToolCallHookContext(call, createContext(), runtime)).toMatchObject({
+ executor: 'client',
+ toolSource: 'mcp',
+ });
+ expect(
+ buildToolCallHookContext(call, createContext(), { ...runtime, streamManager: {} }),
+ ).toMatchObject({ executor: 'server', toolSource: 'mcp' });
+ });
+
+ it('does not infer a parent from progress anchors or a device from a stale binding', () => {
+ const context = createContext();
+ context.state.origin = {
+ lineage: { progressAnchor: { parentOperationId: 'progress-only', toolMessageId: 'anchor' } },
+ };
+ context.state.binding = { device: { id: 'stale-device' } };
+ context.state.plan = { execution: { kind: 'sandbox', target: 'sandbox' } };
+ const event = buildToolCallHookContext(call, context, runtime);
+
+ expect(event.parentOperationId).toBeUndefined();
+ expect(event.activeDeviceId).toBeUndefined();
+ expect(event.executionTarget).toBe('sandbox');
+ expect(event.topicId).toBe('runtime-topic');
+ expect(event.workspaceId).toBe('runtime-workspace');
+ });
+
+ it('shares additive correlation types and keeps blocked results structured', () => {
+ const event = buildToolCallHookContext(call, createContext(), runtime);
+ expectTypeOf(event).toExtend<BeforeToolCallObservationEvent>();
+ expectTypeOf(event.toolCallId).toEqualTypeOf<string>();
+ expectTypeOf(event.assistantMessageId).toEqualTypeOf<string>();
+ expectTypeOf(event.executor).toEqualTypeOf<ToolExecutor>();
+ expectTypeOf(event.parentOperationId).toEqualTypeOf<string | undefined>();
+ expectTypeOf({ ...event, mock: () => true }).toExtend<ToolCallHookEvent>();
+ expectTypeOf({ ...event, error: 'failure' }).toExtend<ToolCallErrorHookEvent>();
+
+ const after: AfterToolCallHookEvent = {
+ ...event,
+ mocked: false,
+ result: { content: 'blocked', state: { type: 'blocked' }, success: false },
+ };
+ expectTypeOf(after.result).toEqualTypeOf<ToolRunResult>();
+ expect(after.result.state?.type).toBe('blocked');
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.ts b/apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.ts
new file mode 100644
index 00000000000..209c27811a5
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/toolCallHookContext.ts
@@ -0,0 +1,47 @@
+import type { ToolCallHookContext, ToolRunContext } from '@lobechat/agent-runtime';
+import type { ChatToolPayload } from '@lobechat/types';
+
+import type { RuntimeExecutorContext } from '../context';
+import { resolveRunActiveDeviceId } from '../executors/resolveRunActiveDeviceId';
+
+/** Shared input for observation, local mock, completion and error notifications. */
+export const buildToolCallHookContext = (
+ call: ChatToolPayload,
+ context: ToolRunContext,
+ runtime: Pick<
+ RuntimeExecutorContext,
+ 'operationId' | 'stepIndex' | 'topicId' | 'userId' | 'workspaceId'
+ > & { streamManager: Pick<RuntimeExecutorContext['streamManager'], 'sendToolExecute'> },
+): ToolCallHookContext => {
+ const { origin } = context.state;
+
+ return {
+ activeDeviceId: resolveRunActiveDeviceId(context.state),
+ agentId: origin?.agentId ?? context.agentId,
+ apiName: call.apiName,
+ args: context.parsedArgs,
+ assistantMessageId: context.parentMessageId,
+ callIndex: context.callIndex,
+ documentId: origin?.documentId,
+ executionTarget: context.state.plan?.execution?.target,
+ executor:
+ call.executor === 'client' && typeof runtime.streamManager.sendToolExecute === 'function'
+ ? 'client'
+ : 'server',
+ groupId: origin?.groupId ?? context.groupId,
+ identifier: call.identifier,
+ operationId: runtime.operationId,
+ parentOperationId: origin?.lineage?.parentOperationId,
+ sessionId: origin?.sessionId,
+ sourceMessageId: origin?.sourceMessageId ?? context.messageId,
+ stepIndex: runtime.stepIndex,
+ taskId: origin?.taskId,
+ threadId: origin?.threadId ?? context.threadId,
+ toolCallId: call.id,
+ toolMessageId: context.toolMessageId,
+ toolSource: context.toolSource ?? call.source,
+ topicId: origin?.topicId ?? context.topicId ?? runtime.topicId,
+ userId: runtime.userId ?? origin?.userId,
+ workspaceId: origin?.workspaceId ?? context.workspaceId ?? runtime.workspaceId,
+ };
+};
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index 823922e9a18..45e2bf18129 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -15,6 +15,7 @@ import type {
SerializedHook,
ToolCallHookEvent,
} from './types';
+import { createWebhookPayloadBuilder } from './webhookPayload';
const log = debug('lobe-server:hook-dispatcher');
@@ -90,26 +91,6 @@ async function fetchDeliver(url: string, payload: Record<string, unknown>): Prom
log('Webhook delivered via fetch: %s (status: %d)', url, res.status);
}
-function buildWebhookPayload(
- event: AnyHookEvent,
- eventFields?: (keyof AgentHookEvent)[],
-): Record<string, unknown> {
- if (eventFields) {
- const payload: Record<string, unknown> = {};
- for (const field of eventFields) {
- if (field === 'finalState') continue;
- if (field in event) payload[field] = event[field as keyof AnyHookEvent];
- }
- return payload;
- }
-
- const payload = { ...event };
- if ('finalState' in payload) {
- delete (payload as { finalState?: unknown }).finalState;
- }
- return payload;
-}
-
/**
* HookDispatcher β€” central hub for registering and dispatching agent lifecycle hooks
*
@@ -118,6 +99,8 @@ function buildWebhookPayload(
* delivered via HTTP POST or QStash
*/
export class HookDispatcher {
+ private readonly buildWebhookPayload = createWebhookPayloadBuilder();
+
/**
* In-memory hook store (local mode)
* Maps operationId β†’ AgentHook[]
@@ -174,13 +157,11 @@ export class HookDispatcher {
hook.id,
hook.webhook.url,
);
- const webhookPayload = buildWebhookPayload(event, hook.webhook.eventFields);
- await deliverWebhook(hook.webhook, {
- ...webhookPayload,
+ const webhookPayload = await this.buildWebhookPayload(event, hook.webhook, {
hookId: hook.id,
hookType: type,
- ...hook.webhook.body,
});
+ if (webhookPayload) await deliverWebhook(hook.webhook, webhookPayload);
} catch (error) {
if (hook.webhook.fallback === 'none') {
// No-fallback webhooks carry control flow (e.g. the sub-agent
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
index 6febd6ecf3d..d5e93e361cf 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
@@ -3,6 +3,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { deliverWebhook, HookDispatcher } from '../HookDispatcher';
import type { AgentHook, AgentHookEvent } from '../types';
+vi.mock('@/database/models/user', () => ({
+ UserModel: { getEmailsByIds: async () => [] },
+}));
+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));
+
// Mock isQueueAgentRuntimeEnabled to control local vs production mode
vi.mock('@/server/services/queue/impls', () => ({
isQueueAgentRuntimeEnabled: vi.fn(function () {
@@ -471,13 +476,16 @@ describe('HookDispatcher', () => {
await dispatcher.dispatch(operationId, 'onToolCallError', {
apiName: 'search_tweets',
args: { query: 'test' },
+ assistantMessageId: 'assistant-1',
callIndex: 1,
error: 'Network timeout',
+ executor: 'server',
identifier: 'twitter',
operationId,
stepIndex: 2,
+ toolCallId: 'native-call-1',
userId: 'user_test',
- } as any);
+ });
expect(handler).toHaveBeenCalledWith(
expect.objectContaining({
@@ -495,22 +503,23 @@ describe('HookDispatcher', () => {
await dispatcher.dispatch(operationId, 'afterToolCall', {
apiName: 'search_tweets',
args: { query: 'test' },
+ assistantMessageId: 'assistant-1',
callIndex: 1,
- content: '{"tweets":[]}',
- executionTimeMs: 150,
+ executor: 'server',
identifier: 'twitter',
mocked: false,
operationId,
+ result: { content: '{"tweets":[]}', executionTime: 150, success: true },
stepIndex: 1,
- success: true,
+ toolCallId: 'native-call-1',
userId: 'user_test',
- } as any);
+ });
expect(handler).toHaveBeenCalledWith(
expect.objectContaining({
apiName: 'search_tweets',
identifier: 'twitter',
- success: true,
+ result: expect.objectContaining({ success: true }),
}),
);
});
@@ -519,6 +528,9 @@ describe('HookDispatcher', () => {
describe('dispatchBeforeToolCall', () => {
it('should return null when no beforeToolCall hooks registered', async () => {
const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -540,6 +552,9 @@ describe('HookDispatcher', () => {
]);
const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: { query: 'test' },
callIndex: 1,
@@ -565,6 +580,9 @@ describe('HookDispatcher', () => {
]);
const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -580,6 +598,9 @@ describe('HookDispatcher', () => {
dispatcher.register(operationId, [{ handler, id: 'check-fields', type: 'beforeToolCall' }]);
await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'post_tweet',
args: { text: 'hello' },
callIndex: 3,
@@ -612,6 +633,9 @@ describe('HookDispatcher', () => {
]);
const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -634,6 +658,9 @@ describe('HookDispatcher', () => {
await expect(
dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -778,6 +805,9 @@ describe('HookDispatcher', () => {
]);
const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -806,6 +836,9 @@ describe('HookDispatcher', () => {
{ handler: secondHandler, id: 'must-not-run', type: 'beforeToolCall' },
]);
const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -833,6 +866,9 @@ describe('HookDispatcher', () => {
]);
const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -862,6 +898,9 @@ describe('HookDispatcher', () => {
// dispatchBeforeToolCall only runs in local mode
const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -895,6 +934,9 @@ describe('HookDispatcher', () => {
// beforeToolCall should not trigger afterStep or onComplete
await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -927,6 +969,9 @@ describe('HookDispatcher', () => {
]);
const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -1035,6 +1080,9 @@ describe('HookDispatcher', () => {
// Local mode: mock works
const localResult = await dispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -1052,6 +1100,9 @@ describe('HookDispatcher', () => {
// This is by design β€” mock is local-only.
const otherDispatcher = new HookDispatcher();
const remoteResult = await otherDispatcher.dispatchBeforeToolCall(operationId, {
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
apiName: 'search',
args: {},
callIndex: 1,
@@ -1070,7 +1121,7 @@ describe('HookDispatcher', () => {
handler: vi.fn(),
id: 'tool-webhook',
type: 'afterToolCall',
- webhook: { url: 'https://example.com/afterToolCall' },
+ webhook: { url: 'https://example.com/afterToolCall', eventFields: ['result', 'mocked'] },
},
]);
@@ -1083,13 +1134,14 @@ describe('HookDispatcher', () => {
apiName: 'search',
args: {},
callIndex: 1,
- content: 'result',
- executionTimeMs: 100,
+ assistantMessageId: 'assistant-1',
+ executor: 'server',
+ toolCallId: 'native-call-1',
+ result: { content: 'result', executionTime: 100, success: true },
identifier: 'twitter',
mocked: false,
operationId,
stepIndex: 0,
- success: true,
userId: 'user_test',
},
serialized,
@@ -1097,7 +1149,15 @@ describe('HookDispatcher', () => {
expect(global.fetch).toHaveBeenCalledWith(
'https://example.com/afterToolCall',
- expect.objectContaining({ method: 'POST' }),
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({
+ result: { content: 'result', executionTime: 100, success: true },
+ mocked: false,
+ hookId: 'tool-webhook',
+ hookType: 'afterToolCall',
+ }),
+ }),
);
});
});
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/webhookUserEmail.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/webhookUserEmail.test.ts
new file mode 100644
index 00000000000..b23ca675c10
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/webhookUserEmail.test.ts
@@ -0,0 +1,490 @@
+import { createServer } from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+import type { ToolRunResult } from '@lobechat/agent-runtime';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { HookDispatcher, hookDispatcher } from '../HookDispatcher';
+import type {
+ AfterToolCallHookEvent,
+ AgentHookEvent,
+ AgentHookType,
+ SerializedHook,
+} from '../types';
+import { createWebhookPayloadBuilder } from '../webhookPayload';
+
+const { getEmailsByIds, publishJSON } = vi.hoisted(() => ({
+ getEmailsByIds: vi.fn(),
+ publishJSON: vi.fn(),
+}));
+vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds } }));
+vi.mock('@/database/server', () => ({
+ getServerDB: async () => ({}),
+}));
+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: () => true }));
+vi.mock('@upstash/qstash', () => ({
+ Client: class {
+ publishJSON = publishJSON;
+ },
+}));
+
+const hookTypes: AgentHookType[] = [
+ 'beforeStep',
+ 'afterStep',
+ 'onComplete',
+ 'onError',
+ 'beforeToolCall',
+ 'afterToolCall',
+ 'onToolCallError',
+ 'beforeCompact',
+ 'afterCompact',
+ 'onCompactError',
+ 'beforeCallAgent',
+ 'afterCallAgent',
+ 'onCallAgentError',
+ 'beforeHumanIntervention',
+ 'afterHumanIntervention',
+ 'onStopByHumanIntervention',
+];
+const event: AgentHookEvent = { agentId: 'agent', operationId: 'run', userId: 'visitor' };
+const received: Record<string, unknown>[] = [];
+const server = createServer(async (req, res) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
+ received.push(JSON.parse(Buffer.concat(chunks).toString()));
+ res.writeHead(200).end('{}');
+});
+let url: string;
+let dispatcher: HookDispatcher;
+
+beforeAll(async () => {
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/hook`;
+});
+afterAll(async () => {
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+});
+beforeEach(() => {
+ dispatcher = new HookDispatcher();
+ received.length = 0;
+ getEmailsByIds
+ .mockReset()
+ .mockImplementation(async (_db, ids: string[]) =>
+ ids.map((id) => ({ id, email: `${id}@example.test` })),
+ );
+ publishJSON.mockReset().mockResolvedValue({});
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+ vi.useRealTimers();
+});
+
+const send = (type: AgentHookType = 'afterToolCall', webhook = { url }, payload = event) =>
+ dispatcher.dispatch('run', type, payload, [{ id: 'notification', type, webhook }]);
+
+describe('webhook user email', () => {
+ it.each(hookTypes)('delivers the final user email for %s', async (type) => {
+ await send(type);
+ expect(received[0]).toMatchObject({
+ userId: 'visitor',
+ userEmail: '[email protected]',
+ hookType: type,
+ });
+ expect(event).not.toHaveProperty('userEmail');
+ });
+
+ it('uses the final body identity for its corresponding email', async () => {
+ await dispatcher.dispatch('run', 'onComplete', event, [
+ { id: 'external', type: 'onComplete', webhook: { url } },
+ {
+ id: 'internal',
+ type: 'onComplete',
+ webhook: { url, body: { userId: 'owner', userEmail: '[email protected]' } },
+ },
+ ]);
+ expect(received.map(({ userId, userEmail }) => ({ userId, userEmail }))).toEqual([
+ { userId: 'visitor', userEmail: '[email protected]' },
+ { userId: 'owner', userEmail: '[email protected]' },
+ ]);
+ expect(event.userId).toBe('visitor');
+ expect(getEmailsByIds).toHaveBeenCalledTimes(2);
+ expect(getEmailsByIds).toHaveBeenCalledWith(expect.anything(), ['owner']);
+ });
+
+ it.each([{ rows: [] }, { rows: [{ id: 'visitor', email: null }] }])(
+ 'omits an unavailable email without an owner fallback',
+ async ({ rows }) => {
+ getEmailsByIds.mockResolvedValue(rows);
+ await send();
+ expect(received[0]).toHaveProperty('userId', 'visitor');
+ expect(received[0]).not.toHaveProperty('userEmail');
+ },
+ );
+
+ it('continues delivery when the lookup fails', async () => {
+ getEmailsByIds.mockRejectedValue(new Error('database unavailable'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ await send();
+ expect(received[0]).toHaveProperty('userId', 'visitor');
+ expect(received[0]).not.toHaveProperty('userEmail');
+ });
+
+ it('does not look up email when eventFields excludes it', async () => {
+ await dispatcher.dispatch('run', 'onComplete', event, [
+ {
+ id: 'projected',
+ type: 'onComplete',
+ webhook: { url, eventFields: ['userId'] },
+ },
+ ]);
+ expect(received[0]).not.toHaveProperty('userEmail');
+ expect(getEmailsByIds).not.toHaveBeenCalled();
+ });
+
+ it('allows selecting email without including the id', async () => {
+ await dispatcher.dispatch('run', 'onComplete', event, [
+ {
+ id: 'projected',
+ type: 'onComplete',
+ webhook: { url, eventFields: ['userEmail'] },
+ },
+ ]);
+ expect(received[0]).toHaveProperty('userEmail', '[email protected]');
+ expect(received[0]).not.toHaveProperty('userId');
+ });
+
+ it('shares a lookup across concurrent events and refreshes after expiry', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(1000);
+ await Promise.all([send(), send('onComplete')]);
+ expect(getEmailsByIds).toHaveBeenCalledTimes(1);
+ now.mockReturnValue(1000 + 5 * 60 * 1000);
+ getEmailsByIds.mockResolvedValue([{ id: 'visitor', email: '[email protected]' }]);
+ await send();
+ expect(getEmailsByIds).toHaveBeenCalledTimes(2);
+ expect(received[2]).toHaveProperty('userEmail', '[email protected]');
+ });
+
+ it.each([undefined, null, '', 42])(
+ 'does not substitute the event identity for an invalid final body id %s',
+ async (userId) => {
+ await dispatcher.dispatch('run', 'onComplete', event, [
+ {
+ id: 'invalid-id',
+ type: 'onComplete',
+ webhook: { url, body: { userId, userEmail: '[email protected]' } },
+ },
+ ]);
+ expect(received[0]).not.toHaveProperty('userEmail');
+ expect(getEmailsByIds).not.toHaveBeenCalled();
+ },
+ );
+
+ it('drops supplied email when no authoritative email is available', async () => {
+ getEmailsByIds.mockResolvedValue([]);
+ await dispatcher.dispatch(
+ 'run',
+ 'onComplete',
+ Object.assign({}, event, { userEmail: '[email protected]' }),
+ [
+ {
+ id: 'spoof',
+ type: 'onComplete',
+ webhook: { url, body: { userEmail: '[email protected]' } },
+ },
+ ],
+ );
+ expect(received[0]).not.toHaveProperty('userEmail');
+ });
+
+ it('resolves identity again in a restored worker', async () => {
+ await send();
+ dispatcher = new HookDispatcher();
+ getEmailsByIds.mockResolvedValue([{ id: 'visitor', email: '[email protected]' }]);
+ await send();
+ expect(received[1]).toHaveProperty('userEmail', '[email protected]');
+ expect(getEmailsByIds).toHaveBeenCalledTimes(2);
+ });
+
+ it('bounds cached identities instead of retaining every user for the process lifetime', async () => {
+ const build = createWebhookPayloadBuilder();
+ const metadata = { hookId: 'hook', hookType: 'onComplete' as const };
+ await build(event, {}, metadata);
+ for (let index = 0; index < 1000; index++) {
+ await build({ ...event, userId: `user-${index}` }, {}, metadata);
+ }
+ await build(event, {}, metadata);
+ expect(getEmailsByIds).toHaveBeenCalledTimes(1002);
+ });
+
+ it('reuses the final body identity email when already cached', async () => {
+ await send('onComplete', { url }, { ...event, userId: 'owner' });
+ await dispatcher.dispatch('run', 'onComplete', event, [
+ {
+ id: 'untrusted',
+ type: 'onComplete',
+ webhook: { url, body: { userId: 'owner' } },
+ },
+ ]);
+ expect(received[0]).toHaveProperty('userEmail', '[email protected]');
+ expect(received[1]).toHaveProperty('userEmail', '[email protected]');
+ expect(getEmailsByIds).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancels a waiter without cancelling another shared lookup', async () => {
+ let complete!: (rows: { id: string; email: string }[]) => void;
+ getEmailsByIds.mockReturnValue(
+ new Promise((resolve) => {
+ complete = resolve;
+ }),
+ );
+ const build = createWebhookPayloadBuilder();
+ const controller = new AbortController();
+ const metadata = { hookId: 'control', hookType: 'beforeToolCall' as const };
+ const cancelled = build(event, {}, metadata, { signal: controller.signal });
+ const sibling = build(event, {}, metadata);
+ controller.abort();
+ expect(await cancelled).toBeUndefined();
+ complete([{ id: 'visitor', email: '[email protected]' }]);
+ expect(await sibling).toHaveProperty('userEmail', '[email protected]');
+ expect(getEmailsByIds).toHaveBeenCalledTimes(1);
+ expect(received).toHaveLength(0);
+ });
+
+ it('does not start a lookup for an already aborted request', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ expect(
+ await createWebhookPayloadBuilder()(
+ event,
+ {},
+ { hookId: 'control', hookType: 'beforeToolCall' },
+ { signal: controller.signal },
+ ),
+ ).toBeUndefined();
+ expect(getEmailsByIds).not.toHaveBeenCalled();
+ });
+
+ it('preserves control-specific input without requiring a notification event shape', async () => {
+ const args = { query: 'effective' };
+ const originalArgs = { query: 'original' };
+ const payload = await createWebhookPayloadBuilder()(
+ { userId: 'visitor', args, originalArgs },
+ {},
+ { hookId: 'control', hookType: 'beforeToolCall' },
+ );
+ expect(payload).toMatchObject({ args, originalArgs, userEmail: '[email protected]' });
+ });
+
+ it.each(['consecutive', 'concurrent'] as const)(
+ 'keeps each final user email distinct on the global dispatcher across %s deliveries',
+ async (mode) => {
+ const deliver = (suffix: string) => {
+ const visitor = `${mode}-visitor-${suffix}`;
+ const owner = `${mode}-owner-${suffix}`;
+ return hookDispatcher.dispatch(
+ `run-${suffix}`,
+ 'onComplete',
+ {
+ ...event,
+ operationId: `run-${suffix}`,
+ userId: visitor,
+ },
+ [
+ { id: 'external', type: 'onComplete', webhook: { url } },
+ { id: 'internal', type: 'onComplete', webhook: { url, body: { userId: owner } } },
+ ],
+ );
+ };
+ if (mode === 'concurrent') {
+ let started!: () => void;
+ let release!: () => void;
+ const firstLookup = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const resume = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ getEmailsByIds.mockImplementation(async (_db, ids: string[]) => {
+ if (ids[0] === `${mode}-visitor-a`) {
+ started();
+ await resume;
+ }
+ return ids.map((id) => ({ id, email: `${id}@example.test` }));
+ });
+ const first = deliver('a');
+ await firstLookup;
+ try {
+ await deliver('b');
+ } finally {
+ release();
+ }
+ await first;
+ } else {
+ await deliver('a');
+ await deliver('b');
+ }
+ expect(received.map(({ userId, userEmail }) => ({ userId, userEmail }))).toEqual(
+ expect.arrayContaining(
+ ['visitor-a', 'owner-a', 'visitor-b', 'owner-b'].map((id) => ({
+ userId: `${mode}-${id}`,
+ userEmail: `${mode}-${id}@example.test`,
+ })),
+ ),
+ );
+ expect(received).toHaveLength(4);
+ expect(getEmailsByIds).toHaveBeenCalledTimes(4);
+ },
+ );
+
+ it('resolves the final body identity on a cold queue worker', async () => {
+ vi.stubEnv('QSTASH_TOKEN', 'test-token');
+ const hooks: SerializedHook[] = [
+ {
+ id: 'internal',
+ type: 'onComplete',
+ webhook: { url, delivery: 'qstash', fallback: 'none', body: { userId: 'owner' } },
+ },
+ ];
+ const serializedHooks = JSON.stringify(hooks);
+ const restoredHooks: SerializedHook[] = JSON.parse(serializedHooks);
+ await dispatcher.dispatch('run', 'onComplete', event, hooks);
+ dispatcher = new HookDispatcher();
+ await dispatcher.dispatch('run', 'onComplete', event, restoredHooks);
+ await dispatcher.dispatch('run', 'onComplete', event, restoredHooks);
+ await dispatcher.dispatch('run', 'onComplete', event, restoredHooks);
+ const bodies = publishJSON.mock.calls.map(([request]) => request.body);
+ expect(bodies.map(({ userEmail }) => userEmail)).toEqual([
+ ]);
+ expect(bodies.every((payload) => !('ownerUserId' in payload))).toBe(true);
+ expect(JSON.stringify(hooks)).toBe(serializedHooks);
+ expect(getEmailsByIds).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([{ rows: [] }, { rows: [{ id: 'owner', email: null }] }])(
+ 'omits unavailable owner email without substituting visitor email',
+ async ({ rows }) => {
+ getEmailsByIds.mockImplementation(async (_db, ids: string[]) =>
+ ids[0] === 'visitor' ? [{ id: 'visitor', email: '[email protected]' }] : rows,
+ );
+ await send();
+ await dispatcher.dispatch('run', 'onComplete', event, [
+ { id: 'internal', type: 'onComplete', webhook: { url, body: { userId: 'owner' } } },
+ ]);
+ expect(received[1]).toHaveProperty('userId', 'owner');
+ expect(received[1]).not.toHaveProperty('userEmail');
+ },
+ );
+
+ it('omits owner email on lookup failure and continues delivery', async () => {
+ getEmailsByIds.mockRejectedValue(new Error('lookup unavailable'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ await dispatcher.dispatch('run', 'onComplete', event, [
+ { id: 'internal', type: 'onComplete', webhook: { url, body: { userId: 'owner' } } },
+ ]);
+ expect(received[0]).not.toHaveProperty('userEmail');
+ });
+
+ it('includes the resolved email in QStash JSON', async () => {
+ vi.stubEnv('QSTASH_TOKEN', 'test-token');
+ const queued: SerializedHook = {
+ id: 'queued',
+ type: 'onComplete',
+ webhook: { url, delivery: 'qstash', fallback: 'none' },
+ };
+ await dispatcher.dispatch('run', 'onComplete', event, [queued]);
+ expect(publishJSON).toHaveBeenCalledWith(
+ expect.objectContaining({
+ body: expect.objectContaining({ userId: 'visitor', userEmail: '[email protected]' }),
+ }),
+ );
+ });
+});
+
+describe('webhook tool results', () => {
+ it.each([
+ { delivery: 'fetch', projected: false },
+ { delivery: 'fetch', projected: true },
+ { delivery: 'qstash', projected: false },
+ { delivery: 'qstash', projected: true },
+ ] as const)(
+ 'trims Work payloads for $delivery (projected: $projected)',
+ async ({ delivery, projected }) => {
+ vi.stubEnv('QSTASH_TOKEN', 'test-token');
+ const args = Object.freeze({ repository: 'example/project', number: 42 });
+ const data = Object.freeze({ body: 'raw tool output'.repeat(1000), number: 42 });
+ const intent = Object.freeze({
+ args,
+ data,
+ provider: 'github',
+ toolName: 'getIssue',
+ type: 'skill' as const,
+ });
+ const result: ToolRunResult = Object.freeze({
+ content: 'Issue summary',
+ executionTime: 100,
+ state: { archived: true },
+ success: true,
+ workRegistration: intent,
+ });
+ const after: AfterToolCallHookEvent = {
+ ...event,
+ apiName: 'getIssue',
+ args,
+ assistantMessageId: 'assistant-1',
+ callIndex: 0,
+ executor: 'server',
+ identifier: 'github',
+ mocked: false,
+ result,
+ stepIndex: 1,
+ toolCallId: 'call-1',
+ };
+ await dispatcher.dispatch('run', 'afterToolCall', after, [
+ {
+ id: 'tool-result',
+ type: 'afterToolCall',
+ webhook: { url, delivery, eventFields: projected ? ['result'] : undefined },
+ },
+ ]);
+ const payload = delivery === 'fetch' ? received[0] : publishJSON.mock.calls[0][0].body;
+ expect(payload.result).toEqual({
+ content: result.content,
+ executionTime: 100,
+ state: result.state,
+ success: true,
+ workRegistration: {
+ args: undefined,
+ data: null,
+ provider: 'github',
+ toolName: 'getIssue',
+ type: 'skill',
+ },
+ });
+ expect(after.result).toBe(result);
+ expect(result.workRegistration).toBe(intent);
+ expect(intent.args).toBe(args);
+ expect(intent.data).toBe(data);
+ },
+ );
+
+ it('preserves task Work metadata in the webhook result', async () => {
+ const result: ToolRunResult = {
+ content: 'Task created',
+ success: true,
+ workRegistration: { action: 'create', targets: [{ taskId: 'task-1' }], type: 'task' },
+ };
+ const payload = await createWebhookPayloadBuilder()(
+ { ...event, result },
+ { eventFields: ['result'] },
+ { hookId: 'task-result', hookType: 'afterToolCall' },
+ );
+ expect(payload?.result).toEqual(result);
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/hooks/index.ts b/apps/server/src/services/agentRuntime/hooks/index.ts
index 6ec43b8794a..8a1e83ce7e2 100644
--- a/apps/server/src/services/agentRuntime/hooks/index.ts
+++ b/apps/server/src/services/agentRuntime/hooks/index.ts
@@ -4,5 +4,6 @@ export type {
AgentHookEvent,
AgentHookType,
AgentHookWebhook,
+ AgentHookWebhookPayload,
SerializedHook,
} from './types';
diff --git a/apps/server/src/services/agentRuntime/hooks/types.ts b/apps/server/src/services/agentRuntime/hooks/types.ts
index 5d18ce991ba..54895233ca0 100644
--- a/apps/server/src/services/agentRuntime/hooks/types.ts
+++ b/apps/server/src/services/agentRuntime/hooks/types.ts
@@ -5,7 +5,7 @@
* Hook registration, webhook delivery, and serialization types are server-specific.
*/
-import type { AgentHookEvent, AgentHookType } from '@lobechat/agent-runtime';
+import type { AgentHookEvent, AgentHookType, AnyHookEvent } from '@lobechat/agent-runtime';
import type { AgentHookWebhookConfig, SerializedAgentHook } from '@lobechat/types';
export type {
@@ -29,18 +29,22 @@ export type {
// ── Server-side Hook Types ───────────────────────────────
+/** Outgoing projection, enriched with the final userId's available email. */
+export type AgentHookWebhookPayload = Partial<AnyHookEvent> &
+ Record<string, unknown> & { userEmail?: string };
+
/**
* Webhook delivery configuration for production mode.
*
* Runtime-precise refinement of the serialized wire shape
* ({@link AgentHookWebhookConfig} in `@lobechat/types`, used for persistence /
* zod validation): the shared `body` / `delivery` / `url` are inherited, while
- * `eventFields` is narrowed to `keyof AgentHookEvent` and the server-only
+ * `eventFields` is extended with tool-result and email fields and the server-only
* `fallback` policy is added.
*/
export interface AgentHookWebhook extends Omit<AgentHookWebhookConfig, 'eventFields'> {
/** Event fields to include in the webhook payload. Defaults to all serializable event fields. */
- eventFields?: (keyof AgentHookEvent)[];
+ eventFields?: (keyof AgentHookEvent | 'result' | 'mocked' | 'userEmail')[];
/**
* Behavior when QStash delivery fails (publish error or missing
diff --git a/apps/server/src/services/agentRuntime/hooks/webhookPayload.ts b/apps/server/src/services/agentRuntime/hooks/webhookPayload.ts
new file mode 100644
index 00000000000..4a63e327910
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/hooks/webhookPayload.ts
@@ -0,0 +1,96 @@
+import type { AgentHookType, ToolRunResult } from '@lobechat/agent-runtime';
+import { redactResultForEvents } from '@lobechat/agent-runtime';
+
+import { UserModel } from '@/database/models/user';
+import { getServerDB } from '@/database/server';
+
+import type { AgentHookWebhook, AgentHookWebhookPayload } from './types';
+
+const EMAIL_CACHE_TTL_MS = 5 * 60 * 1000;
+const EMAIL_CACHE_CAPACITY = 1000;
+
+/** Email is optional enrichment; database failures must not suppress the hook. */
+const readUserEmail = async (userId: string): Promise<string | undefined> => {
+ try {
+ const users = await UserModel.getEmailsByIds(await getServerDB(), [userId]);
+ return users.find((user) => user.id === userId)?.email ?? undefined;
+ } catch {
+ console.error('[HookDispatcher] Failed to resolve webhook user email');
+ return undefined;
+ }
+};
+
+/** Allow each waiter to cancel independently; query timeouts belong to the database. */
+const waitForEmail = (value: Promise<string | undefined>, signal?: AbortSignal) => {
+ if (signal?.aborted) return Promise.resolve(undefined);
+ if (!signal) return value;
+ return new Promise<string | undefined>((resolve) => {
+ const finish = (email?: string) => {
+ signal.removeEventListener('abort', onAbort);
+ resolve(email);
+ };
+ const onAbort = () => finish();
+ signal.addEventListener('abort', onAbort, { once: true });
+ void value.then(finish);
+ });
+};
+
+/**
+ * Per-dispatcher bounded cache, including pending lookups and missing emails.
+ * Workers resolve independently; this is a five-minute delivery-time cache,
+ * not a persisted run identity snapshot.
+ */
+const createCachedLookup = (read: (key: string) => Promise<string | undefined>) => {
+ const entries = new Map<string, { expiresAt: number; value: Promise<string | undefined> }>();
+ return (key: string) => {
+ const now = Date.now();
+ const cached = entries.get(key);
+ if (cached && cached.expiresAt > now) return cached.value;
+ entries.delete(key);
+ if (entries.size >= EMAIL_CACHE_CAPACITY) {
+ const oldest = entries.keys().next().value;
+ if (oldest !== undefined) entries.delete(oldest);
+ }
+ const value = read(key);
+ entries.set(key, { expiresAt: now + EMAIL_CACHE_TTL_MS, value });
+ return value;
+ };
+};
+
+export const createWebhookPayloadBuilder = () => {
+ const resolveEmail = createCachedLookup(readUserEmail);
+
+ return async <T extends { userId?: string }>(
+ event: T,
+ webhook: Pick<AgentHookWebhook, 'body' | 'eventFields'>,
+ metadata: { hookId: string; hookType: AgentHookType },
+ options: { signal?: AbortSignal } = {},
+ ): Promise<AgentHookWebhookPayload | undefined> => {
+ const { signal } = options;
+ if (signal?.aborted) return undefined;
+ const { body, eventFields } = webhook;
+ const selected: Record<string, unknown> = eventFields ? {} : { ...event };
+ if (eventFields) {
+ for (const field of eventFields) {
+ if (field in event) selected[field] = event[field as keyof T];
+ }
+ }
+ const payload: AgentHookWebhookPayload = { ...selected, ...metadata, ...body };
+ if (metadata.hookType === 'afterToolCall' && payload.result) {
+ payload.result = redactResultForEvents(payload.result as ToolRunResult);
+ }
+ delete payload.finalState;
+ delete payload.userEmail;
+ const userId = 'userId' in payload ? payload.userId : event.userId;
+ if (
+ (!eventFields || eventFields.includes('userEmail')) &&
+ typeof userId === 'string' &&
+ userId
+ ) {
+ const email = await waitForEmail(resolveEmail(userId), signal);
+ if (signal?.aborted) return undefined;
+ if (email !== undefined) payload.userEmail = email;
+ }
+ return payload;
+ };
+};
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index a0eee656c6b..ba14e4066ea 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -14,7 +14,11 @@ import type {
AgentState,
InstructionExecutor,
} from '../types';
-import { extractActivatedSkillsFromMessages, extractTodosFromMessages } from '../utils';
+import {
+ extractActivatedSkillsFromMessages,
+ extractTodosFromMessages,
+ redactResultForEvents,
+} from '../utils';
import { selectToolManifestMap, selectToolSourceMap } from '../utils/operationToolSet';
import { settleAbortedToolRows } from './abortedToolRows';
@@ -44,21 +48,6 @@ interface ToolResultEntry {
const nowIso = () => new Date().toISOString();
-/**
- * Skill work-registration intents carry the UNTRUNCATED tool payload
- * (`data`/`args`) solely for server-side Work registration, which reads it
- * off the in-process `executionResult` before anything leaves the executor.
- * Strip it from every copy that DOES leave: realtime `tool_end` stream events
- * (clients only read `workRegistration` as a presence flag, see
- * gatewayEventHandler) and the recorded step `tool_result` events
- * (AgentStateManager serializes those into Redis, where the raw payload would
- * bloat the capped event blob).
- */
-const redactResultForEvents = (result: ToolRunResult): ToolRunResult =>
- result.workRegistration?.type === 'skill'
- ? { ...result, workRegistration: { ...result.workRegistration, args: undefined, data: null } }
- : result;
-
const markPersistFatal = <T>(error: T): T => {
if (error && typeof error === 'object') persistFatalErrors.add(error);
return error;
diff --git a/packages/agent-runtime/src/types/hooks.ts b/packages/agent-runtime/src/types/hooks.ts
index 4a98f8c597c..c329445cd06 100644
--- a/packages/agent-runtime/src/types/hooks.ts
+++ b/packages/agent-runtime/src/types/hooks.ts
@@ -1,4 +1,9 @@
-import type { ChatErrorBudgetContext, ChatErrorHeterogeneousContext } from '@lobechat/types';
+import type {
+ ChatErrorBudgetContext,
+ ChatErrorHeterogeneousContext,
+ ExecutionPlan,
+ ToolExecutor,
+} from '@lobechat/types';
import type { ToolRunResult } from '../transport/tool';
@@ -19,7 +24,7 @@ export type AgentHookType =
| 'beforeStep' // Before each step executes
| 'beforeToolCall' // Before a tool call executes (supports mocking via event.mock())
| 'beforeCallAgent' // Before calling a sub-agent
- | 'afterCallAgent' // After sub-agent completes
+ | 'afterCallAgent' // After sub-agent creation/start returns, not when the child completes
| 'beforeCompact' // Before context compression starts
| 'beforeHumanIntervention' // Before agent pauses for human approval
| 'afterCompact' // After context compression completes
@@ -154,57 +159,65 @@ export interface AgentHookEvent {
}
/**
- * Event payload for beforeToolCall hooks.
- * Call `mock()` to skip real tool execution and return a fake result.
+ * Correlation and routing facts shared by tool lifecycle notifications.
+ * The server transport supplies the native toolCallId on every invocation.
*/
-export interface ToolCallHookEvent {
+export interface ToolCallHookContext {
+ /** Device selected by the run's execution plan and access policy, if any. */
+ activeDeviceId?: string;
+ agentId?: string;
apiName: string;
+ /** Effective arguments used for this invocation. */
args: Record<string, any>;
+ /** Assistant message owning the call, distinct from the source user message. */
+ assistantMessageId: string;
callIndex: number;
+ documentId?: string;
+ /** Effective run execution target, when the run has an execution plan. */
+ executionTarget?: ExecutionPlan['target'];
+ /** Transport dispatch destination; independent of the tool's origin. */
+ executor: ToolExecutor;
+ groupId?: string;
identifier: string;
- /** Returns false when an earlier hook already won the mock slot. */
- mock: (result: ToolRunResult) => boolean;
operationId: string;
+ /** Only present when the run has an actual parent operation in its lineage. */
+ parentOperationId?: string;
+ sessionId?: string;
+ sourceMessageId?: string;
stepIndex: number;
+ taskId?: string;
+ threadId?: string;
+ /** Native model/runtime call id, never synthesized from callIndex. */
+ toolCallId: string;
+ /** Existing tool message on resume; absent before a new message is created. */
+ toolMessageId?: string;
+ toolSource?: string;
+ topicId?: string;
+ userId?: string;
+ workspaceId?: string;
}
/**
- * Event payload for beforeToolCall observation dispatch (webhook/logging).
- * Same fields as ToolCallHookEvent but without mock() β€” used for production webhook delivery.
+ * Event payload for beforeToolCall hooks.
+ * Call `mock()` to skip real tool execution and return a fake result.
*/
-export interface BeforeToolCallObservationEvent {
- apiName: string;
- args: Record<string, any>;
- callIndex: number;
- identifier: string;
- operationId: string;
- stepIndex: number;
- userId?: string;
+export interface ToolCallHookEvent extends ToolCallHookContext {
+ /** Returns false when an earlier hook already won the mock slot. */
+ mock: (result: ToolRunResult) => boolean;
}
-export interface AfterToolCallHookEvent {
- apiName: string;
- args: Record<string, any>;
- callIndex: number;
- content: string;
- executionTimeMs: number;
- identifier: string;
+/** beforeToolCall notification payload, without the local mock callback. */
+export type BeforeToolCallObservationEvent = ToolCallHookContext;
+
+export interface AfterToolCallHookEvent extends ToolCallHookContext {
+ /** Whether a beforeToolCall hook supplied the result through mock(). */
mocked: boolean;
- operationId: string;
- stepIndex: number;
- success: boolean;
- userId?: string;
+ /** Structured result after archival, including errors and state (e.g. blocked). */
+ result: ToolRunResult;
}
-export interface ToolCallErrorHookEvent {
- apiName: string;
- args: Record<string, any>;
- callIndex: number;
+export interface ToolCallErrorHookEvent extends ToolCallHookContext {
error: string;
- identifier: string;
- operationId: string;
- stepIndex: number;
- userId?: string;
}
export interface BeforeCompactHookEvent {
@@ -262,12 +275,14 @@ export interface BeforeCallAgentHookEvent {
userId?: string;
}
+/** Reports the creation/start result; child completion belongs to its onComplete hook. */
export interface AfterCallAgentHookEvent {
agentId: string;
operationId: string;
subOperationId: string;
success: boolean;
- threadId: string;
+ /** Isolated child thread, when available; shared group members have no isolated thread. */
+ threadId?: string;
userId?: string;
}
diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.ts
index dd058db6388..66aa168681c 100644
--- a/packages/agent-runtime/src/utils/index.ts
+++ b/packages/agent-runtime/src/utils/index.ts
@@ -2,6 +2,7 @@ export * from './llmErrorClassifier';
export * from './messageSelectors';
export * from './normalizeAgentState';
export * from './operationToolSet';
+export * from './redactResultForEvents';
export * from './replay';
export * from './runtimeRetry';
export * from './stateSlots';
diff --git a/packages/agent-runtime/src/utils/redactResultForEvents.ts b/packages/agent-runtime/src/utils/redactResultForEvents.ts
new file mode 100644
index 00000000000..da5d0f56ca8
--- /dev/null
+++ b/packages/agent-runtime/src/utils/redactResultForEvents.ts
@@ -0,0 +1,7 @@
+import type { ToolRunResult } from '../transport/tool';
+
+/** Trim raw skill payloads from event copies while preserving the result used for Work registration. */
+export const redactResultForEvents = (result: ToolRunResult): ToolRunResult =>
+ result.workRegistration?.type === 'skill'
+ ? { ...result, workRegistration: { ...result.workRegistration, args: undefined, data: null } }
+ : result;