Skip to content

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

🐛 fix(agent): preserve hook denial reasons in tool results (#20714)

Bryande581d964aff
diff --git a/.agents/skills/agent-runtime-hooks/SKILL.md b/.agents/skills/agent-runtime-hooks/SKILL.md
index 320a9b49bfb..42d6ac4ad70 100644
--- a/.agents/skills/agent-runtime-hooks/SKILL.md
+++ b/.agents/skills/agent-runtime-hooks/SKILL.md
@@ -102,10 +102,10 @@ const hook: AgentHook = {
- `matcher` is a regex against `${identifier}/${apiName}`, supported only on tool events. Omitted, empty, or `*` matches all tools.
- Header environment templates resolve only at send time from `allowedEnvVars`; persist templates, never resolved secrets.
- Notifications ignore response content and may return HTTP 204.
-- `beforeToolCall` with `responseHandling: 'toolCall'` awaits an optional HTTP decision before tool execution. Return HTTP 2xx JSON with `{ "decision": "allow" }` or `{ "decision": "deny", "reason": "禁止执行该操作" }` to intervene. The type is `{ decision: 'allow' } | { decision: 'deny'; reason?: string }`; a deny without reason uses `Blocked by beforeToolCall hook.`. Denials preserve the reason in the tool result/card with classification `hook_denied`.
-- `afterToolCall` also accepts `responseHandling: 'toolCall'`. It synchronously checks the full request/result before archival and model consumption; deny substitutes a neutral result and never echoes receiver reasons. It does not undo tool side effects, retries, or charges. See [the result-control contract](../../../docs/development/agent-tool-result-hooks.md) for deferred completions and runtime boundaries.
+- `beforeToolCall` with `responseHandling: 'toolCall'` awaits an optional HTTP decision before tool execution. Return HTTP 2xx JSON with `{ "decision": "allow" }` or `{ "decision": "deny", "reason": "禁止执行该操作" }` to intervene. The type is `{ decision: 'allow' } | { decision: 'deny'; reason?: string }`; a deny with an omitted or empty reason uses `Blocked by beforeToolCall hook.`. Denials preserve the reason in the tool result/card with classification `hook_denied`.
+- `afterToolCall` also accepts `responseHandling: 'toolCall'`. It synchronously checks the full request/result before archival and model consumption; deny replaces the original result with the receiver's optional reason in both content and blocked state. A deny with an omitted or empty reason uses `Blocked by afterToolCall hook.`, following the same `Blocked by ${type} hook.` rule as `beforeToolCall`. The reason enters model context and the tool card, as with `beforeToolCall`. It does not undo tool side effects, retries, or charges. See [the result-control contract](../../../docs/development/agent-tool-result-hooks.md) for deferred completions and runtime boundaries.
- Environment response modes are `ignore` (default notifications) and `toolCall` (optional decisions for both before and after). Only subscribed events are enabled. Replace removed `toolResult`/`toolCallAndResult` values with `toolCall`; use the events list to select after-only checking. Existing after responses with a valid decision now control results.
-- HTTP 204, empty successful bodies, invalid JSON, and JSON without a top-level decision (including arrays, scalars, null, or only the old nested `hookSpecificOutput`) are notification responses, even with `onError: 'block'`. Continue checking subsequent hooks; do not treat a notification as permission to skip later policies. Explicit invalid decisions, non-2xx status, oversized bodies, invalid UTF-8, network failures, and timeouts follow `onError: 'continue' | 'block'` (default `continue`). Cancellation never grants permission.
+- HTTP 204, empty successful bodies, invalid JSON, and JSON without a top-level decision (including arrays, scalars, null, or only the old nested `hookSpecificOutput`) are notification responses, even with `onError: 'block'`. Continue checking subsequent hooks; do not treat a notification as permission to skip later policies. Explicit invalid decisions, non-2xx status, oversized bodies, invalid UTF-8, network failures, and timeouts follow `onError: 'continue' | 'block'` (default `continue`); blocking uses `hook_control_error` as the tool-result content and reason for both before and after hooks. Cancellation never grants permission.
- Extra response fields are allowed and discarded. Only `decision` and a deny's optional string `reason` are consumed; `updatedInput`/`additionalContext` do not change tool arguments or conversation context.
- Configuration: `packages/types/src/agentHook.ts`; response parsing: `packages/types/src/agentHookResponse.ts`; HTTP delivery: `apps/server/src/services/agentRuntime/hooks/httpWebhook.ts`.
diff --git a/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts
index b42c01ddf78..2075d74d4a2 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts
@@ -9,7 +9,6 @@ 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 { BLOCKED_TOOL_RESULT_CONTENT } from '@/server/services/agentRuntime/hooks/toolResultControl';
import type { RuntimeExecutorContext } from '../context';
import { ServerToolTransport } from './ServerToolTransport';
@@ -172,6 +171,8 @@ afterEach(() => {
describe('afterToolCall control pipeline', () => {
const secret = 'synthetic-sensitive-result';
+ const denialReason = '禁止将敏感工具结果交给模型';
+ const defaultReason = 'Blocked by afterToolCall hook.';
const raw = () => ({
content: secret.repeat(1000),
error: { message: secret, type: 'tool_error' },
@@ -195,7 +196,7 @@ describe('afterToolCall control pipeline', () => {
'withholds the full result before persistence and LLM continuation, queue=%s',
async (queue) => {
queueMode.mockReturnValue(queue);
- fetchHook.mockImplementation(async () => response('deny', secret));
+ fetchHook.mockImplementation(async () => response('deny', denialReason));
const fixture = setup([control()], undefined, true);
fixture.execute.mockResolvedValue(raw());
const result = await fixture.step();
@@ -209,22 +210,26 @@ describe('afterToolCall control pipeline', () => {
});
expect(fixture.rows).toEqual([
expect.objectContaining({
- content: BLOCKED_TOOL_RESULT_CONTENT,
+ content: denialReason,
pluginError: 'hook_denied',
pluginState: {
type: 'blocked',
phase: 'afterToolCall',
- reason: BLOCKED_TOOL_RESULT_CONTENT,
+ reason: denialReason,
},
tool_call_id: 'native-1',
}),
]);
expect(JSON.stringify(result)).not.toContain(secret);
+ expect(JSON.stringify(result)).toContain(denialReason);
expect(JSON.stringify(result)).not.toContain('123456789');
expect(JSON.stringify(await fixture.host.transports.messages.query())).not.toContain(secret);
expect(
JSON.stringify(vi.mocked(fixture.host.transports.stream.publishEvent).mock.calls),
).not.toContain(secret);
+ expect(
+ JSON.stringify(vi.mocked(fixture.host.transports.stream.publishEvent).mock.calls),
+ ).toContain(denialReason);
expect(archive).not.toHaveBeenCalled();
expect(result.newState.cost?.tools.total).toBe(5);
expect(fixture.host.transports.stream.publishEvent).toHaveBeenCalledWith(
@@ -289,7 +294,8 @@ describe('afterToolCall control pipeline', () => {
);
resolve(response('deny'));
await running;
- expect(fixture.rows[0].content).toBe(BLOCKED_TOOL_RESULT_CONTENT);
+ expect(fixture.rows[0].content).toBe(defaultReason);
+ expect(fixture.rows[0].pluginState).toMatchObject({ reason: defaultReason });
});
it.each(['server', 'client', 'mock'] as const)(
@@ -329,9 +335,10 @@ describe('afterToolCall control pipeline', () => {
fetchHook.mockResolvedValue(new Response(JSON.stringify({ decision: secret })));
const result = await fixture.step();
expect(fixture.execute).toHaveBeenCalledTimes(1);
- expect(fixture.rows[0].content).toBe(
- onError === 'block' ? BLOCKED_TOOL_RESULT_CONTENT : 'executed',
- );
+ expect(fixture.rows[0].content).toBe(onError === 'block' ? 'hook_control_error' : 'executed');
+ if (onError === 'block') {
+ expect(fixture.rows[0].pluginState).toMatchObject({ reason: 'hook_control_error' });
+ }
expect(JSON.stringify(result)).not.toContain(secret);
},
);
@@ -359,15 +366,16 @@ describe('afterToolCall control pipeline', () => {
}),
);
const result = await fixture.step();
- expect(fixture.rows[0].content).toBe(
- onError === 'block' ? BLOCKED_TOOL_RESULT_CONTENT : 'executed',
- );
+ expect(fixture.rows[0].content).toBe(onError === 'block' ? 'hook_control_error' : 'executed');
+ if (onError === 'block') {
+ expect(fixture.rows[0].pluginState).toMatchObject({ reason: 'hook_control_error' });
+ }
expect(fixture.execute).toHaveBeenCalledTimes(1);
expect(JSON.stringify(result)).not.toContain(secret);
},
);
- it('applies ordered controls once, preserves a tool stop, and does not forward a receiver reason', async () => {
+ it('applies ordered controls once, preserves a tool stop, and forwards the denying hook reason', async () => {
const fixture = setup([
control('allow'),
{ ...control('skip'), matcher: '^other/' },
@@ -376,7 +384,7 @@ describe('afterToolCall control pipeline', () => {
]);
fixture.execute.mockResolvedValue({ ...raw(), stop: true });
fetchHook.mockImplementation(async (url) =>
- response(String(url).endsWith('/deny') ? 'deny' : 'allow', secret),
+ response(String(url).endsWith('/deny') ? 'deny' : 'allow', denialReason),
);
const result = await fixture.step();
expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([
@@ -384,9 +392,49 @@ describe('afterToolCall control pipeline', () => {
'https://hooks.example/deny',
]);
expect(result.newState.status).toBe('done');
+ expect(fixture.rows[0]).toMatchObject({
+ content: denialReason,
+ pluginState: { reason: denialReason },
+ });
expect(JSON.stringify(result)).not.toContain(secret);
});
+ it.each([' \n自定义 "reason"\n ', secret])(
+ 'preserves an explicitly provided denial reason verbatim: %j',
+ async (reason) => {
+ const fixture = setup([control()]);
+ fixture.execute.mockResolvedValue(raw());
+ fetchHook.mockImplementation(async () => response('deny', reason));
+
+ await fixture.step();
+
+ expect(fixture.rows[0]).toMatchObject({
+ content: reason,
+ pluginError: 'hook_denied',
+ pluginState: { reason, type: 'blocked', phase: 'afterToolCall' },
+ });
+ expect(fixture.rows[0].pluginState).not.toHaveProperty('nested');
+ expect(fixture.rows[0].pluginState).not.toHaveProperty('images');
+ expect(archive).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([false, true])('uses the default for an empty denial reason, queue=%s', async (queue) => {
+ queueMode.mockReturnValue(queue);
+ const fixture = setup([control()]);
+ fixture.execute.mockResolvedValue(raw());
+ fetchHook.mockImplementation(async () => response('deny', ''));
+
+ await fixture.step();
+
+ expect(fixture.rows[0]).toMatchObject({
+ content: defaultReason,
+ pluginError: 'hook_denied',
+ pluginState: { reason: defaultReason, type: 'blocked', phase: 'afterToolCall' },
+ });
+ expect(JSON.stringify(fixture.rows)).not.toContain(secret);
+ });
+
it('evaluates a failed result after the last tool retry only', async () => {
const fixture = setup([control()]);
fixture.execute.mockResolvedValue({
@@ -417,7 +465,7 @@ describe('afterToolCall control pipeline', () => {
expect.arrayContaining([
expect.objectContaining({
tool_call_id: 'constructor',
- content: BLOCKED_TOOL_RESULT_CONTENT,
+ content: defaultReason,
}),
expect.objectContaining({ tool_call_id: '__proto__', content: 'allowed sibling' }),
]),
@@ -467,7 +515,7 @@ describe('afterToolCall control pipeline', () => {
expect(fixture.rows).toHaveLength(1);
expect(fixture.host.transports.messages.updateToolMessage).toHaveBeenCalledWith(
'existing-row',
- expect.objectContaining({ replacePluginState: true, content: BLOCKED_TOOL_RESULT_CONTENT }),
+ expect.objectContaining({ replacePluginState: true, content: defaultReason }),
);
expect(JSON.stringify(await fixture.host.transports.messages.query())).not.toContain(secret);
expect(JSON.stringify(result)).not.toContain(secret);
@@ -712,11 +760,7 @@ describe('afterToolCall control pipeline', () => {
'run:three',
'control:three',
]);
- expect(fixture.rows.map((row) => row.content)).toEqual([
- 'one',
- BLOCKED_TOOL_RESULT_CONTENT,
- 'three',
- ]);
+ expect(fixture.rows.map((row) => row.content)).toEqual(['one', defaultReason, 'three']);
});
it.each(['beforeToolCall', 'afterToolCall', 'beforeToolCall,afterToolCall'])(
@@ -734,7 +778,7 @@ describe('afterToolCall control pipeline', () => {
await fixture.step();
expect(fixture.execute).toHaveBeenCalledTimes(1);
expect(fixture.rows[0].content).toBe(
- events.includes('afterToolCall') ? BLOCKED_TOOL_RESULT_CONTENT : 'executed',
+ events.includes('afterToolCall') ? defaultReason : 'executed',
);
expect(fetchHook.mock.calls.map(([, init]) => JSON.parse(init.body).hookType)).toEqual(
events.split(','),
diff --git a/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts
index 7b0bc571289..f5ef8a45f94 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/toolControlPipeline.test.ts
@@ -195,11 +195,16 @@ describe('beforeToolCall control pipeline', () => {
},
);
- it.each([false, true])(
- 'denies before mock/execution and persists attempts=0, queue=%s',
- async (queue) => {
+ it.each([
+ { queue: false, reason: undefined },
+ { queue: true, reason: undefined },
+ { queue: false, reason: '' },
+ { queue: true, reason: '' },
+ ])(
+ 'denies before mock/execution and persists attempts=0, queue=$queue, reason=$reason',
+ async ({ queue, reason }) => {
queueMode.mockReturnValue(queue);
- fetchHook.mockImplementation(async () => response('deny'));
+ fetchHook.mockImplementation(async () => response('deny', reason));
const mock = vi.fn(async (event) => {
(event as ToolCallHookEvent).mock({ content: 'mock', success: true });
});
diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts
index 1fed8f9b9d6..9da67258fd0 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/serverSubAgent.integration.test.ts
@@ -19,6 +19,7 @@ import { eq } from 'drizzle-orm';
import OpenAI from 'openai';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MessageModel } from '@/database/models/message';
import { inMemoryAgentStateManager } from '@/server/modules/AgentRuntime/InMemoryAgentStateManager';
import { inMemoryStreamEventManager } from '@/server/modules/AgentRuntime/InMemoryStreamEventManager';
@@ -212,9 +213,14 @@ afterEach(async () => {
});
describe('Server callSubAgent suspend/resume', () => {
- it.each([undefined, 'allow', 'deny'] as const)(
- 'publishes the child result after %s control and resumes the parent',
- async (decision) => {
+ it.each([
+ { decision: undefined, reason: undefined },
+ { decision: 'allow', reason: undefined },
+ { decision: 'deny', reason: undefined },
+ { decision: 'deny', reason: '' },
+ ] as const)(
+ 'publishes the child result after $decision control with reason=$reason and resumes the parent',
+ async ({ decision, reason }) => {
const pendingContents: (string | null)[] = [];
const reviewedResults: string[] = [];
const fetchHook = vi.fn(async (_url: string, init: RequestInit) => {
@@ -225,7 +231,7 @@ describe('Server callSubAgent suspend/resume', () => {
.where(eq(messages.id, payload.toolMessageId));
pendingContents.push(placeholder.content);
reviewedResults.push(payload.result.content);
- return new Response(JSON.stringify({ decision }));
+ return new Response(JSON.stringify({ decision, reason }));
});
if (decision) {
vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/subagent-result');
@@ -291,18 +297,31 @@ describe('Server callSubAgent suspend/resume', () => {
m.role === 'tool' &&
!!m.content &&
stripSubAgentReference(m.content) ===
- (decision === 'deny'
- ? 'Tool result withheld by afterToolCall hook.'
- : SUB_AGENT_ANSWER),
+ (decision === 'deny' ? 'Blocked by afterToolCall hook.' : SUB_AGENT_ANSWER),
);
expect(subAgentToolMessage).toBeDefined();
if (decision !== 'deny')
expect(subAgentToolMessage!.content).toMatch(/<sub_agent id="[^"]+" \/>$/);
const parentInput = JSON.stringify(mockResponsesCreate.mock.calls[2][0]);
expect(parentInput).toContain(
- decision === 'deny' ? 'Tool result withheld by afterToolCall hook.' : SUB_AGENT_ANSWER,
+ decision === 'deny' ? 'Blocked by afterToolCall hook.' : SUB_AGENT_ANSWER,
);
- if (decision === 'deny') expect(parentInput).not.toContain(SUB_AGENT_ANSWER);
+ if (decision === 'deny') {
+ expect(parentInput).not.toContain(SUB_AGENT_ANSWER);
+ // A replay after removal of the environment hook must not replace the first final result.
+ vi.unstubAllEnvs();
+ const messageModel = new MessageModel(serverDB, userId);
+ const replay = await messageModel.updateToolMessage(subAgentToolMessage!.id, {
+ content: SUB_AGENT_ANSWER,
+ pluginState: { status: 'completed' },
+ pluginError: null,
+ onlyIfEmpty: true,
+ });
+ expect(replay).toMatchObject({ success: true, applied: false });
+ const persisted = await messageModel.findById(subAgentToolMessage!.id);
+ expect(persisted?.content).toBe('Blocked by afterToolCall hook.');
+ expect(JSON.stringify(persisted)).not.toContain(SUB_AGENT_ANSWER);
+ }
},
);
});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 7b0146536a4..c9c5050d012 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -3753,6 +3753,89 @@ describe('AgentRuntimeService', () => {
expect(resumeSpy).toHaveBeenCalled();
});
+ it('completes a multi-member empty-reason denial and retains it after callback replay', async () => {
+ const privateContent = 'synthetic-private-member-answer';
+ const defaultReason = 'Blocked by afterToolCall hook.';
+ const anchors = [
+ { id: 'anchor-0', content: '', state: {} },
+ { id: 'anchor-1', content: '', state: {} },
+ ];
+ const group = { id: 'grp-tool-1', parentId: 'assistant', content: '', state: {} };
+ const rows = [...anchors, group];
+ (service as any).serverDB.query = {
+ messages: { findMany: vi.fn(async () => anchors) },
+ messagePlugins: { findFirst: vi.fn().mockResolvedValue({ state: {} }) },
+ };
+ (service as any).messageModel.findById = vi.fn(async (id) =>
+ rows.find((row) => row.id === id),
+ );
+ (service as any).messageModel.findMessagePlugin = vi.fn(async (id) => ({
+ id,
+ toolCallId: 'group-call',
+ identifier: 'lobe-group-management',
+ apiName: 'executeAgentTasks',
+ arguments: '{}',
+ }));
+ updateToolMessage.mockImplementation(async (id, value) => {
+ const row = rows.find((row) => row.id === id)!;
+ if (row.content && value.onlyIfEmpty) return { success: true, applied: false };
+ row.content = value.content;
+ row.state = value.pluginState;
+ return { success: true, applied: true };
+ });
+ mockCoordinator.loadAgentState.mockResolvedValue({
+ operationId: 'parent-1',
+ stepCount: 1,
+ status: 'waiting_for_async_tool',
+ host: {
+ hooks: [
+ {
+ id: 'after-control',
+ type: 'afterToolCall',
+ webhook: { url: 'https://hooks.example/control', responseHandling: 'toolCall' },
+ },
+ ],
+ },
+ });
+ const fetchHook = vi
+ .spyOn(globalThis, 'fetch')
+ .mockImplementation(
+ async () => new Response(JSON.stringify({ decision: 'deny', reason: '' })),
+ );
+ const complete = (anchorMessageId: string) =>
+ service.completeGroupActionMember({
+ anchorMessageId,
+ expectedMembers: 2,
+ finalState: {
+ ...memberState,
+ messages: [{ role: 'assistant', content: privateContent }],
+ } as any,
+ groupToolMessageId: group.id,
+ mode: 'isolated',
+ onComplete: 'resume',
+ operationId: `child-${anchorMessageId}`,
+ parentOperationId: 'parent-1',
+ reason: 'done',
+ });
+ try {
+ expect(await complete('anchor-0')).toBe(false);
+ expect(resumeSpy).not.toHaveBeenCalled();
+ expect(await complete('anchor-1')).toBe(true);
+ expect(resumeSpy).toHaveBeenCalledTimes(1);
+ expect(fetchHook).toHaveBeenCalledTimes(3);
+ expect(rows.every((row) => row.content === defaultReason)).toBe(true);
+ expect(JSON.stringify(rows)).not.toContain(privateContent);
+
+ mockCoordinator.loadAgentState.mockResolvedValue(null);
+ await complete('anchor-0');
+ expect(fetchHook).toHaveBeenCalledTimes(3);
+ expect(rows.every((row) => row.content === defaultReason)).toBe(true);
+ expect(JSON.stringify(rows)).not.toContain(privateContent);
+ } finally {
+ fetchHook.mockRestore();
+ }
+ });
+
it('throws when the anchor backfill fails so the webhook redelivers', async () => {
updateToolMessage.mockResolvedValue({ success: false });
@@ -3829,86 +3912,104 @@ describe('AgentRuntimeService', () => {
);
});
- it('gates deferred output before backfill and parent resume, including callback replay', async () => {
- const privateContent = 'synthetic-private-child-answer';
- const stored = {
- id: 'tool-msg-1',
- identifier: 'lobe-agent',
- apiName: 'callSubAgent',
- arguments: '{"instruction":"original"}',
- toolCallId: 'native-child',
- state: {},
- };
- (service as any).messageModel.findMessagePlugin = vi.fn(async () => stored);
- (service as any).messageModel.findById = vi
- .fn()
- .mockResolvedValue({ id: 'tool-msg-1', parentId: 'assistant' });
- const fetchHook = vi
- .spyOn(globalThis, 'fetch')
- .mockImplementation(
- async () => new Response(JSON.stringify({ decision: 'deny', reason: privateContent })),
- );
- const hooks = [
- {
- id: 'after-control',
- type: 'afterToolCall',
- webhook: { url: 'https://hooks.example/control', responseHandling: 'toolCall' },
- },
- ];
- mockCoordinator.loadAgentState.mockResolvedValue({
- operationId: 'parent-op-1',
- stepCount: 3,
- host: { hooks },
- });
- updateToolMessage.mockImplementation(async (_id, value) => {
- if ((stored as any).content && value.onlyIfEmpty) return { success: true, applied: false };
- (stored as any).content = value.content;
- stored.state = value.pluginState;
- (service as any).messageModel.findById.mockResolvedValue({
+ it.each([
+ {
+ reason: 'The child result is restricted by policy.',
+ expected: 'The child result is restricted by policy.',
+ },
+ { reason: '', expected: 'Blocked by afterToolCall hook.' },
+ ])(
+ 'gates deferred output before backfill and parent resume, including callback replay, reason=$reason',
+ async ({ reason, expected: denialReason }) => {
+ const privateContent = 'synthetic-private-child-answer';
+ const stored = {
id: 'tool-msg-1',
- parentId: 'assistant',
- content: value.content,
- });
- return { success: true };
- });
- try {
- await service.completeSubAgentBridge({
- ...bridgeParams,
- finalState: {
- ...childState,
- messages: [{ role: 'assistant', content: privateContent }],
- } as any,
- });
- expect(JSON.parse(String(fetchHook.mock.calls[0][1]?.body))).toMatchObject({
- args: { instruction: 'original' },
+ identifier: 'lobe-agent',
+ apiName: 'callSubAgent',
+ arguments: '{"instruction":"original"}',
toolCallId: 'native-child',
- result: { content: expect.stringContaining(privateContent) },
+ state: {},
+ };
+ (service as any).messageModel.findMessagePlugin = vi.fn(async () => stored);
+ (service as any).messageModel.findById = vi
+ .fn()
+ .mockResolvedValue({ id: 'tool-msg-1', parentId: 'assistant' });
+ const fetchHook = vi
+ .spyOn(globalThis, 'fetch')
+ .mockImplementation(
+ async () => new Response(JSON.stringify({ decision: 'deny', reason })),
+ );
+ const hooks = [
+ {
+ id: 'after-control',
+ type: 'afterToolCall',
+ webhook: { url: 'https://hooks.example/control', responseHandling: 'toolCall' },
+ },
+ ];
+ mockCoordinator.loadAgentState.mockResolvedValue({
+ operationId: 'parent-op-1',
+ stepCount: 3,
+ host: { hooks },
});
- expect(JSON.stringify(updateToolMessage.mock.calls)).not.toContain(privateContent);
- expect(updateToolMessage).toHaveBeenCalledWith(
- 'tool-msg-1',
- expect.objectContaining({
- content: 'Tool result withheld by afterToolCall hook.',
- replacePluginState: true,
- onlyIfEmpty: true,
- }),
- );
- expect(resumeSpy).toHaveBeenCalledTimes(1);
- // A duplicate callback cannot restore the raw child answer after configuration removal.
- mockCoordinator.loadAgentState.mockResolvedValue(null);
- await service.completeSubAgentBridge({
- ...bridgeParams,
- finalState: {
- ...childState,
- messages: [{ role: 'assistant', content: privateContent }],
- } as any,
+ updateToolMessage.mockImplementation(async (_id, value) => {
+ if ((stored as any).content && value.onlyIfEmpty)
+ return { success: true, applied: false };
+ (stored as any).content = value.content;
+ stored.state = value.pluginState;
+ (service as any).messageModel.findById.mockResolvedValue({
+ id: 'tool-msg-1',
+ parentId: 'assistant',
+ content: value.content,
+ });
+ return { success: true };
});
- expect(fetchHook).toHaveBeenCalledTimes(1);
- expect((stored as any).content).toBe('Tool result withheld by afterToolCall hook.');
- } finally {
- fetchHook.mockRestore();
- }
- });
+ try {
+ await service.completeSubAgentBridge({
+ ...bridgeParams,
+ finalState: {
+ ...childState,
+ messages: [{ role: 'assistant', content: privateContent }],
+ } as any,
+ });
+ expect(JSON.parse(String(fetchHook.mock.calls[0][1]?.body))).toMatchObject({
+ args: { instruction: 'original' },
+ toolCallId: 'native-child',
+ result: { content: expect.stringContaining(privateContent) },
+ });
+ expect(JSON.stringify(updateToolMessage.mock.calls)).not.toContain(privateContent);
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'tool-msg-1',
+ expect.objectContaining({
+ content: denialReason,
+ pluginError: 'hook_denied',
+ pluginState: expect.objectContaining({
+ phase: 'afterToolCall',
+ reason: denialReason,
+ type: 'blocked',
+ }),
+ replacePluginState: true,
+ onlyIfEmpty: true,
+ }),
+ );
+ expect(resumeSpy).toHaveBeenCalledTimes(1);
+ // A duplicate callback cannot restore the raw child answer after configuration removal.
+ mockCoordinator.loadAgentState.mockResolvedValue(null);
+ await service.completeSubAgentBridge({
+ ...bridgeParams,
+ finalState: {
+ ...childState,
+ messages: [{ role: 'assistant', content: privateContent }],
+ } as any,
+ });
+ expect(fetchHook).toHaveBeenCalledTimes(1);
+ expect((stored as any).content).toBe(denialReason);
+ expect(stored.state).toMatchObject({ reason: denialReason, type: 'blocked' });
+ expect(JSON.stringify(stored.state)).not.toContain(privateContent);
+ } finally {
+ fetchHook.mockRestore();
+ }
+ },
+ );
it('ends a callSubAgent result with the sub-agent id so the parent can continue it', async () => {
(service as any).messageModel.findMessagePlugin = vi
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index 1af59c0a044..afe3520288f 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -220,7 +220,7 @@ export class HookDispatcher {
if (response.status === 'success' && response.decision.decision === 'deny') {
return {
status: 'blocked',
- reason: response.decision.reason ?? `Blocked by ${type} hook.`,
+ reason: response.decision.reason || `Blocked by ${type} hook.`,
};
}
if (response.status === 'error') {
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/deferredToolResultControl.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/deferredToolResultControl.test.ts
index 5bdec70739b..bf6fc7648fa 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/deferredToolResultControl.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/deferredToolResultControl.test.ts
@@ -4,7 +4,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { controlDeferredToolResult } from '../deferredToolResultControl';
import { HookDispatcher } from '../HookDispatcher';
-import { BLOCKED_TOOL_RESULT_CONTENT } from '../toolResultControl';
const { fetchHook, queueMode } = vi.hoisted(() => ({ fetchHook: vi.fn(), queueMode: vi.fn() }));
vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds: async () => [] } }));
@@ -13,6 +12,7 @@ vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: qu
vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));
const secret = 'synthetic-private-child-result';
+const denialReason = '子任务结果被策略拒绝';
const original = { content: secret, success: true, state: { full: secret, totalCost: 0.25 } };
const plugin: MessagePluginItem = {
id: 'tool-row',
@@ -68,7 +68,7 @@ beforeEach(() => {
fetchHook
.mockReset()
.mockImplementation(
- async () => new Response(JSON.stringify({ decision: 'deny', reason: secret })),
+ async () => new Response(JSON.stringify({ decision: 'deny', reason: denialReason })),
);
queueMode.mockReturnValue(false);
});
@@ -138,9 +138,10 @@ describe('out-of-band tool result control', () => {
result: original,
});
expect(result).toMatchObject({
- content: BLOCKED_TOOL_RESULT_CONTENT,
+ content: denialReason,
+ error: 'hook_denied',
success: false,
- state: { totalCost: 0.25 },
+ state: { totalCost: 0.25, reason: denialReason, type: 'blocked', phase: 'afterToolCall' },
});
expect(JSON.stringify(result)).not.toContain(secret);
},
@@ -161,7 +162,7 @@ describe('out-of-band tool result control', () => {
parentId: 'assistant',
});
const { result } = await controlDeferredToolResult(deps, input);
- expect(result.content).toBe(BLOCKED_TOOL_RESULT_CONTENT);
+ expect(result.content).toBe(denialReason);
expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({
operationId: 'parent',
toolCallId: 'native-call',
@@ -322,7 +323,7 @@ describe('out-of-band tool result control', () => {
),
);
expect((await controlDeferredToolResult(deps, input)).result.content).toBe(
- BLOCKED_TOOL_RESULT_CONTENT,
+ 'Blocked by afterToolCall hook.',
);
expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([
'https://hooks.example/after',
@@ -364,8 +365,6 @@ describe('out-of-band tool result control', () => {
vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');
vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');
vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');
- expect((await controlDeferredToolResult(deps, input)).result.content).toBe(
- BLOCKED_TOOL_RESULT_CONTENT,
- );
+ expect((await controlDeferredToolResult(deps, input)).result.content).toBe(denialReason);
});
});
diff --git a/apps/server/src/services/agentRuntime/hooks/toolResultControl.ts b/apps/server/src/services/agentRuntime/hooks/toolResultControl.ts
index d23f471ca5d..dafab2bbe43 100644
--- a/apps/server/src/services/agentRuntime/hooks/toolResultControl.ts
+++ b/apps/server/src/services/agentRuntime/hooks/toolResultControl.ts
@@ -18,18 +18,24 @@ export interface ToolResultControlOutcome {
/**
* The tool has already executed. Replace its entire model-facing result, rather
* than only the text: state/error/Work data may contain the same denied output.
- * Never echo a receiver-provided reason, which may quote the protected result.
+ * The hook's denial reason is the replacement content; discard the original output.
*/
-export function blockedToolResult(result: ToolRunResult, preserveUsage = false): ToolRunResult {
+export function blockedToolResult(
+ result: ToolRunResult,
+ {
+ preserveUsage = false,
+ reason = BLOCKED_TOOL_RESULT_CONTENT,
+ }: { preserveUsage?: boolean; reason?: string } = {},
+): ToolRunResult {
return {
- content: BLOCKED_TOOL_RESULT_CONTENT,
+ content: reason,
deviceExecutionTime: result.deviceExecutionTime,
error: 'hook_denied',
executionTime: result.executionTime,
state: {
...(preserveUsage && pickToolResultUsage(result.state)),
phase: 'afterToolCall',
- reason: BLOCKED_TOOL_RESULT_CONTENT,
+ reason,
type: 'blocked',
},
...(result.stop !== undefined && { stop: result.stop }),
@@ -62,7 +68,7 @@ export async function controlToolResult(
return {
blocked: true,
cancelled: true,
- result: blockedToolResult(event.result, preserveUsage),
+ result: blockedToolResult(event.result, { preserveUsage }),
};
}
return {
@@ -70,7 +76,7 @@ export async function controlToolResult(
cancelled: false,
result:
decision?.status === 'blocked'
- ? blockedToolResult(event.result, preserveUsage)
+ ? blockedToolResult(event.result, { preserveUsage, reason: decision.reason })
: event.result,
};
}
diff --git a/docs/development/agent-tool-result-hooks.md b/docs/development/agent-tool-result-hooks.md
index 088aee942fe..98ffca269c1 100644
--- a/docs/development/agent-tool-result-hooks.md
+++ b/docs/development/agent-tool-result-hooks.md
@@ -35,7 +35,7 @@ To control the call or result, reply with HTTP 2xx and either:
{ "decision": "deny", "reason": "Result is not suitable for the model" }
```
-Only `decision` and an optional string denial `reason` are parsed. Extra fields are ignored; controls cannot replace results, rewrite arguments, or append model context. Controls require fetch, cannot also have a local handler, and cannot filter or override their request with `eventFields` or `body`.
+Only `decision` and an optional string denial `reason` are parsed. Extra fields are ignored; controls cannot supply an allowed result, rewrite arguments, or append model context. Controls require fetch, cannot also have a local handler, and cannot filter or override their request with `eventFields` or `body`.
HTTP 204, empty bodies, invalid JSON, and valid JSON without a top-level `decision` are notification responses. This includes arrays, scalars, `null`, and the old nested `hookSpecificOutput` format. They continue even with `onError: 'block'`. An explicit but invalid decision (including an invalid denial reason) is a protocol error and follows `onError`. Each hook is still awaited; notification responses do not bypass later matching controls.
@@ -44,11 +44,11 @@ Matching controls run in registration order. A deny stops the remaining controls
## Denial and failure behavior
- Allow continues the existing archival, persistence, streaming, and model-context flow
-- Deny replaces the complete result with `Tool result withheld by afterToolCall hook.`, `error: 'hook_denied'`, and a neutral blocked state tagged `phase: 'afterToolCall'`. The original content, error, images/state, archive references, and Work-registration intent are not passed onward
-- The receiver's denial reason is deliberately not echoed into model context or tool state, because it could quote the denied output
+- Deny replaces the complete result with the receiver's optional `reason`, `error: 'hook_denied'`, and a blocked state tagged `phase: 'afterToolCall'` whose `reason` matches the replacement content. With an omitted or empty reason, the replacement is `Blocked by afterToolCall hook.`, following the same `Blocked by ${type} hook.` rule as `beforeToolCall`. The original content, error, images/state, archive references, and Work-registration intent are not passed onward
+- As with `beforeToolCall`, a non-empty denial reason enters the tool result, model context, and tool card unchanged. An omitted or empty reason uses `Blocked by ${type} hook.` so deferred denials remain final for completion and replay checks
- The native call/result pairing remains intact. A deny does not retry the tool or charge it as an unexecuted call; actual attempt count, execution time, and existing tool charges remain. Deferred child usage counters are retained without child output
- Result controls run after the tool's existing internal retry loop and also inspect failed/timeout results. Exceptions that do not produce a result retain the existing `onToolCallError` behavior
-- Non-2xx responses, explicit invalid decisions, oversized responses, invalid UTF-8, network failures, and timeouts use the existing `onError` policy: `continue` by default, or `block`. Successful notification responses do not invoke `onError`. Cancellation never becomes permission to release a result
+- Non-2xx responses, explicit invalid decisions, oversized responses, invalid UTF-8, network failures, and timeouts use the existing `onError` policy: `continue` by default, or `block`. Blocking on a control error uses `hook_control_error` as both content and blocked-state reason, for before and after hooks. Successful notification responses do not invoke `onError`. Cancellation never becomes permission to release a result
- Denied results are persisted in sanitized form, so later history rehydration cannot recover their original content or state. Deferred completion replays cannot overwrite an already withheld result, even if the hook is later removed
## Server environment configuration