π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(agent): gate tool results with afterToolCall controls (#20297)
Bryan8df205644f1b
diff --git a/.agents/skills/agent-runtime-hooks/SKILL.md b/.agents/skills/agent-runtime-hooks/SKILL.mdindex 4ff7a482481..dd182eef9d6 100644--- a/.agents/skills/agent-runtime-hooks/SKILL.md+++ b/.agents/skills/agent-runtime-hooks/SKILL.md@@ -22,7 +22,7 @@ execAgent({ hooks })β ββ [call_tool]β β ββ beforeToolCall ββ Before tool executes (supports mocking)β β ββ (tool execution)- β β ββ afterToolCall βββ After tool completes (observation only)+ β β ββ afterToolCall βββ After tool completes (optional result control)β β ββ onToolCallError β Tool threw an exceptionβ ββ ββ [request_human_approve]@@ -103,10 +103,29 @@ const hook: AgentHook = {- 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 HTTP control response before tool execution. Return HTTP 200 JSON with `{ "decision": "allow" }` or `{ "decision": "deny", "reason": "η¦ζ’ζ§θ‘θ―₯ζδ½" }`. 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.+- Environment response modes preserve compatibility: `toolCall` controls only before; opt into `toolResult` for after-only or `toolCallAndResult` for both. The per-hook decision protocol remains `responseHandling: 'toolCall'`.- Empty bodies, HTTP 204 or other non-200 status, invalid JSON, missing/invalid decisions, and responses containing only the old nested `hookSpecificOutput` format are protocol errors. They follow the control hook's `onError: 'continue' | 'block'` policy (default `continue`); an empty response is never an allow decision.- 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`.+### Hook configuration lifetime++- Environment hooks (`AGENT_HOOK_WEBHOOK_*`) always come from the executing worker's **current environment**, including after human approval and deferred completion. Never persist their configuration or restore a previous environment's hooks.+- Code-supplied webhook hooks (`execAgent({ hooks })`) retain the existing per-operation serialization and persistence. Recover these caller hooks from the runtime snapshot or durable operation record; preserve environment-variable templates without expanding secrets into storage.+- Evaluate each operation's recovered caller hooks in order, then evaluate current environment hooks once in the final round. Do not deduplicate caller hook IDs across operations. Environment-only hooks do not require durable operation storage. Removing an environment hook stops it from controlling subsequent results; when no matching result control remains, allow the result. Do not freeze a previous environment policy across an approval or restart.+- Deferred completion publishes into its empty placeholder once; duplicate callbacks retain that first final result, including a denial. Propagate caller-policy storage errors rather than treating failed reads as an empty hook list. Do not extend default allow to configured-hook delivery failures: those follow `onError`.+- Cover environment removal/addition across approval and snapshot expiry, publication without review markers, and continued enforcement of persisted caller hooks in regression tests.++### Publish after the result hook++- Await result control before archival, message content/state writes, streaming, and model consumption. Persist the allowed result or the sanitized denial directly; do not add `toolResultControl` pending/allowed/blocked metadata or hide raw output through history projections.+- Human approval sources claim the decision and retain the answer in their private resolution/outbox. `MessageModel.resolveHumanApproval` defaults to claim-only; only the runtime calls it with `publishResult: true` after result control. Stop/rejection receipts can publish directly because they contain no executed tool output.+- Recover original caller hooks through the existing intervention operation identity or deferred callback's parent operation. Keep the in-memory hook verdict separate from tool-owned state; a tool returning `type: 'blocked'` is not a hook verdict.+- Every deferred backfill, including a member that fails to start, follows the same hook-before-write order. Use the existing empty placeholder to arbitrate duplicate final writes; do not introduce a replacement review state machine.+- When a thread has a sub-agent or group-member completion bridge, that bridge exclusively publishes its tool result. Thread lifecycle hooks update thread metadata only; never prefill the tool message with an ungated summary, including after approval recovery.+- Cover an answer held while a hook runs, atomic publication and rollback, duplicate callbacks after policy removal, and partial member startup failure. History readers should need no result-review logic.+## Events| Event | Timing and payload |@@ -154,7 +173,7 @@ Tool observation payloads use `BeforeToolCallObservationEvent`; the callback bel## Webhook Payloads-`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.+`createWebhookPayloadBuilder()` selects `eventFields`, adds `hookId`/`hookType`, then merges `webhook.body`. The body determines the final value of overlapping fields. Tool-result notification payloads use `redactResultForEvents()` to trim raw skill Work data; controls receive the full result. Work registration retains the full in-process result. `finalState` is available to local handlers; serialized payloads carry the event's data fields.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.diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex b0a492f7e68..7acd884b254 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -246,6 +246,7 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {// call_llm does a parent existence preflight; return a truthy row by// default so existing tests don't have to stub it.findById: vi.fn().mockResolvedValue({ id: 'msg-existing' }),+ findMessagePlugin: vi.fn().mockResolvedValue(undefined),// The abort settle asks whether a row already holds the call. Null by// default: these tests exercise calls that never got one.findToolMessageIdByToolCallId: vi.fn().mockResolvedValue(null),@@ -6090,6 +6091,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {async (throws) => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6141,6 +6144,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should preserve native identity and structured results across tool notifications', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6227,6 +6232,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should report structured blocked results as unsuccessful notifications, not exceptions', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6266,6 +6273,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should correlate repeated tool names in a batch by native call ids', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6307,6 +6316,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should retain client routing and structured client results in notifications', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6352,6 +6363,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should dispatch beforeToolCall and afterToolCall hooks', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6395,6 +6408,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {const controller = new AbortController();const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6427,6 +6442,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {// webhook consumer would see `afterToolCall` after `onComplete`.const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6461,6 +6478,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should skip real execution when beforeToolCall returns mock', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6501,6 +6520,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should preserve failed mock results without executing the real tool', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6541,6 +6562,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6570,6 +6593,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should derive callIndex from state.usage.tools.byTool', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6622,6 +6647,8 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {it('should dispatch beforeCompact and afterCompact hooks', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),@@ -6660,9 +6687,51 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {});describe('request_human_approve hooks', () => {+ it('creates an empty result slot before a human answer can be claimed', async () => {+ const state = createToolState({+ messages: [{ content: '', id: 'asst-1', role: 'assistant' }],+ });+ const dispatcher = new HookDispatcher();+ dispatcher.register('op-123', [+ {+ id: 'result-control',+ type: 'afterToolCall',+ webhook: { url: 'https://hooks.example/policy', responseHandling: 'toolCall' },+ },+ ]);+ const executors = createRuntimeExecutors({+ ...ctx,+ hookDispatcher: dispatcher,+ loadAgentState: async () => state,+ });+ await executors.request_human_approve!(+ {+ type: 'request_human_approve',+ pendingToolsCalling: [+ {+ apiName: 'ask',+ arguments: '{}',+ id: 'call-ask',+ identifier: 'questions',+ type: 'builtin',+ },+ ],+ },+ state,+ );+ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ content: '',+ tool_call_id: 'call-ask',+ }),+ );+ });+it('should dispatch beforeHumanIntervention hook', async () => {const mockDispatcher = {dispatch: vi.fn().mockResolvedValue(undefined),+ hasAfterToolCallControl: vi.fn().mockReturnValue(false),+ evaluateAfterToolCall: vi.fn().mockResolvedValue({ status: 'allow' }),evaluateToolCall: vi.fn().mockResolvedValue({status: 'allow',}),diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.groupMember.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.groupMember.test.tsindex ea1b7d1c685..3a71c9111f6 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.groupMember.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.groupMember.test.ts@@ -31,6 +31,94 @@ describe('resolveGroupMemberId', () => {// G-05: the member runner hands the supervisor run's approval policy to every// forked member instead of letting them fall back to headless.describe('buildServerAgentMemberRunner', () => {+ it.each(['allow', 'blocked'] as const)(+ 'publishes a failed member start only after its hook returns %s while its sibling starts',+ async (status) => {+ const rows: Record<string, any>[] = [];+ const onGroupMemberResult = vi.fn(async () => {+ expect(rows[1].content).not.toBe('');+ return true;+ });+ let decide!: (value: { status: 'allow' | 'blocked' }) => void;+ const decision = new Promise<{ status: 'allow' | 'blocked' }>((resolve) => {+ decide = resolve;+ });+ let entered!: () => void;+ const hookEntered = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const evaluateAfterToolCall = vi.fn(async () => {+ entered();+ return decision;+ });+ const messageModel = {+ create: vi.fn(async (value) => {+ const row = { ...value, id: `row-${rows.length}` };+ rows.push(row);+ return row;+ }),+ findById: vi.fn(async (id) => rows.find((row) => row.id === id)),+ findMessagePlugin: vi.fn(async (id) => {+ const row = rows.find((row) => row.id === id);+ return row && { ...row.plugin, toolCallId: row.tool_call_id, state: row.pluginState };+ }),+ updateToolMessage: vi.fn(async (id, value) => {+ Object.assign(+ rows.find((row) => row.id === id)!,+ value,+ );+ return { success: true };+ }),+ };+ const runner = buildServerAgentMemberRunner(+ {+ execGroupMember: vi.fn(async ({ agentId }) => ({ started: agentId === 'sibling' })),+ hookDispatcher: { hasAfterToolCallControl: () => true, evaluateAfterToolCall },+ messageModel,+ onGroupMemberResult,+ operationId: 'op-sup',+ topicId: 'topic',+ userId: 'owner',+ } as unknown as RuntimeExecutorContext,+ {+ origin: { agentId: 'supervisor', groupId: 'group', topicId: 'topic' },+ } as AgentState,+ {+ apiName: 'executeAgentTasks',+ identifier: 'lobe-group-management',+ arguments: '{}',+ id: 'call',+ type: 'builtin',+ },+ 'assistant',+ )!;+ const run = runner.run({+ members: [+ { agentId: 'failed', instruction: 'go' },+ { agentId: 'sibling', instruction: 'go' },+ ],+ mode: 'in_group',+ onComplete: 'resume',+ });+ await Promise.race([hookEntered, run]);+ expect(evaluateAfterToolCall).toHaveBeenCalledTimes(1);+ expect(rows.map((row) => row.content)).toEqual(['', '', '']);+ expect(rows.every((row) => !row.metadata?.toolResultControl)).toBe(true);+ expect(messageModel.updateToolMessage).not.toHaveBeenCalled();+ expect(onGroupMemberResult).not.toHaveBeenCalled();+ decide({ status });+ await expect(run).resolves.toMatchObject({ started: true, startedCount: 1 });+ expect(rows[1].content).toBe(+ status === 'allow'+ ? 'Agent member "failed" failed to start.'+ : 'Tool result withheld by afterToolCall hook.',+ );+ expect(rows[0].metadata).toEqual({ agentCouncil: true });+ expect(rows[2].content).toBe('');+ expect(onGroupMemberResult).toHaveBeenCalledTimes(1);+ },+ );+it('forwards the supervisor approval policy to each member', async () => {const execGroupMember = vi.fn().mockResolvedValue({ operationId: 'op-m', started: true });const ctx = {diff --git a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.tsindex 9c297e191e7..fed29d59427 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/executorHelpers.subAgentModel.test.ts@@ -84,6 +84,36 @@ describe('buildServerVirtualSubAgentRunner sub-agent model resolution', () => {// either runner does not inherit the parent's shareGate, so for a run with// `ctx.agentShareVisitor` set, no runner may be built at all.describe('buildServerVirtualSubAgentRunner continuing an earlier sub-agent', () => {+ it('quarantines the placeholder before a child can write an early completion', async () => {+ const create = vi.fn().mockResolvedValue({ id: 'placeholder' });+ const execVirtualSubAgent = vi.fn(async () => {+ expect(create).toHaveBeenCalledWith(+ expect.objectContaining({+ content: '',+ }),+ );+ return { operationId: 'child', success: true, threadId: 'thread' };+ });+ const runner = buildServerVirtualSubAgentRunner(+ {+ operationId: 'op',+ stepIndex: 4,+ topicId: 'topic',+ execVirtualSubAgent,+ messageModel: { create },+ hookDispatcher: { hasAfterToolCallControl: () => true },+ } as unknown as RuntimeExecutorContext,+ {+ origin: { agentId: 'agent', topicId: 'topic' },+ usage: { tools: { byTool: [{ name: 'lobe-agent/callSubAgent', calls: 1 }] } },+ } as AgentState,+ { id: 'call', identifier: 'lobe-agent', apiName: 'callSubAgent' } as ChatToolPayload,+ 'assistant',+ );+ await runner!.run({ description: 'task', instruction: 'run' });+ expect(execVirtualSubAgent).toHaveBeenCalledTimes(1);+ });+it('reuses the sub-agent thread and links the new placeholder to it', async () => {const execVirtualSubAgent = vi.fn()diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.tsindex 31f97cd1648..884491150fe 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.test.ts@@ -62,6 +62,20 @@ describe('ServerMessageTransport', () => {expect(messageModel.findByClientId).toHaveBeenCalledWith(options.idempotencyKey);});+ it('does not allow a denied result into model context when its durable replacement failed', async () => {+ const messageModel = {+ updateToolMessage: vi.fn().mockResolvedValue({ success: false }),+ } as unknown as MessageModel;+ const transport = new ServerMessageTransport(messageModel);+ await expect(+ transport.updateToolMessage('tool-row', {+ content: 'withheld',+ replacePluginState: true,+ pluginState: { phase: 'afterToolCall', type: 'blocked' },+ }),+ ).rejects.toThrow('Failed to persist tool result');+ });+it('does not swallow an unrelated unique constraint violation', async () => {const error = createUniqueViolation('messages_pkey');const messageModel = {diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.tsindex 40108cfe6db..b39c892a97b 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerMessageTransport.ts@@ -148,6 +148,9 @@ export class ServerMessageTransport implements MessageTransport {}async updateToolMessage(id: string, params: UpdateToolMessageInput): Promise<void> {- await this.messageModel.updateToolMessage(id, params);+ const result = await this.messageModel.updateToolMessage(id, params);+ if (!result.success) {+ throw new Error('Failed to persist tool result');+ }}}diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.tsindex fc80fb01b7f..0d7a0790070 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts@@ -19,7 +19,13 @@ import {import type { ChatToolPayload } from '@lobechat/types';import { AgentModel } from '@/database/models/agent';+import { AgentOperationModel } from '@/database/models/agentOperation';import { isDeviceCapablePlan, isLocalSandboxEnabled } from '@/helpers/executionTarget';+import {+ controlDeferredToolResult,+ loadDurableToolResultHooks,+} from '@/server/services/agentRuntime/hooks/deferredToolResultControl';+import { controlToolResult } from '@/server/services/agentRuntime/hooks/toolResultControl';import type { DeviceAccessReason } from '@/server/services/aiAgent/deviceToolAudit';import {isDeviceToolIdentifier,@@ -336,17 +342,79 @@ export class ServerToolTransport implements ToolTransport {...execution.result,executionTime: execution.result.executionTime ?? 0,};- const executionResult = await archiveRuntimeToolResult(resultWithExecutionTime, {- agentId: context.state.origin?.agentId,- canReadArchive: enabledToolIds.includes(AgentDocumentsIdentifier),- identifier: chatToolPayload.identifier,- limit: context.toolResultMaxLength,- serverDB,- toolCallId: chatToolPayload.id,- topicId: this.ctx.topicId ?? context.state.origin?.topicId,- userId,- workspaceId: context.state.origin?.workspaceId ?? this.ctx.workspaceId,- });+ // Evaluate the full result before truncation/archive creation. A denied+ // archive must not remain retrievable by the model on a later tool call.+ const originalOperationId = context.toolMessageId+ ? (await this.ctx.messageModel.findMessagePlugin(context.toolMessageId))?.intervention+ ?.operationId+ : undefined;+ let originalControl: Awaited<ReturnType<typeof controlDeferredToolResult>> | undefined;+ if (originalOperationId && context.toolMessageId) {+ if (!this.ctx.hookDispatcher || !this.ctx.userId) {+ throw new Error(+ 'Cannot review a resumed tool result without its runtime owner and dispatcher',+ );+ }+ originalControl = await controlDeferredToolResult(+ {+ dispatcher: this.ctx.hookDispatcher,+ loadState: (operationId) =>+ operationId === this.ctx.operationId+ ? Promise.resolve(context.state)+ : (this.ctx.loadAgentState?.(operationId) ?? Promise.resolve(null)),+ loadDurableHooks: (operationId) =>+ loadDurableToolResultHooks(+ new AgentOperationModel(this.ctx.serverDB, this.ctx.userId!, this.ctx.workspaceId),+ operationId,+ ),+ messageModel: this.ctx.messageModel,+ userId: this.ctx.userId,+ workspaceId: this.ctx.workspaceId,+ },+ {+ operationId: originalOperationId,+ includeServerHooks: originalOperationId === this.ctx.operationId,+ toolMessageId: context.toolMessageId,+ result: resultWithExecutionTime,+ signal: context.abortSignal,+ },+ );+ }+ // Approval continuations need not inherit caller hooks. Keep the original+ // gate; any new run controls can only narrow its decision. Never infer+ // a control decision from the untrusted tool's result.state fields.+ const controlled =+ originalControl && (originalControl.blocked || originalOperationId === this.ctx.operationId)+ ? originalControl+ : await controlToolResult(+ this.ctx.hookDispatcher,+ {+ ...buildToolCallHookContext(chatToolPayload, context, this.ctx),+ mocked: toolCallMocked || !!execution.mocked,+ result: originalControl?.result ?? resultWithExecutionTime,+ },+ context.state.host?.hooks,+ context.abortSignal,+ );+ if (controlled.cancelled) {+ return { ...execution, interrupted: true, result: controlled.result };+ }+ const executionResult = controlled.blocked+ ? controlled.result+ : await archiveRuntimeToolResult(+ { ...controlled.result, executionTime: controlled.result.executionTime ?? 0 },+ {+ agentId: context.state.origin?.agentId,+ canReadArchive: enabledToolIds.includes(AgentDocumentsIdentifier),+ identifier: chatToolPayload.identifier,+ limit: context.toolResultMaxLength,+ serverDB,+ toolCallId: chatToolPayload.id,+ topicId: this.ctx.topicId ?? context.state.origin?.topicId,+ userId,+ workspaceId: context.state.origin?.workspaceId ?? this.ctx.workspaceId,+ },+ );await this.dispatchAfterToolCall(chatToolPayload, context, executionResult, toolCallMocked);@@ -361,6 +429,7 @@ export class ServerToolTransport implements ToolTransport {...execution,mocked: toolCallMocked || execution.mocked,result: executionResult,+ resultBlocked: controlled.blocked,};} catch (error) {executeToolSpan.recordException(error as Error);diff --git a/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.tsnew file mode 100644index 00000000000..1b44b15121d--- /dev/null+++ b/apps/server/src/modules/AgentRuntime/adapters/afterToolControlPipeline.test.ts@@ -0,0 +1,778 @@+import type { AgentRuntimeHost, AgentState, ToolCallHookEvent } from '@lobechat/agent-runtime';+import {+ AgentRuntime,+ createAgentRuntimeExecutors,+ GeneralChatAgent,+} from '@lobechat/agent-runtime';+import type { ChatToolPayload } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { AgentHook } from '@/server/services/agentRuntime/hooks';+import { HookDispatcher } from '@/server/services/agentRuntime/hooks';+import { BLOCKED_TOOL_RESULT_CONTENT } from '@/server/services/agentRuntime/hooks/toolResultControl';++import type { RuntimeExecutorContext } from '../context';+import { ServerToolTransport } from './ServerToolTransport';++const { archive, dispatchClient, fetchHook, getEmailsByIds, queueMode } = vi.hoisted(() => ({+ archive: vi.fn(async (result) => result),+ dispatchClient: vi.fn(),+ fetchHook: vi.fn(),+ getEmailsByIds: vi.fn(),+ queueMode: vi.fn(),+}));+vi.mock('../dispatchClientTool', () => ({ dispatchClientTool: dispatchClient }));+vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds } }));+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: queueMode }));+vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));+vi.mock('@/database/models/agent', () => ({+ AgentModel: class {+ getAgentVisibility = async () => 'private';+ },+}));+vi.mock('../executorHelpers', () => ({+ archiveRuntimeToolResult: archive,+ buildServerAgentMemberRunner: () => undefined,+ buildServerVirtualSubAgentRunner: () => undefined,+ GEN_AI_FUNCTION_TOOL_TYPE: 'function',+ isOperationInterrupted: async () => false,+ log: () => {},+ registerWorkFromIntent: vi.fn(),+ TOOL_MAX_RETRIES: 2,+ TOOL_PRICING: { 'fs/write': 5 },+}));++const call = (id = 'native-1'): ChatToolPayload => ({+ id,+ apiName: 'write',+ identifier: 'fs',+ arguments: '{"path":"a"}',+ type: 'builtin',+});+const control = (id = 'control', onError: 'continue' | 'block' = 'continue') =>+ ({+ id,+ type: 'afterToolCall',+ webhook: { url: `https://hooks.example/${id}`, responseHandling: 'toolCall', onError },+ }) satisfies AgentHook;+const response = (decision: 'allow' | 'deny', reason?: string) =>+ new Response(JSON.stringify(decision === 'deny' ? { decision, reason } : { decision }));++function setup(hooks: AgentHook[], signal?: AbortSignal, restore = false) {+ const registered = new HookDispatcher();+ registered.register('op', hooks);+ const dispatcher = restore ? new HookDispatcher() : registered;+ const execute = vi.fn().mockResolvedValue({ content: 'executed', success: true });+ const rows: Record<string, unknown>[] = [];+ const loadState = vi.fn().mockResolvedValue(null);+ const state: AgentState = {+ cost: {+ calculatedAt: '',+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ },+ createdAt: '',+ lastModified: '',+ messages: [],+ operationId: 'op',+ status: 'running',+ stepCount: 0,+ origin: { agentId: 'agent', topicId: 'topic' },+ // Serialize to model a worker boundary, not merely an in-memory clone.+ // eslint-disable-next-line unicorn/prefer-structured-clone+ host: { hooks: JSON.parse(JSON.stringify(registered.getSerializedHooks('op') ?? [])) },+ userInterventionConfig: { approvalMode: 'auto-run' },+ };+ const transport = new ServerToolTransport({+ operationId: 'op',+ stepIndex: 1,+ userId: 'user',+ hookDispatcher: dispatcher,+ abortSignal: signal,+ serverDB: {},+ streamManager: { sendToolExecute: vi.fn() },+ toolExecutionService: { executeTool: execute },+ loadAgentState: loadState,+ messageModel: {+ findById: async (id: string) => rows.find((row) => row.id === id),+ findMessagePlugin: async (id: string) => {+ const row = rows.find((row) => row.id === id);+ return row+ ? {+ ...call(),+ toolCallId: row.tool_call_id,+ state: row.pluginState,+ intervention: row.pluginIntervention,+ ...(row.plugin as Record<string, unknown>),+ }+ : undefined;+ },+ },+ } as unknown as RuntimeExecutorContext);+ const host: AgentRuntimeHost = {+ operation: { operationId: 'op', stepIndex: 1, agentId: 'agent', abortSignal: signal },+ transports: {+ tools: transport,+ messages: {+ createToolMessage: vi.fn(async (row) => {+ const persisted = { ...row, id: `row-${rows.length + 1}` };+ rows.push(persisted);+ return persisted;+ }),+ query: vi.fn(async () => rows),+ updateToolMessage: vi.fn(async (id, update) => {+ const row = rows.find((row) => row.id === id);+ if (row) Object.assign(row, update);+ }),+ updateToolIntervention: vi.fn(),+ update: vi.fn(),+ findToolMessageIdByToolCallId: vi.fn(),+ } as unknown as AgentRuntimeHost['transports']['messages'],+ stream: { publishEvent: vi.fn(), publishChunk: vi.fn() },+ },+ };+ const executors = createAgentRuntimeExecutors(host);+ const runtime = new AgentRuntime(new GeneralChatAgent({ operationId: 'op' }), {+ executors,+ });+ const step = (calls = [call()]) =>+ runtime.step(state, {+ phase: 'llm_result',+ payload: { hasToolsCalling: true, parentMessageId: 'assistant', toolsCalling: calls },+ });+ return { dispatcher, execute, executors, host, rows, runtime, state, step, loadState };+}++beforeEach(() => {+ vi.stubGlobal('fetch', fetchHook);+ archive.mockClear().mockImplementation(async (result) => result);+ getEmailsByIds.mockReset().mockResolvedValue([]);+ fetchHook.mockReset().mockImplementation(async () => response('allow'));+ queueMode.mockReturnValue(false);+ dispatchClient.mockReset().mockResolvedValue({ content: 'client result', success: true });+});+afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+});++describe('afterToolCall control pipeline', () => {+ const secret = 'synthetic-sensitive-result';+ const raw = () => ({+ content: secret.repeat(1000),+ error: { message: secret, type: 'tool_error' },+ executionTime: 42,+ state: {+ images: [{ url: `https://files.example/${secret}`, mediaType: 'image/png' }],+ nested: { text: secret },+ totalCost: 123456789,+ },+ success: true,+ workRegistration: {+ type: 'skill' as const,+ args: { path: 'a' },+ data: { text: secret },+ provider: 'synthetic',+ toolName: 'read',+ },+ });++ it.each([false, true])(+ 'withholds the full result before persistence and LLM continuation, queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ fetchHook.mockImplementation(async () => response('deny', secret));+ const fixture = setup([control()], undefined, true);+ fixture.execute.mockResolvedValue(raw());+ const result = await fixture.step();++ expect(fixture.execute).toHaveBeenCalledTimes(1);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({+ args: { path: 'a' },+ hookType: 'afterToolCall',+ toolCallId: 'native-1',+ result: raw(),+ });+ expect(fixture.rows).toEqual([+ expect.objectContaining({+ content: BLOCKED_TOOL_RESULT_CONTENT,+ pluginError: 'hook_denied',+ pluginState: {+ type: 'blocked',+ phase: 'afterToolCall',+ reason: BLOCKED_TOOL_RESULT_CONTENT,+ },+ tool_call_id: 'native-1',+ }),+ ]);+ expect(JSON.stringify(result)).not.toContain(secret);+ 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(archive).not.toHaveBeenCalled();+ expect(result.newState.cost?.tools.total).toBe(5);+ expect(fixture.host.transports.stream.publishEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'tool_end',+ data: expect.objectContaining({ attempts: 1, maxAttempts: 3, executionTime: 42 }),+ }),+ );+ },+ );++ it.each(['server', 'client'] as const)(+ 'carries the allowed verdict separately from %s result state',+ async (executor) => {+ const fixture = setup([control()]);+ const result = {+ content: 'allowed output',+ success: true,+ state: { phase: 'afterToolCall', type: 'blocked' },+ };+ if (executor === 'client') {+ dispatchClient.mockResolvedValue(result);+ }+ fixture.execute.mockResolvedValue(result);+ await fixture.step([{ ...call(), ...(executor === 'client' && { executor: 'client' }) }]);+ expect(dispatchClient).toHaveBeenCalledTimes(executor === 'client' ? 1 : 0);+ expect(fixture.execute).toHaveBeenCalledTimes(executor === 'server' ? 1 : 0);+ expect(fixture.rows[0]).toMatchObject({+ content: 'allowed output',+ });+ expect(fixture.rows[0].pluginIntervention).toBeUndefined();+ },+ );++ it('inspects complete output before archiving an allowed result', async () => {+ const fixture = setup([control()]);+ fixture.execute.mockResolvedValue(raw());+ archive.mockImplementation(async (result) => ({ ...result, content: 'archived preview' }));+ const result = await fixture.step();+ expect(JSON.parse(fetchHook.mock.calls[0][1].body).result).toEqual(raw());+ expect(archive.mock.calls[0][0]).toEqual(raw());+ expect(fixture.rows[0].content).toBe('archived preview');+ expect(result.newState.messages[0].content).toBe('archived preview');+ });++ it('holds all model-facing output while the result decision is pending', async () => {+ let resolve!: (value: Response) => void;+ fetchHook.mockImplementation(+ () =>+ new Promise<Response>((done) => {+ resolve = done;+ }),+ );+ const fixture = setup([control()]);+ fixture.execute.mockResolvedValue(raw());+ const running = fixture.step();+ await vi.waitFor(() => expect(fetchHook).toHaveBeenCalledTimes(1));+ expect(fixture.rows).toHaveLength(0);+ expect(archive).not.toHaveBeenCalled();+ expect(fixture.host.transports.stream.publishEvent).not.toHaveBeenCalledWith(+ expect.objectContaining({ type: 'tool_end' }),+ );+ resolve(response('deny'));+ await running;+ expect(fixture.rows[0].content).toBe(BLOCKED_TOOL_RESULT_CONTENT);+ });++ it.each(['server', 'client', 'mock'] as const)(+ 'gates %s results without re-execution',+ async (source) => {+ const hooks: AgentHook[] = [control()];+ if (source === 'mock')+ hooks.push({+ id: 'mock',+ type: 'beforeToolCall',+ handler: async (event) => {+ (event as ToolCallHookEvent).mock(raw());+ },+ });+ const fixture = setup(hooks);+ fixture.execute.mockResolvedValue(raw());+ dispatchClient.mockResolvedValue(raw());+ fetchHook.mockImplementation(async () => response('deny'));+ const result = await fixture.step([+ { ...call(), ...(source === 'client' && { executor: 'client' }) },+ ]);+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({+ mocked: source === 'mock',+ result: raw(),+ });+ expect(fixture.execute).toHaveBeenCalledTimes(source === 'server' ? 1 : 0);+ expect(dispatchClient).toHaveBeenCalledTimes(source === 'client' ? 1 : 0);+ expect(JSON.stringify(result)).not.toContain(secret);+ },+ );++ it.each(['continue', 'block'] as const)(+ 'uses onError=%s for invalid responses and never leaks response text',+ async (onError) => {+ const fixture = setup([control('control', onError)]);+ fetchHook.mockResolvedValue(new Response(JSON.stringify({ invalid: 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(JSON.stringify(result)).not.toContain(secret);+ },+ );++ it.each(['continue', 'block'] as const)(+ 'respects the hook timeout with onError=%s',+ async (onError) => {+ const fixture = setup([+ {+ ...control('control', onError),+ webhook: {+ url: 'https://hooks.example/timeout',+ responseHandling: 'toolCall',+ onError,+ timeout: 0.02,+ },+ },+ ]);+ fetchHook.mockImplementation(+ (_url, request) =>+ new Promise((_resolve, reject) => {+ request.signal.addEventListener('abort', () => reject(new Error(secret)), {+ once: true,+ });+ }),+ );+ const result = await fixture.step();+ expect(fixture.rows[0].content).toBe(+ onError === 'block' ? BLOCKED_TOOL_RESULT_CONTENT : 'executed',+ );+ 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 () => {+ const fixture = setup([+ control('allow'),+ { ...control('skip'), matcher: '^other/' },+ control('deny'),+ control('unreached'),+ ]);+ fixture.execute.mockResolvedValue({ ...raw(), stop: true });+ fetchHook.mockImplementation(async (url) =>+ response(String(url).endsWith('/deny') ? 'deny' : 'allow', secret),+ );+ const result = await fixture.step();+ expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([+ 'https://hooks.example/allow',+ 'https://hooks.example/deny',+ ]);+ expect(result.newState.status).toBe('done');+ expect(JSON.stringify(result)).not.toContain(secret);+ });++ it('evaluates a failed result after the last tool retry only', async () => {+ const fixture = setup([control()]);+ fixture.execute.mockResolvedValue({+ ...raw(),+ success: false,+ error: { kind: 'retry', message: secret },+ });+ fetchHook.mockImplementation(async () => response('deny'));+ const result = await fixture.step();+ expect(fixture.execute).toHaveBeenCalledTimes(3);+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body).result.success).toBe(false);+ expect(JSON.stringify(result)).not.toContain(secret);+ expect(result.newState.cost?.tools.total).toBe(5);+ });++ it('keeps native IDs paired and mixed parallel siblings isolated', async () => {+ const fixture = setup([control()]);+ fixture.execute.mockImplementation(async (tool) => ({+ content: tool.id === 'constructor' ? secret : 'allowed sibling',+ success: true,+ }));+ fetchHook.mockImplementation(async (_url, request) =>+ response(JSON.parse(request.body).toolCallId === 'constructor' ? 'deny' : 'allow'),+ );+ const result = await fixture.step([call('constructor'), call('__proto__')]);+ expect(fixture.rows).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ tool_call_id: 'constructor',+ content: BLOCKED_TOOL_RESULT_CONTENT,+ }),+ expect.objectContaining({ tool_call_id: '__proto__', content: 'allowed sibling' }),+ ]),+ );+ expect(JSON.stringify(result)).not.toContain(secret);+ expect(result.newState.cost?.tools.total).toBe(10);+ expect(fetchHook).toHaveBeenCalledTimes(2);+ });++ it.each(['single', 'batch'] as const)(+ 'replaces the durable result on a reused %s row',+ async (mode) => {+ const fixture = setup([control()]);+ fixture.rows.push({+ id: 'existing-row',+ role: 'tool',+ tool_call_id: 'native-1',+ content: secret,+ pluginState: { images: [{ url: secret }] },+ });+ fixture.execute.mockResolvedValue(raw());+ fetchHook.mockImplementation(async () => response('deny'));+ const result =+ mode === 'single'+ ? await fixture.executors.call_tool!(+ {+ type: 'call_tool',+ payload: {+ parentMessageId: 'existing-row',+ skipCreateToolMessage: true,+ toolCalling: call(),+ },+ },+ fixture.state,+ )+ : await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: {+ parentMessageId: 'assistant',+ toolsCalling: [call()],+ existingToolMessageIds: { 'native-1': 'existing-row' },+ },+ },+ fixture.state,+ );+ expect(fixture.rows).toHaveLength(1);+ expect(fixture.host.transports.messages.updateToolMessage).toHaveBeenCalledWith(+ 'existing-row',+ expect.objectContaining({ replacePluginState: true, content: BLOCKED_TOOL_RESULT_CONTENT }),+ );+ expect(JSON.stringify(await fixture.host.transports.messages.query())).not.toContain(secret);+ expect(JSON.stringify(result)).not.toContain(secret);+ },+ );++ it.each(['single', 'batch'] as const)(+ 'keeps the original result control after a %s approval creates a hook-less continuation',+ async (mode) => {+ const fixture = setup([]);+ fixture.rows.push({+ id: 'protected-row',+ parentId: 'original-assistant',+ role: 'tool',+ tool_call_id: 'native-1',+ content: '',+ plugin: call(),+ pluginIntervention: { operationId: 'original-op', status: 'approved' },+ });+ fixture.loadState.mockResolvedValue({+ ...fixture.state,+ operationId: 'original-op',+ host: { hooks: [control()] },+ });+ fixture.execute.mockResolvedValue(raw());+ fetchHook.mockImplementation(async () => response('deny'));+ const result =+ mode === 'single'+ ? await fixture.executors.call_tool!(+ {+ type: 'call_tool',+ payload: {+ parentMessageId: 'protected-row',+ skipCreateToolMessage: true,+ toolCalling: call(),+ },+ },+ fixture.state,+ )+ : await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: {+ parentMessageId: 'assistant',+ toolsCalling: [call()],+ existingToolMessageIds: { 'native-1': 'protected-row' },+ },+ },+ fixture.state,+ );+ expect(fixture.execute).toHaveBeenCalledTimes(1);+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({+ operationId: 'original-op',+ result: raw(),+ });+ expect(JSON.stringify(result)).not.toContain(secret);+ expect(JSON.stringify(fixture.rows)).not.toContain(secret);+ expect(archive).not.toHaveBeenCalled();+ },+ );++ it.each(['single', 'batch'] as const)(+ 'evaluates the environment once after the original caller in an allowed %s continuation',+ async (mode) => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/environment');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');+ const fixture = setup([]);+ fixture.rows.push({+ id: 'protected-row',+ parentId: 'original-assistant',+ role: 'tool',+ tool_call_id: 'native-1',+ content: '',+ plugin: call(),+ pluginIntervention: { operationId: 'original-op', status: 'approved' },+ });+ fixture.loadState.mockResolvedValue({+ ...fixture.state,+ operationId: 'original-op',+ host: { hooks: [control()] },+ });+ fetchHook.mockImplementation(async () => response('allow'));+ if (mode === 'single') {+ await fixture.executors.call_tool!(+ {+ type: 'call_tool',+ payload: {+ parentMessageId: 'protected-row',+ skipCreateToolMessage: true,+ toolCalling: call(),+ },+ },+ fixture.state,+ );+ } else {+ await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: {+ parentMessageId: 'assistant',+ toolsCalling: [call()],+ existingToolMessageIds: { 'native-1': 'protected-row' },+ },+ },+ fixture.state,+ );+ }+ expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([+ 'https://hooks.example/control',+ 'https://hooks.example/environment',+ ]);+ expect(fixture.host.transports.messages.updateToolMessage).toHaveBeenCalledWith(+ 'protected-row',+ expect.objectContaining({ content: 'executed', pluginError: null }),+ );+ expect(fixture.rows[0].content).toBe('executed');+ },+ );++ it.each(['single', 'batch'] as const)(+ 'publishes a %s result when the environment control has been removed',+ async (mode) => {+ const fixture = setup([]);+ fixture.rows.push({+ id: 'protected-row',+ parentId: 'original-assistant',+ role: 'tool',+ tool_call_id: 'native-1',+ content: '',+ plugin: call(),+ pluginIntervention: { operationId: 'original-op', status: 'approved' },+ });+ fixture.loadState.mockResolvedValue({ ...fixture.state, operationId: 'original-op' });+ if (mode === 'single') {+ await fixture.executors.call_tool!(+ {+ type: 'call_tool',+ payload: {+ parentMessageId: 'protected-row',+ skipCreateToolMessage: true,+ toolCalling: call(),+ },+ },+ fixture.state,+ );+ } else {+ await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: {+ parentMessageId: 'assistant',+ toolsCalling: [call()],+ existingToolMessageIds: { 'native-1': 'protected-row' },+ },+ },+ fixture.state,+ );+ }+ expect(fetchHook).not.toHaveBeenCalled();+ expect(archive).toHaveBeenCalled();+ expect(fixture.host.transports.messages.updateToolMessage).toHaveBeenCalledWith(+ 'protected-row',+ expect.objectContaining({ content: 'executed', pluginError: null }),+ );+ expect(fixture.rows[0].content).toBe('executed');+ },+ );++ it('does not trust tool state to bypass a continuationβs additional control', async () => {+ const fixture = setup([control('new-policy')]);+ fixture.rows.push({+ id: 'protected-row',+ parentId: 'original-assistant',+ role: 'tool',+ tool_call_id: 'native-1',+ content: '',+ plugin: call(),+ pluginIntervention: { operationId: 'original-op', status: 'approved' },+ });+ fixture.loadState.mockResolvedValue({+ ...fixture.state,+ operationId: 'original-op',+ host: { hooks: [control('original-policy')] },+ });+ fixture.execute.mockResolvedValue({+ ...raw(),+ state: { phase: 'afterToolCall', type: 'blocked' },+ });+ fetchHook.mockImplementation(async (url) =>+ response(String(url).endsWith('/original-policy') ? 'allow' : 'deny'),+ );+ const result = await fixture.executors.call_tool!(+ {+ type: 'call_tool',+ payload: {+ parentMessageId: 'protected-row',+ skipCreateToolMessage: true,+ toolCalling: call(),+ },+ },+ fixture.state,+ );+ expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([+ 'https://hooks.example/original-policy',+ 'https://hooks.example/new-policy',+ ]);+ expect(JSON.stringify(result)).not.toContain(secret);+ expect(archive).not.toHaveBeenCalled();+ });++ it('preserves ordered execution lanes while withholding only the denied result', async () => {+ const fixture = setup([control()]);+ fixture.state.toolManifestMap = { fs: { api: [{ name: 'write', ordered: true }] } };+ const order: string[] = [];+ fixture.execute.mockImplementation(async (tool) => {+ order.push(`run:${tool.id}`);+ return { content: tool.id, success: true };+ });+ fetchHook.mockImplementation(async (_url, init) => {+ const id = JSON.parse(init.body).toolCallId;+ order.push(`control:${id}`);+ return response(id === 'two' ? 'deny' : 'allow');+ });+ await fixture.executors.call_tools_batch!(+ {+ type: 'call_tools_batch',+ payload: {+ parentMessageId: 'assistant',+ toolsCalling: [call('one'), call('two'), call('three')],+ },+ },+ fixture.state,+ );+ expect(order).toEqual([+ 'run:one',+ 'control:one',+ 'run:two',+ 'control:two',+ 'run:three',+ 'control:three',+ ]);+ expect(fixture.rows.map((row) => row.content)).toEqual([+ 'one',+ BLOCKED_TOOL_RESULT_CONTENT,+ 'three',+ ]);+ });++ it.each(['toolCall', 'toolResult', 'toolCallAndResult'] as const)(+ 'applies the explicit environment mode %s at runtime',+ async (mode) => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/env');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-token');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'beforeToolCall,afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', mode);+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');+ fetchHook.mockImplementation(async (_url, init) =>+ response(JSON.parse(init.body).hookType === 'afterToolCall' ? 'deny' : 'allow'),+ );+ const fixture = setup([]);+ await fixture.step();+ expect(fixture.execute).toHaveBeenCalledTimes(1);+ expect(fixture.rows[0].content).toBe(+ mode === 'toolCall' ? 'executed' : BLOCKED_TOOL_RESULT_CONTENT,+ );+ await vi.waitFor(() => expect(fetchHook).toHaveBeenCalledTimes(2));+ expect(fetchHook.mock.calls.map(([, init]) => JSON.parse(init.body).hookType)).toEqual([+ 'beforeToolCall',+ 'afterToolCall',+ ]);+ },+ );++ it('does not review deferred placeholders as completed tool results', async () => {+ const fixture = setup([control()]);+ fixture.execute.mockResolvedValue({+ content: '',+ deferred: true,+ state: { toolMessageId: 'pending' },+ success: true,+ });+ const result = await fixture.step();+ expect(result.newState.status).toBe('waiting_for_async_tool');+ expect(fetchHook).not.toHaveBeenCalled();+ });++ it('cancels a pending decision without letting continue release the result', async () => {+ const abort = new AbortController();+ fetchHook.mockImplementation(+ (_url, request) =>+ new Promise((_resolve, reject) => {+ request.signal.addEventListener('abort', () => reject(new Error(secret)), { once: true });+ }),+ );+ const fixture = setup([control('control', 'continue')], abort.signal);+ fixture.execute.mockResolvedValue(raw());+ const running = fixture.step();+ await vi.waitFor(() => expect(fetchHook).toHaveBeenCalledTimes(1));+ abort.abort();+ const result = await running;+ expect(JSON.stringify(result)).not.toContain(secret);+ expect(JSON.stringify(fixture.rows)).not.toContain(secret);+ expect(archive).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.tsindex 037d5f4cb52..f83e96b5390 100644--- a/apps/server/src/modules/AgentRuntime/context.ts+++ b/apps/server/src/modules/AgentRuntime/context.ts@@ -12,6 +12,7 @@ import type { HookDispatcher } from '@/server/services/agentRuntime/hooks/HookDiimport type {ExecGroupMemberParams,ExecGroupMemberResult,+ GroupActionMemberBridgeParams,} from '@/server/services/agentRuntime/types';import { type ToolExecutionService } from '@/server/services/toolExecution';@@ -63,6 +64,13 @@ export interface RuntimeExecutorContext {loadAgentState?: (operationId: string) => Promise<AgentState | null>;messageModel: MessageModel;modelRuntimeConfig?: AgentState['modelRuntimeConfig'];+ /** Check the shared completion barrier after a startup-failure receipt is published. */+ onGroupMemberResult?: (+ params: Pick<+ GroupActionMemberBridgeParams,+ 'anchorMessageId' | 'expectedMembers' | 'groupToolMessageId' | 'parentOperationId'+ >,+ ) => Promise<boolean>;operationId: string;serverDB: LobeChatDatabase;stepIndex: number;diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 6b20c10c3b8..91eb991db78 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -1,4 +1,8 @@-import { type AgentState, selectUserInterventionConfig } from '@lobechat/agent-runtime';+import {+ type AgentState,+ selectUserInterventionConfig,+ type ToolRunResult,+} from '@lobechat/agent-runtime';import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';import { dispatchWorkRegistrationIntent } from '@lobechat/builtin-tools/workRegistration';import { getSubAgentChatConfigOverride, resolveSubAgentModel } from '@lobechat/const';@@ -12,8 +16,13 @@ import {} from '@lobechat/types';import debug from 'debug';+import { AgentOperationModel } from '@/database/models/agentOperation';import { WorkModel } from '@/database/models/work';import { type LobeChatDatabase } from '@/database/type';+import {+ controlDeferredToolResult,+ loadDurableToolResultHooks,+} from '@/server/services/agentRuntime/hooks/deferredToolResultControl';import { FileService } from '@/server/services/file';import {type ServerAgentMemberRunner,@@ -446,7 +455,9 @@ export const buildServerAgentMemberRunner = (agentId,content: '',groupId,- ...(isCouncil ? { metadata: { agentCouncil: true } } : {}),+ ...(isCouncil && {+ metadata: { agentCouncil: true },+ }),parentId: parentMessageId,plugin: chatToolPayload as any,pluginState: { expectedMembers, onComplete, status: 'pending' },@@ -495,6 +506,7 @@ export const buildServerAgentMemberRunner = (// 3. Fork members.let startedCount = 0;const startErrors: string[] = [];+ const failedAnchorIds: string[] = [];await Promise.all(resolvedMembers.map(async (member, i) => {const anchorMessageId = anchorIds[i];@@ -533,10 +545,46 @@ export const buildServerAgentMemberRunner = (// Member failed to start β its completion bridge will never fire, so// backfill the anchor as errored to keep the K=N barrier reachable.try {- await ctx.messageModel.updateToolMessage(anchorMessageId, {+ const result: ToolRunResult = {content: `Agent member "${member.agentId}" failed to start.`,- pluginState: { status: 'error' },+ state: { status: 'error' },+ success: false,+ };+ const controlled =+ ctx.hookDispatcher && ctx.userId+ ? await controlDeferredToolResult(+ {+ dispatcher: ctx.hookDispatcher,+ loadState: (id) =>+ id === ctx.operationId+ ? Promise.resolve(state)+ : (ctx.loadAgentState?.(id) ?? Promise.resolve(null)),+ loadDurableHooks: (id) =>+ loadDurableToolResultHooks(+ new AgentOperationModel(ctx.serverDB, ctx.userId!, ctx.workspaceId),+ id,+ ),+ messageModel: ctx.messageModel,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ {+ contextToolMessageId: groupTool.id,+ operationId: ctx.operationId,+ toolMessageId: anchorMessageId,+ result,+ },+ )+ : { blocked: false, result };+ const saved = await ctx.messageModel.updateToolMessage(anchorMessageId, {+ content: controlled.result.content,+ pluginError: controlled.result.error ?? null,+ pluginState: controlled.result.state,+ onlyIfEmpty: true,+ ...(controlled.blocked && { replacePluginState: true }),});+ if (!saved.success) throw new Error('Failed to persist member startup failure');+ failedAnchorIds.push(anchorMessageId);} catch (error) {log('buildServerAgentMemberRunner: failed to mark anchor %s as errored: %O',@@ -564,6 +612,16 @@ export const buildServerAgentMemberRunner = (return { errors: startErrors, started: false, startedCount: 0 };}+ // A sibling may complete while the failed member waits on its result hook.+ // Recheck after publishing the last startup receipt so local mode cannot+ // strand the group waiting for a callback that will never arrive.+ if (failedAnchorIds.length)+ await ctx.onGroupMemberResult?.({+ anchorMessageId: failedAnchorIds[0],+ expectedMembers,+ groupToolMessageId: groupTool.id,+ parentOperationId: ctx.operationId,+ });return { started: true, startedCount };},};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.tsindex 772e0b8973b..04622b5f36f 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@@ -205,57 +205,104 @@ afterEach(async () => {await cleanupTestUser(serverDB, userId);vi.clearAllMocks();vi.restoreAllMocks();+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();inMemoryAgentStateManager.clear();inMemoryStreamEventManager.clear();});describe('Server callSubAgent suspend/resume', () => {- it('parks the parent, runs the sub-op, backfills the tool message and resumes', async () => {- // 1: parent emits callSubAgent 2: sub-op final answer 3: parent resume final- let callCount = 0;- mockResponsesCreate.mockImplementation(function () {- callCount++;- if (callCount === 1) return Promise.resolve(createCallSubAgentResponse() as any);- if (callCount === 2) return Promise.resolve(createFinalTextResponse(SUB_AGENT_ANSWER) as any);- return Promise.resolve(createFinalTextResponse(PARENT_FINAL) as any);- });+ it.each([undefined, 'allow', 'deny'] as const)(+ 'publishes the child result after %s control and resumes the parent',+ async (decision) => {+ const pendingContents: (string | null)[] = [];+ const reviewedResults: string[] = [];+ const fetchHook = vi.fn(async (_url: string, init: RequestInit) => {+ const payload = JSON.parse(init.body as string);+ const [placeholder] = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.id, payload.toolMessageId));+ pendingContents.push(placeholder.content);+ reviewedResults.push(payload.result.content);+ return new Response(JSON.stringify({ decision }));+ });+ if (decision) {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/subagent-result');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');+ const originalFetch = globalThis.fetch;+ vi.stubGlobal('fetch', (url: string, init: RequestInit) =>+ String(url) === 'https://hooks.example/subagent-result'+ ? fetchHook(url, init)+ : originalFetch(url, init),+ );+ }+ // 1: parent emits callSubAgent 2: sub-op final answer 3: parent resume final+ let callCount = 0;+ mockResponsesCreate.mockImplementation(function () {+ callCount++;+ if (callCount === 1) return Promise.resolve(createCallSubAgentResponse() as any);+ if (callCount === 2)+ return Promise.resolve(createFinalTextResponse(SUB_AGENT_ANSWER) as any);+ return Promise.resolve(createFinalTextResponse(PARENT_FINAL) as any);+ });- const caller = aiAgentRouter.createCaller(createTestContext());+ const caller = aiAgentRouter.createCaller(createTestContext());- const createResult = await caller.execAgent({- agentId: testAgentId,- prompt: 'Please research the ultimate question and report back.',- });- expect(createResult.success).toBe(true);+ const createResult = await caller.execAgent({+ agentId: testAgentId,+ prompt: 'Please research the ultimate question and report back.',+ });+ expect(createResult.success).toBe(true);- const finalState = await waitForOperationComplete(- inMemoryAgentStateManager,- createResult.operationId,- { maxWaitTime: 20_000 },- );+ const finalState = await waitForOperationComplete(+ inMemoryAgentStateManager,+ createResult.operationId,+ { maxWaitTime: 20_000 },+ );- // Parent resumed and completed- expect(finalState.status).toBe('done');- expect(finalState.pendingToolsCalling ?? []).toHaveLength(0);+ // Parent resumed and completed+ expect(finalState.status).toBe('done');+ expect(finalState.pendingToolsCalling ?? []).toHaveLength(0);- // Three LLM calls: parent-initial, sub-op, parent-resume- expect(mockResponsesCreate).toHaveBeenCalledTimes(3);+ // Three LLM calls: parent-initial, sub-op, parent-resume+ expect(mockResponsesCreate).toHaveBeenCalledTimes(3);- // A child op was spawned and reconciled to the parent- const childOps = await serverDB- .select()- .from(agentOperations)- .where(eq(agentOperations.parentOperationId, createResult.operationId));- expect(childOps.length).toBeGreaterThanOrEqual(1);+ // A child op was spawned and reconciled to the parent+ const childOps = await serverDB+ .select()+ .from(agentOperations)+ .where(eq(agentOperations.parentOperationId, createResult.operationId));+ expect(childOps.length).toBeGreaterThanOrEqual(1);+ if (decision) {+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(pendingContents).toEqual(['']);+ expect(reviewedResults[0]).toContain(SUB_AGENT_ANSWER);+ expect(reviewedResults[0]).toMatch(/<sub_agent id="[^"]+" \/>$/);+ }- // The placeholder tool message was backfilled with the sub-agent's answer,- // followed by the hidden reference the parent uses to continue that sub-agent- const allMessages = await serverDB.select().from(messages).where(eq(messages.userId, userId));- const subAgentToolMessage = allMessages.find(- (m) =>- m.role === 'tool' && !!m.content && stripSubAgentReference(m.content) === SUB_AGENT_ANSWER,- );- expect(subAgentToolMessage).toBeDefined();- expect(subAgentToolMessage!.content).toMatch(/<sub_agent id="[^"]+" \/>$/);- });+ // The placeholder tool message was backfilled with the sub-agent's answer,+ // followed by the hidden reference the parent uses to continue that sub-agent+ const allMessages = await serverDB.select().from(messages).where(eq(messages.userId, userId));+ const subAgentToolMessage = allMessages.find(+ (m) =>+ m.role === 'tool' &&+ !!m.content &&+ stripSubAgentReference(m.content) ===+ (decision === 'deny'+ ? 'Tool result withheld 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,+ );+ if (decision === 'deny') expect(parentInput).not.toContain(SUB_AGENT_ANSWER);+ },+ );});diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex 914e860964b..7f9610e16aa 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -124,7 +124,7 @@ const messageBatchOperationSchema = z.discriminatedUnion('type', [value: z.object({content: z.string().optional(),heterogeneousToolState: heterogeneousToolStateSnapshotSchema.optional(),- metadata: z.record(z.string(), z.any()).optional(),+ metadata: z.object({}).passthrough().optional(),pluginError: z.any().optional(),pluginState: z.record(z.string(), z.any()).optional(),}),diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 7dce326318d..4a06bbbf381 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -55,6 +55,8 @@ vi.mock('@/server/services/file', () => ({vi.mock('@/database/models/message', () => ({MessageModel: vi.fn().mockImplementation(function () {return {+ findById: vi.fn().mockResolvedValue(undefined),+ findMessagePlugin: vi.fn().mockResolvedValue(undefined),query: vi.fn().mockResolvedValue([]),};}),@@ -703,6 +705,40 @@ describe('AgentRuntimeService', () => {}});+ it('does not require durable storage for an environment-only result hook', async () => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/environment');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(+ new Error('db down'),+ );++ await expect(service.createOperation(mockParams)).resolves.toBeDefined();+ });++ it('requires durable storage for a caller result hook', async () => {+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(+ new Error('db down'),+ );++ await expect(+ service.createOperation({+ ...mockParams,+ hooks: [+ {+ id: 'caller',+ type: 'afterToolCall',+ webhook: {+ url: 'https://hooks.example/caller',+ responseHandling: 'toolCall',+ },+ },+ ],+ }),+ ).rejects.toThrow('Failed to durably persist afterToolCall');+ });+// Codex P1 on #20093: the member bridge lived only in the 2h runtime// snapshot, so a late approval continued the supervisor instead.it("keeps a durable copy of a group member's completion bridge on the row", async () => {@@ -3428,6 +3464,9 @@ describe('AgentRuntimeService', () => {let resumeSpy: MockInstance<AgentRuntimeService['tryResumeParentFromAsyncTool']>;beforeEach(() => {+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ metadata: { _hooks: [] },+ });updateToolMessage = vi.fn().mockResolvedValue({ success: true });(service as any).messageModel.updateToolMessage = updateToolMessage;resumeSpy = vi.spyOn(service, 'tryResumeParentFromAsyncTool').mockResolvedValue(true);@@ -3757,6 +3796,9 @@ describe('AgentRuntimeService', () => {let resumeSpy: MockInstance<AgentRuntimeService['tryResumeParentFromAsyncTool']>;beforeEach(() => {+ vi.spyOn((service as any).agentOperationModel, 'findById').mockResolvedValue({+ metadata: { _hooks: [] },+ });updateToolMessage = vi.fn().mockResolvedValue({ success: true });(service as any).messageModel.updateToolMessage = updateToolMessage;resumeSpy = vi.spyOn(service, 'tryResumeParentFromAsyncTool').mockResolvedValue(true);@@ -3770,8 +3812,9 @@ describe('AgentRuntimeService', () => {expect(won).toBe(true);expect(updateToolMessage).toHaveBeenCalledWith('tool-msg-1', {+ onlyIfEmpty: true,content: 'final answer',- pluginError: undefined,+ pluginError: null,pluginState: {model: 'gpt-test',status: 'completed',@@ -3786,6 +3829,87 @@ 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({+ 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' },+ 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: '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,+ });+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect((stored as any).content).toBe('Tool result withheld by afterToolCall hook.');+ } 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.fn()diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 03280232011..8ac201b7f86 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -113,7 +113,12 @@ import {} from './CompletionLifecycle';import { stepChangedCredentials } from './credentialFacts';import { logToolCallPc } from './formalObservation';-import { type AgentHook, hookDispatcher } from './hooks';+import { type AgentHook, hookDispatcher, parseSerializedHooks } from './hooks';+import {+ controlDeferredToolResult,+ type DeferredToolResultControlInput,+ loadDurableToolResultHooks,+} from './hooks/deferredToolResultControl';import { HumanInterventionHandler } from './HumanInterventionHandler';import { buildProjectedMessagePatch } from './messagePatch';import { OperationTraceRecorder } from './OperationTraceRecorder';@@ -888,6 +893,23 @@ export class AgentRuntimeService {}}+ /** Review out-of-band results before any subsequent history read can expose them. */+ async controlCompletedToolResult(input: DeferredToolResultControlInput) {+ const controlled = await controlDeferredToolResult(+ {+ dispatcher: hookDispatcher,+ loadState: (operationId) => this.coordinator.loadAgentState(operationId),+ loadDurableHooks: (operationId) =>+ loadDurableToolResultHooks(this.agentOperationModel, operationId),+ messageModel: this.messageModel,+ userId: this.userId,+ workspaceId: this.workspaceId,+ },+ input,+ );+ return controlled;+ }+/** Load the authoritative runtime state for a deterministic intervention continuation. */async loadInterventionContinuationState(operationId: string): Promise<AgentState | null> {return this.coordinator.loadAgentState(operationId);@@ -1227,6 +1249,18 @@ export class AgentRuntimeService {// stop can still reach the member's supervisor (`loadGroupMemberBridge`).const groupMemberBridge = hooks?.find((hook) => hook.id === 'group-member-bridge')?.webhook?.body as Omit<GroupActionMemberBridgeParams, 'operationId' | 'reason'> | undefined;+ // The Redis state expires independently of pending tools/approvals. Keep+ // caller hook templates on the private operation record, as hetero runs do.+ const durableHooks = parseSerializedHooks(+ (hooks ?? []).flatMap((hook) =>+ hook.webhook+ ? [{ id: hook.id, type: hook.type, matcher: hook.matcher, webhook: hook.webhook }]+ : [],+ ),+ );+ const requiresDurableResultControl = durableHooks.some(+ (hook) => hook.type === 'afterToolCall' && hook.webhook?.responseHandling === 'toolCall',+ );const operationStartPersisted = await traceStartStage('record_start', () =>this.completionLifecycle.recordStart({agentId: appContext?.agentId ?? null,@@ -1241,20 +1275,14 @@ export class AgentRuntimeService {},chatGroupId: appContext?.groupId ?? null,maxSteps,- // Persist the Agent Signal run marker on the operation row so server-side- // self-iteration tools can read it back (operation.metadata.agentSignal) at tool-call- // time β the trimmed appContext above intentionally drops it.- ...(appContext?.agentSignal || interventionResolution || groupMemberBridge- ? {- metadata: {- ...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),- ...(interventionResolution- ? { agentInterventionContinuation: interventionResolution }- : {}),- ...(groupMemberBridge ? { groupMemberBridge } : {}),- },- }- : {}),+ metadata: {+ ...(durableHooks.length > 0 && { _hooks: durableHooks }),+ ...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),+ ...(interventionResolution+ ? { agentInterventionContinuation: interventionResolution }+ : {}),+ ...(groupMemberBridge ? { groupMemberBridge } : {}),+ },model: modelRuntimeConfig?.model,modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),operationId,@@ -1266,6 +1294,9 @@ export class AgentRuntimeService {trigger: appContext?.trigger,}),);+ if (requiresDurableResultControl && !operationStartPersisted) {+ throw new Error('Failed to durably persist afterToolCall control policy before dispatch');+ }if (interventionResolution && !operationStartPersisted) {throw new Error(`Failed to durably persist intervention continuation ${operationId} before dispatch`,@@ -4360,27 +4391,40 @@ export class AgentRuntimeService {? appendSubAgentReference(resultContent, threadId): resultContent;- const backfill = await this.messageModel.updateToolMessage(toolMessageId, {- content,- pluginError: failed- ? formatErrorForMetadata(finalState?.error ?? params.errorMessage)- : undefined,- pluginState: {- model: finalState?.modelRuntimeConfig?.model,- status: failed ? 'error' : 'completed',- threadId,- // The child's spend rides on this anchor row so the parent's usage tray can- // account for it. The tray sums per-MESSAGE usage, and the child's own- // assistant messages live in an isolation thread the parent never loads β- // this row is the only place the child's cost surfaces in the parent's own- // message list.- totalCost: finalState?.cost?.total,- totalInputTokens: finalState?.usage?.llm?.tokens?.input,- totalOutputTokens: finalState?.usage?.llm?.tokens?.output,- totalToolCalls: finalState?.usage?.tools?.totalCalls,- totalTokens: finalState?.usage?.llm?.tokens?.total,+ const { result: completed, blocked } = await this.controlCompletedToolResult({+ preserveUsage: true,+ operationId: parentOperationId,+ toolMessageId,+ result: {+ content,+ success: !failed,+ error: failed+ ? formatErrorForMetadata(finalState?.error ?? params.errorMessage)+ : undefined,+ state: {+ model: finalState?.modelRuntimeConfig?.model,+ status: failed ? 'error' : 'completed',+ threadId,+ // The child's spend rides on this anchor row so the parent's usage tray can+ // account for it. The tray sums per-MESSAGE usage, and the child's own+ // assistant messages live in an isolation thread the parent never loads β+ // this row is the only place the child's cost surfaces in the parent's own+ // message list.+ totalCost: finalState?.cost?.total,+ totalInputTokens: finalState?.usage?.llm?.tokens?.input,+ totalOutputTokens: finalState?.usage?.llm?.tokens?.output,+ totalToolCalls: finalState?.usage?.tools?.totalCalls,+ totalTokens: finalState?.usage?.llm?.tokens?.total,+ },},});+ const backfill = await this.messageModel.updateToolMessage(toolMessageId, {+ content: completed.content,+ pluginError: completed.error ?? null,+ pluginState: completed.state,+ onlyIfEmpty: true,+ ...(blocked && { replacePluginState: true }),+ });if (!backfill.success) {throw new Error(`Sub-agent bridge: failed to backfill tool message ${toolMessageId} for parent ${parentOperationId}`,@@ -4611,31 +4655,63 @@ export class AgentRuntimeService {? `Agent ${agentLabel} responded in the group.`: lastAssistantContent || 'Agent member completed without a textual answer.';- const anchorBackfill = await this.messageModel.updateToolMessage(anchorMessageId, {- content: anchorContent,- pluginError: failed ? formatErrorForMetadata(finalState?.error) : undefined,- pluginState: {- model: finalState?.modelRuntimeConfig?.model,- status: failed ? 'error' : 'completed',- threadId,- // The child's spend rides on this anchor row so the parent's usage tray can- // account for it. The tray sums per-MESSAGE usage, and the child's own- // assistant messages live in an isolation thread the parent never loads β- // this row is the only place the child's cost surfaces in the parent's own- // message list.- totalCost: finalState?.cost?.total,- totalInputTokens: finalState?.usage?.llm?.tokens?.input,- totalOutputTokens: finalState?.usage?.llm?.tokens?.output,- totalToolCalls: finalState?.usage?.tools?.totalCalls,- totalTokens: finalState?.usage?.llm?.tokens?.total,+ const { result: completed, blocked } = await this.controlCompletedToolResult({+ preserveUsage: true,+ contextToolMessageId: groupToolMessageId,+ operationId: parentOperationId,+ toolMessageId: anchorMessageId,+ result: {+ content: anchorContent,+ success: !failed,+ error: failed ? formatErrorForMetadata(finalState?.error) : undefined,+ state: {+ model: finalState?.modelRuntimeConfig?.model,+ status: failed ? 'error' : 'completed',+ threadId,+ // The child's spend rides on this anchor row so the parent's usage tray can+ // account for it. The tray sums per-MESSAGE usage, and the child's own+ // assistant messages live in an isolation thread the parent never loads β+ // this row is the only place the child's cost surfaces in the parent's own+ // message list.+ totalCost: finalState?.cost?.total,+ totalInputTokens: finalState?.usage?.llm?.tokens?.input,+ totalOutputTokens: finalState?.usage?.llm?.tokens?.output,+ totalToolCalls: finalState?.usage?.tools?.totalCalls,+ totalTokens: finalState?.usage?.llm?.tokens?.total,+ },},});+ const anchorBackfill = await this.messageModel.updateToolMessage(anchorMessageId, {+ content: completed.content,+ pluginError: completed.error ?? null,+ pluginState: completed.state,+ onlyIfEmpty: true,+ ...(blocked && { replacePluginState: true }),+ });if (!anchorBackfill.success) {throw new Error(`Group-member bridge: failed to backfill anchor ${anchorMessageId} for parent ${parentOperationId}`,);}+ return this.completeGroupMemberBarrier({+ anchorMessageId,+ expectedMembers,+ groupToolMessageId,+ parentOperationId,+ });+ }++ /** Shared by a child's completion and a member that failed before an operation existed. */+ async completeGroupMemberBarrier({+ anchorMessageId,+ expectedMembers,+ groupToolMessageId,+ parentOperationId,+ }: Pick<+ GroupActionMemberBridgeParams,+ 'anchorMessageId' | 'expectedMembers' | 'groupToolMessageId' | 'parentOperationId'+ >): Promise<boolean> {// 2. K=N member barrier (multi-member actions only β single-member actions// use the group tool call itself as the anchor, already backfilled above).if (expectedMembers > 1 && anchorMessageId !== groupToolMessageId) {@@ -4643,7 +4719,7 @@ export class AgentRuntimeService {if (fulfilled < expectedMembers) {log('[%s] group-member barrier %d/%d, holding parent %s',- operationId,+ parentOperationId,fulfilled,expectedMembers,parentOperationId,@@ -4660,9 +4736,23 @@ export class AgentRuntimeService {// All members done β backfill the group tool call so the parked op's// single-tool barrier ([groupTool]) passes. Idempotent across racing// last-committers; the resume/finish CAS guarantees one transition.+ const { result: groupResult, blocked: groupBlocked } = await this.controlCompletedToolResult({+ operationId: parentOperationId,+ toolMessageId: groupToolMessageId,+ result: {+ content: `All ${expectedMembers} agent members completed.`,+ state: { expectedMembers, status: 'completed' },+ success: true,+ },+ });const groupBackfill = await this.messageModel.updateToolMessage(groupToolMessageId, {- content: `All ${expectedMembers} agent members completed.`,- pluginState: { expectedMembers, status: 'completed' },+ content: groupResult.content,+ pluginError: groupResult.error ?? null,+ pluginState: groupResult.state,+ onlyIfEmpty: true,+ ...(groupBlocked && {+ replacePluginState: true,+ }),});if (!groupBackfill.success) {throw new Error(@@ -5065,6 +5155,7 @@ export class AgentRuntimeService {execSubAgent: this.delegate.execSubAgent,execVirtualSubAgent: this.delegate.execVirtualSubAgent,execGroupMember: this.delegate.execGroupMember,+ onGroupMemberResult: (params) => this.completeGroupMemberBarrier(params),hookDispatcher,loadAgentState: this.coordinator.loadAgentState.bind(this.coordinator),messageModel: this.messageModel,diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 8982a148b46..e9c09777f47 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -241,7 +241,12 @@ export class CompletionLifecycle {await this.agentOperationModel.recordStart(params);} catch (error) {persisted = false;- log('[%s] Failed to record operation start (non-fatal): %O', params.operationId, error);+ // Hook configuration may contain inline authorization headers. Never log+ // a database error that could repeat its bound metadata parameters.+ const hooks = params.metadata?._hooks;+ if (hooks && (!Array.isArray(hooks) || hooks.length > 0))+ log('[%s] Failed to record operation start (non-fatal)', params.operationId);+ else log('[%s] Failed to record operation start (non-fatal): %O', params.operationId, error);}// Auto-instantiate the task's verify plan at run start so the completion gatediff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex a6855f2b10d..f4e8413e3de 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -1,9 +1,11 @@// @vitest-environment nodeimport { type Message, parse } from '@lobechat/conversation-flow';import { ChatErrorType, RequestTrigger } from '@lobechat/types';+import debug from 'debug';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { NotifyAgentInterventionRequiredParams } from '@/business/server/agent-run/agentInterventionReview';+import { AgentOperationModel } from '@/database/models/agentOperation';import { WorkModel } from '@/database/models/work';import * as agentSignalService from '@/server/services/agentSignal';import * as verifyServices from '@/server/services/verify';@@ -64,6 +66,50 @@ const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');+describe('CompletionLifecycle.recordStart diagnostics', () => {+ let debugNamespaces: string;++ beforeEach(() => {+ debugNamespaces = debug.disable();+ debug.enable('lobe-server:completion-lifecycle');+ });++ afterEach(() => {+ debug.enable(debugNamespaces);+ vi.restoreAllMocks();+ });++ it.each([undefined, { _hooks: [] }])(+ 'retains the database failure cause without persisted hooks: %j',+ async (metadata) => {+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(+ new Error('connection refused'),+ );+ const output = vi.spyOn(debug, 'log').mockImplementation(() => {});++ expect(await buildLifecycle().recordStart({ operationId: 'op-1', metadata })).toBe(false);+ expect(output.mock.calls.flat().join(' ')).toContain('connection refused');+ },+ );++ it('does not log database parameters containing hook credentials', async () => {+ const secret = 'synthetic-hook-authorization';+ vi.spyOn(AgentOperationModel.prototype, 'recordStart').mockRejectedValue(+ new Error(`Failed query; params: ${secret}`),+ );+ const output = vi.spyOn(debug, 'log').mockImplementation(() => {});++ expect(+ await buildLifecycle().recordStart({+ operationId: 'op-1',+ metadata: { _hooks: [{ webhook: { headers: { Authorization: secret } } }] },+ }),+ ).toBe(false);+ expect(output.mock.calls.flat().join(' ')).toContain('Failed to record operation start');+ expect(output.mock.calls.flat().join(' ')).not.toContain(secret);+ });+});+describe('isSuccessLikeCompletionReason', () => {// Regression: file-Work registration was gated on `reason === 'done'` alone,// silently skipping runs stopped by a step/cost cap even though the lifecyclediff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.tsindex b4899f18aad..13d86b21d7c 100644--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts@@ -14,6 +14,7 @@ import { deliverWebhook, executeToolCallWebhook } from './httpWebhook';import { matchesHook } from './matcher';import { getServerHooks, mergeServerHooks } from './serverHooks';import type {+ AfterToolCallHookEvent,AgentHook,AgentHookEvent,AgentHookType,@@ -59,12 +60,16 @@ export class HookDispatcher {private hooks: Map<string, AgentHook[]> = new Map();/** Shared by normal dispatch and tool control, including cold-worker recovery. */- private resolveHooks(operationId: string, serializedHooks?: SerializedAgentHook[]) {+ private resolveHooks(+ operationId: string,+ serializedHooks?: SerializedAgentHook[],+ includeServerHooks = true,+ ) {const restored = serializedHooks ? parseSerializedHooks(serializedHooks) : undefined;const hooks: (AgentHook | SerializedHook)[] = isQueueAgentRuntimeEnabled()? (restored ?? this.getSerializedHooks(operationId) ?? []): (this.hooks.get(operationId) ?? restored ?? []);- return mergeServerHooks(hooks, getServerHooks());+ return mergeServerHooks(hooks, includeServerHooks ? getServerHooks() : []);}/**@@ -145,6 +150,17 @@ export class HookDispatcher {if (criticalError) throw criticalError;}+ /** Includes cold-worker and current environment controls, without invoking a receiver. */+ hasAfterToolCallControl(+ operationId: string,+ serializedHooks?: SerializedAgentHook[],+ includeServerHooks = true,+ ): boolean {+ return this.resolveHooks(operationId, serializedHooks, includeServerHooks).some(+ (hook) => hook.type === 'afterToolCall' && hook.webhook?.responseHandling === 'toolCall',+ );+ }+/** Ordered synchronous controls. Cancellation never goes through onError. */async evaluateToolCall(operationId: string,@@ -152,11 +168,40 @@ export class HookDispatcher {serializedHooks?: SerializedAgentHook[],signal?: AbortSignal,): Promise<{ status: 'allow' | 'blocked' | 'cancelled'; reason?: string }> {- const hooks = this.resolveHooks(operationId, serializedHooks);+ return this.evaluateToolControl('beforeToolCall', operationId, event, serializedHooks, signal);+ }++ /** Result controls run before archival, persistence, streaming, and model consumption. */+ async evaluateAfterToolCall(+ operationId: string,+ event: AfterToolCallHookEvent,+ serializedHooks?: SerializedAgentHook[],+ signal?: AbortSignal,+ includeServerHooks = true,+ ): Promise<{ status: 'allow' | 'blocked' | 'cancelled'; reason?: string }> {+ return this.evaluateToolControl(+ 'afterToolCall',+ operationId,+ event,+ serializedHooks,+ signal,+ includeServerHooks,+ );+ }++ private async evaluateToolControl(+ type: 'beforeToolCall' | 'afterToolCall',+ operationId: string,+ event: Omit<ToolCallHookEvent, 'mock'> | AfterToolCallHookEvent,+ serializedHooks?: SerializedAgentHook[],+ signal?: AbortSignal,+ includeServerHooks = true,+ ): Promise<{ status: 'allow' | 'blocked' | 'cancelled'; reason?: string }> {+ const hooks = this.resolveHooks(operationId, serializedHooks, includeServerHooks);for (const hook of hooks) {if (signal?.aborted) return { status: 'cancelled' };if (- hook.type !== 'beforeToolCall' ||+ hook.type !== type ||hook.webhook?.responseHandling !== 'toolCall' ||!matchesHook(hook.matcher, event))@@ -164,8 +209,8 @@ export class HookDispatcher {const payload = await this.buildWebhookPayload(event,{},- { hookId: hook.id, hookType: 'beforeToolCall' },- { signal },+ { hookId: hook.id, hookType: type },+ { preserveToolResult: true, signal },);if (!payload || signal?.aborted) return { status: 'cancelled' };const response = await executeToolCallWebhook(hook.webhook, payload, { signal });@@ -173,7 +218,7 @@ export class HookDispatcher {if (response.status === 'success' && response.decision.decision === 'deny') {return {status: 'blocked',- reason: response.decision.reason ?? 'Blocked by beforeToolCall 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.tsnew file mode 100644index 00000000000..7fbbc0d4bad--- /dev/null+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/deferredToolResultControl.test.ts@@ -0,0 +1,371 @@+import type { AgentState } from '@lobechat/agent-runtime';+import type { MessagePluginItem } from '@lobechat/types';+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 () => [] } }));+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: queueMode }));+vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));++const secret = 'synthetic-private-child-result';+const original = { content: secret, success: true, state: { full: secret, totalCost: 0.25 } };+const plugin: MessagePluginItem = {+ id: 'tool-row',+ toolCallId: 'native-call',+ identifier: 'lobe-agent',+ apiName: 'callSubAgent',+ arguments: '{"instruction":"original request"}',+ type: 'builtin',+ userId: 'owner',+};+const hook = {+ id: 'after',+ type: 'afterToolCall' as const,+ webhook: {+ url: 'https://hooks.example/after',+ responseHandling: 'toolCall' as const,+ onError: 'block' as const,+ },+};+const state = {+ operationId: 'parent',+ stepCount: 2,+ origin: { agentId: 'agent', topicId: 'topic' },+ host: { hooks: [hook] },+} as AgentState;+function setup() {+ const deps = {+ dispatcher: new HookDispatcher(),+ loadState: vi.fn().mockResolvedValue(state),+ loadDurableHooks: vi.fn().mockResolvedValue([]),+ messageModel: {+ findById: vi.fn().mockResolvedValue({+ id: 'tool-row',+ parentId: 'assistant',+ role: 'tool',+ agentId: 'agent',+ topicId: 'topic',+ }),+ findMessagePlugin: vi.fn().mockResolvedValue(plugin),+ },+ userId: 'owner',+ };+ const input = {+ operationId: 'parent',+ toolMessageId: 'tool-row',+ result: original,+ preserveUsage: true,+ };+ return { deps, input };+}+beforeEach(() => {+ vi.stubGlobal('fetch', fetchHook);+ fetchHook+ .mockReset()+ .mockImplementation(+ async () => new Response(JSON.stringify({ decision: 'deny', reason: secret })),+ );+ queueMode.mockReturnValue(false);+});+afterEach(() => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+});++describe('out-of-band tool result control', () => {+ it.each([false, true])(+ 'evaluates current environment once while retaining same-id caller policies, queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ const { deps, input } = setup();+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/environment');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-test-token');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');+ deps.messageModel.findMessagePlugin.mockResolvedValue({+ ...plugin,+ intervention: { operationId: 'original', status: 'approved' },+ });+ deps.loadState.mockResolvedValue(null);+ deps.loadDurableHooks.mockImplementation(async (id) => [+ { ...hook, webhook: { ...hook.webhook, url: `https://hooks.example/${id}` } },+ ]);+ fetchHook.mockImplementation(async () => new Response(JSON.stringify({ decision: 'allow' })));++ expect((await controlDeferredToolResult(deps, input)).result).toBe(original);+ expect(+ fetchHook.mock.calls.map(([url, init]) => [url, JSON.parse(init.body).operationId]),+ ).toEqual([+ ['https://hooks.example/original', 'original'],+ ['https://hooks.example/parent', 'parent'],+ ['https://hooks.example/environment', 'parent'],+ ]);++ fetchHook+ .mockClear()+ .mockImplementation(+ async (url) =>+ new Response(+ JSON.stringify({ decision: String(url).endsWith('/parent') ? 'deny' : 'allow' }),+ ),+ );+ expect((await controlDeferredToolResult(deps, input)).blocked).toBe(true);+ expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([+ 'https://hooks.example/original',+ 'https://hooks.example/parent',+ ]);+ },+ );+ it.each([false, true])(+ 'recovers the original call and full result on a cold worker, queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ const { deps, input } = setup();+ const { result } = await controlDeferredToolResult(deps, input);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({+ operationId: 'parent',+ toolCallId: 'native-call',+ toolMessageId: 'tool-row',+ assistantMessageId: 'assistant',+ args: { instruction: 'original request' },+ userId: 'owner',+ result: original,+ });+ expect(result).toMatchObject({+ content: BLOCKED_TOOL_RESULT_CONTENT,+ success: false,+ state: { totalCost: 0.25 },+ });+ expect(JSON.stringify(result)).not.toContain(secret);+ },+ );+ it('leaves no-control completions unchanged without requiring call metadata', async () => {+ const { deps, input } = setup();+ deps.loadState.mockResolvedValue(null);+ deps.messageModel.findMessagePlugin.mockResolvedValue(undefined);+ expect((await controlDeferredToolResult(deps, input)).result).toBe(original);+ expect(fetchHook).not.toHaveBeenCalled();+ });+ it('restores caller controls and call identity after Redis expiry', async () => {+ const { deps, input } = setup();+ deps.loadState.mockResolvedValue(null);+ deps.loadDurableHooks.mockResolvedValue([hook]);+ deps.messageModel.findById.mockResolvedValue({+ id: 'tool-row',+ parentId: 'assistant',+ });+ const { result } = await controlDeferredToolResult(deps, input);+ expect(result.content).toBe(BLOCKED_TOOL_RESULT_CONTENT);+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({+ operationId: 'parent',+ toolCallId: 'native-call',+ result: original,+ });+ });++ it('propagates a caller hook store failure rather than treating it as no hooks', async () => {+ const { deps, input } = setup();+ deps.loadState.mockResolvedValue(null);+ deps.loadDurableHooks.mockRejectedValue(new Error('database unavailable'));+ await expect(controlDeferredToolResult(deps, input)).rejects.toThrow('database unavailable');+ expect(fetchHook).not.toHaveBeenCalled();+ });+ it('retains pre-feature no-hook behavior for legacy rows', async () => {+ const { deps, input } = setup();+ deps.loadState.mockResolvedValue(null);+ deps.loadDurableHooks.mockResolvedValue(undefined);+ expect((await controlDeferredToolResult(deps, input)).result).toBe(original);+ expect(fetchHook).not.toHaveBeenCalled();+ });++ it('preserves legacy results when configured hooks only match another tool', async () => {+ const { deps, input } = setup();+ deps.loadState.mockResolvedValue(null);+ deps.loadDurableHooks.mockResolvedValue([{ ...hook, matcher: '^other/tool$' }]);+ expect((await controlDeferredToolResult(deps, input)).result).toBe(original);+ expect(fetchHook).not.toHaveBeenCalled();+ });+ it.each([false, true])(+ 'evaluates deferred results using the current environment instead of its old policy, queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ const { deps, input } = setup();+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/after');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-token');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');+ expect(deps.dispatcher.hasAfterToolCallControl('parent', [])).toBe(true);+ deps.loadState.mockResolvedValue(null);+ deps.loadDurableHooks.mockResolvedValue([]);+ deps.messageModel.findById.mockResolvedValue({+ id: 'tool-row',+ parentId: 'assistant',+ });++ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', undefined);+ expect(await controlDeferredToolResult(deps, input)).toMatchObject({+ blocked: false,+ result: original,+ });+ expect(fetchHook).not.toHaveBeenCalled();++ // A newly configured environment policy is evaluated at completion time.+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/after');+ fetchHook.mockResolvedValue(new Response(JSON.stringify({ decision: 'allow' })));+ expect(await controlDeferredToolResult(deps, input)).toMatchObject({+ result: original,+ });+ expect(fetchHook).toHaveBeenCalledTimes(1);+ },+ );+ it.each([+ { label: 'live snapshot without controls', snapshot: true, hooks: [] },+ {+ label: 'only notification hooks',+ snapshot: false,+ hooks: [+ { ...hook, webhook: { ...hook.webhook, responseHandling: 'ignore', onError: 'continue' } },+ ],+ },+ {+ label: 'controls for another tool',+ snapshot: false,+ hooks: [{ ...hook, matcher: '^other/tool$' }],+ },+ {+ label: 'removed environment hook template',+ snapshot: false,+ hooks: [{ ...hook, id: 'server-env-webhook:afterToolCall' }],+ },+ ])('allows results when there is no matching control: $label', async ({ snapshot, hooks }) => {+ const { deps, input } = setup();+ deps.loadState.mockResolvedValue(snapshot ? { ...state, host: { hooks } } : null);+ deps.loadDurableHooks.mockResolvedValue(hooks);+ deps.messageModel.findById.mockResolvedValue({+ id: 'tool-row',+ parentId: 'assistant',+ });+ expect(await controlDeferredToolResult(deps, input)).toMatchObject({+ blocked: false,+ result: original,+ });+ expect(fetchHook).not.toHaveBeenCalled();+ });+ it.each([false, true])(+ 'still enforces persisted caller hooks after environment removal, queue=%s',+ async (queue) => {+ queueMode.mockReturnValue(queue);+ const { deps, input } = setup();+ deps.loadState.mockResolvedValue(null);+ deps.loadDurableHooks.mockResolvedValue([hook]);+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', undefined);+ deps.messageModel.findById.mockResolvedValue({+ id: 'tool-row',+ parentId: 'assistant',+ });+ expect(await controlDeferredToolResult(deps, input)).toMatchObject({+ blocked: true,+ });+ expect(fetchHook).toHaveBeenCalledTimes(1);+ expect(fetchHook.mock.calls[0][0]).toBe(hook.webhook.url);+ },+ );++ it('does not treat tool-owned blocked state as a prior hook denial', async () => {+ const { deps, input } = setup();+ deps.messageModel.findMessagePlugin.mockResolvedValue({+ ...plugin,+ state: { type: 'blocked', phase: 'afterToolCall' },+ });+ fetchHook.mockResolvedValue(new Response(JSON.stringify({ decision: 'allow' })));+ const controlled = await controlDeferredToolResult(deps, input);+ expect(controlled).toMatchObject({+ blocked: false,+ result: original,+ });+ expect(fetchHook).toHaveBeenCalledTimes(1);+ });++ it('keeps original caller hooks on an approved deferred call and applies continuation hooks too', async () => {+ const { deps, input } = setup();+ deps.messageModel.findMessagePlugin.mockResolvedValue({+ ...plugin,+ intervention: { operationId: 'original', status: 'approved' },+ });+ deps.loadState.mockImplementation(async (id) =>+ id === 'original'+ ? null+ : {+ ...state,+ host: {+ hooks: [+ {+ ...hook,+ id: 'new',+ webhook: { ...hook.webhook, url: 'https://hooks.example/new' },+ },+ ],+ },+ },+ );+ deps.loadDurableHooks.mockResolvedValue([hook]);+ fetchHook.mockImplementation(+ async (url) =>+ new Response(+ JSON.stringify({ decision: String(url).endsWith('/after') ? 'allow' : 'deny' }),+ ),+ );+ expect((await controlDeferredToolResult(deps, input)).result.content).toBe(+ BLOCKED_TOOL_RESULT_CONTENT,+ );+ expect(fetchHook.mock.calls.map(([url]) => url)).toEqual([+ 'https://hooks.example/after',+ 'https://hooks.example/new',+ ]);+ });++ it('uses the parent group call arguments for an isolated member result', async () => {+ const { deps, input } = setup();+ deps.messageModel.findMessagePlugin.mockImplementation(async (id) =>+ id === 'group-tool'+ ? { ...plugin, id, apiName: 'executeAgentTasks', state: { onComplete: 'finish' } }+ : undefined,+ );+ const { result } = await controlDeferredToolResult(deps, {+ ...input,+ contextToolMessageId: 'group-tool',+ });+ expect(JSON.parse(fetchHook.mock.calls[0][1].body)).toMatchObject({+ apiName: 'executeAgentTasks',+ toolMessageId: 'tool-row',+ result: original,+ });+ expect(result.state?.onComplete).toBe('finish');+ });+ it('fails closed when a configured control cannot reconstruct the call', async () => {+ const { deps, input } = setup();+ deps.messageModel.findMessagePlugin.mockResolvedValue(undefined);+ await expect(controlDeferredToolResult(deps, input)).rejects.toThrow(+ 'tool call context is unavailable',+ );+ expect(fetchHook).not.toHaveBeenCalled();+ });+ it('uses current after-only environment controls when the parent snapshot is unavailable', async () => {+ const { deps, input } = setup();+ deps.loadState.mockResolvedValue(null);+ vi.stubEnv('AGENT_HOOK_WEBHOOK_URL', 'https://hooks.example/after');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_TOKEN', 'synthetic-token');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');+ expect((await controlDeferredToolResult(deps, input)).result.content).toBe(+ BLOCKED_TOOL_RESULT_CONTENT,+ );+ });+});diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.tsindex 53a7cd8940d..61e95429725 100644--- a/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.ts+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/serverHooks.test.ts@@ -135,6 +135,32 @@ describe('environment hooks through real HTTP transport', () => {},);+ it.each(['toolResult', 'toolCallAndResult'])(+ 'opts into afterToolCall controls with %s without persisting server secrets',+ async (mode) => {+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', mode);+ vi.stubEnv(+ 'AGENT_HOOK_WEBHOOK_EVENTS',+ mode === 'toolResult' ? 'afterToolCall' : 'beforeToolCall,afterToolCall',+ );+ response = { decision: 'deny' };+ const dispatcher = new HookDispatcher();+ dispatcher.register(event.operationId, []);+ expect(dispatcher.getSerializedHooks(event.operationId)).toEqual([]);+ const after = { ...event, mocked: false, result: { content: 'full result', success: true } };+ expect(await dispatcher.evaluateAfterToolCall(event.operationId, after)).toMatchObject({+ status: 'blocked',+ });+ await dispatcher.dispatch(event.operationId, 'afterToolCall', after);+ expect(requests).toHaveLength(1);+ expect(requests[0].body).toMatchObject({ hookType: 'afterToolCall', result: after.result });+ expect(await dispatcher.evaluateToolCall(event.operationId, event)).toMatchObject({+ status: mode === 'toolCallAndResult' ? 'blocked' : 'allow',+ });+ expect(requests).toHaveLength(mode === 'toolCallAndResult' ? 2 : 1);+ },+ );+it('preserves caller handlers and internal callbacks and prevents same-ID replacement', async () => {const dispatcher = new HookDispatcher();const handler = vi.fn();diff --git a/apps/server/src/services/agentRuntime/hooks/deferredToolResultControl.ts b/apps/server/src/services/agentRuntime/hooks/deferredToolResultControl.tsnew file mode 100644index 00000000000..2fae3130dbb--- /dev/null+++ b/apps/server/src/services/agentRuntime/hooks/deferredToolResultControl.ts@@ -0,0 +1,156 @@+import type { AgentState, ToolRunResult } from '@lobechat/agent-runtime';+import { selectToolSourceMap } from '@lobechat/agent-runtime';+import type { SerializedAgentHook } from '@lobechat/types';+import { isRecord } from '@lobechat/utils/object';++import type { AgentOperationModel } from '@/database/models/agentOperation';+import type { MessageModel } from '@/database/models/message';+import { resolveRunActiveDeviceId } from '@/server/modules/AgentRuntime/executors/resolveRunActiveDeviceId';++import { type HookDispatcher, parseSerializedHooks } from './HookDispatcher';+import { controlToolResult, type ToolResultControlOutcome } from './toolResultControl';++export interface DeferredToolResultControlInput {+ /** Parent tool whose arguments produced a member anchor's result. */+ contextToolMessageId?: string;+ /** A following continuation round can evaluate the current environment instead. */+ includeServerHooks?: boolean;+ operationId?: string;+ /** Only server-built child usage, never arbitrary tool/user result fields. */+ preserveUsage?: boolean;+ result: ToolRunResult;+ signal?: AbortSignal;+ toolMessageId: string;+}++/** Reuse the existing private operation hook storage; never project it onto messages. */+export async function loadDurableToolResultHooks(+ operations: Pick<AgentOperationModel, 'findById'>,+ operationId: string,+): Promise<SerializedAgentHook[] | undefined> {+ const operation = await operations.findById(operationId);+ const hooks = operation?.metadata?._hooks;+ return Array.isArray(hooks) ? parseSerializedHooks(hooks) : undefined;+}++/**+ * Deferred completions do not return through ServerToolTransport. Recover their+ * authoritative call and parent hooks before writing the result into history.+ * No notification is added: this only extends explicitly configured controls.+ */+export async function controlDeferredToolResult(+ deps: {+ dispatcher: HookDispatcher;+ loadState: (operationId: string) => Promise<AgentState | null>;+ loadDurableHooks: (operationId: string) => Promise<SerializedAgentHook[] | undefined>;+ messageModel: Pick<MessageModel, 'findById' | 'findMessagePlugin'>;+ userId: string;+ workspaceId?: string;+ },+ input: DeferredToolResultControlInput,+): Promise<ToolResultControlOutcome> {+ const contextMessageId = input.contextToolMessageId ?? input.toolMessageId;+ const [message, persisted] = await Promise.all([+ deps.messageModel.findById(contextMessageId),+ deps.messageModel.findMessagePlugin(contextMessageId),+ ]);+ // Approval continuations have a new operation; the existing intervention+ // identity still locates the caller hooks of the original parked call.+ const operationIds = [+ ...new Set(+ [persisted?.intervention?.operationId, input.operationId].filter((id): id is string =>+ Boolean(id),+ ),+ ),+ ];+ let outcome: ToolResultControlOutcome = {+ blocked: false,+ cancelled: false,+ result: input.result,+ };+ const rounds = operationIds.length ? operationIds : [undefined];+ for (const [index, operationId] of rounds.entries()) {+ outcome = await evaluate(+ operationId,+ input.includeServerHooks !== false && index === rounds.length - 1,+ );+ if (outcome.blocked || outcome.cancelled) return outcome;+ }+ return outcome;++ async function evaluate(+ operationId: string | undefined,+ includeServerHooks: boolean,+ ): Promise<ToolResultControlOutcome> {+ const state = operationId ? await deps.loadState(operationId) : null;+ let hooks = state?.host?.hooks;+ if (!state && operationId) {+ hooks = await deps.loadDurableHooks(operationId);+ }+ if (!deps.dispatcher.hasAfterToolCallControl(operationId ?? '', hooks, includeServerHooks))+ return {+ blocked: false,+ cancelled: false,+ result: input.result,+ };+ const plugin = persisted;+ if (+ !operationId ||+ !message?.parentId ||+ !plugin?.toolCallId ||+ !plugin.identifier ||+ !plugin.apiName+ ) {+ // Do not acknowledge an unreviewed backfill when its authoritative call+ // cannot be reconstructed. A durable callback can retry the same result.+ throw new Error('Cannot evaluate afterToolCall: tool call context is unavailable');+ }+ let args: Record<string, unknown> = {};+ try {+ const parsed: unknown = JSON.parse(plugin.arguments ?? '{}');+ if (isRecord(parsed)) args = parsed;+ } catch {+ // Match the synchronous tool context: malformed arguments have an empty preview.+ }+ const toolName = `${plugin.identifier}/${plugin.apiName}`;+ const controlled = await controlToolResult(+ deps.dispatcher,+ {+ activeDeviceId: state ? resolveRunActiveDeviceId(state) : undefined,+ agentId: state?.origin?.agentId ?? message.agentId ?? undefined,+ apiName: plugin.apiName,+ args,+ assistantMessageId: message.parentId,+ callIndex:+ (state?.usage?.tools?.byTool?.find((tool) => tool.name === toolName)?.calls ?? 0) + 1,+ documentId: state?.origin?.documentId,+ executionTarget: state?.plan?.execution?.target,+ executor: 'server',+ groupId: state?.origin?.groupId ?? message.groupId ?? undefined,+ identifier: plugin.identifier,+ mocked: false,+ operationId,+ parentOperationId: state?.origin?.lineage?.parentOperationId,+ result: input.result,+ sessionId: state?.origin?.sessionId ?? message.sessionId ?? undefined,+ sourceMessageId: state?.origin?.sourceMessageId,+ stepIndex: Math.max(0, (state?.stepCount ?? 1) - 1),+ taskId: state?.origin?.taskId,+ threadId: state?.origin?.threadId ?? message.threadId ?? undefined,+ toolCallId: plugin.toolCallId,+ toolMessageId: input.toolMessageId,+ toolSource: state ? selectToolSourceMap(state)[plugin.identifier] : undefined,+ topicId: state?.origin?.topicId ?? message.topicId ?? undefined,+ userId: deps.userId,+ workspaceId: state?.origin?.workspaceId ?? deps.workspaceId,+ },+ hooks,+ input.signal,+ { includeServerHooks, preserveUsage: input.preserveUsage },+ );+ if (controlled.blocked && plugin.state?.onComplete === 'finish') {+ controlled.result.state!.onComplete = 'finish';+ }+ return controlled;+ }+}diff --git a/apps/server/src/services/agentRuntime/hooks/serverHooks.ts b/apps/server/src/services/agentRuntime/hooks/serverHooks.tsindex 71be4e43058..93a167230ba 100644--- a/apps/server/src/services/agentRuntime/hooks/serverHooks.ts+++ b/apps/server/src/services/agentRuntime/hooks/serverHooks.ts@@ -16,7 +16,12 @@ export function getServerHooks(): AgentHook[] {};return env.AGENT_HOOK_WEBHOOK_EVENTS!.map((type): AgentHook => {const id = `${SERVER_HOOK_PREFIX}${type}`;- if (type === 'beforeToolCall' && env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolCall') {+ if (+ (type === 'beforeToolCall' &&+ ['toolCall', 'toolCallAndResult'].includes(env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING)) ||+ (type === 'afterToolCall' &&+ ['toolResult', 'toolCallAndResult'].includes(env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING))+ ) {return {id,type,diff --git a/apps/server/src/services/agentRuntime/hooks/toolResultControl.ts b/apps/server/src/services/agentRuntime/hooks/toolResultControl.tsnew file mode 100644index 00000000000..d23f471ca5d--- /dev/null+++ b/apps/server/src/services/agentRuntime/hooks/toolResultControl.ts@@ -0,0 +1,76 @@+import type { AfterToolCallHookEvent, ToolRunResult } from '@lobechat/agent-runtime';+import type { SerializedAgentHook } from '@lobechat/types';+import {+ BLOCKED_TOOL_RESULT_CONTENT,+ pickToolResultUsage,+} from '@lobechat/utils/toolResultControl';++import type { HookDispatcher } from './HookDispatcher';++export { BLOCKED_TOOL_RESULT_CONTENT } from '@lobechat/utils/toolResultControl';++export interface ToolResultControlOutcome {+ blocked: boolean;+ cancelled: boolean;+ result: ToolRunResult;+}++/**+ * 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.+ */+export function blockedToolResult(result: ToolRunResult, preserveUsage = false): ToolRunResult {+ return {+ content: BLOCKED_TOOL_RESULT_CONTENT,+ deviceExecutionTime: result.deviceExecutionTime,+ error: 'hook_denied',+ executionTime: result.executionTime,+ state: {+ ...(preserveUsage && pickToolResultUsage(result.state)),+ phase: 'afterToolCall',+ reason: BLOCKED_TOOL_RESULT_CONTENT,+ type: 'blocked',+ },+ ...(result.stop !== undefined && { stop: result.stop }),+ success: false,+ };+}++/** One shared gate for immediate and out-of-band tool completions. */+export async function controlToolResult(+ dispatcher: HookDispatcher | undefined,+ event: AfterToolCallHookEvent,+ hooks?: SerializedAgentHook[],+ signal?: AbortSignal,+ {+ preserveUsage = false,+ includeServerHooks = true,+ }: {+ preserveUsage?: boolean;+ includeServerHooks?: boolean;+ } = {},+): Promise<ToolResultControlOutcome> {+ const decision = await dispatcher?.evaluateAfterToolCall(+ event.operationId,+ event,+ hooks,+ signal,+ includeServerHooks,+ );+ if (signal?.aborted || decision?.status === 'cancelled') {+ return {+ blocked: true,+ cancelled: true,+ result: blockedToolResult(event.result, preserveUsage),+ };+ }+ return {+ blocked: decision?.status === 'blocked',+ cancelled: false,+ result:+ decision?.status === 'blocked'+ ? blockedToolResult(event.result, preserveUsage)+ : event.result,+ };+}diff --git a/apps/server/src/services/agentRuntime/hooks/types.ts b/apps/server/src/services/agentRuntime/hooks/types.tsindex ea9a39f7d7d..d6a48fe9392 100644--- a/apps/server/src/services/agentRuntime/hooks/types.ts+++ b/apps/server/src/services/agentRuntime/hooks/types.ts@@ -46,14 +46,14 @@ export type NotificationWebhook = AgentHookWebhook & {responseHandling?: 'ignore';};-/** Control hooks are webhook-only and synchronous. Evaluated at tool execution entry, after product permission and approval. */+/** Control hooks are webhook-only and synchronous. Evaluated at execution entry or after the complete result, before it enters model context. */export type AgentHook = {id: string;matcher?: AgentHookMatcher;} & (| {handler?: never;- type: 'beforeToolCall';+ type: 'beforeToolCall' | 'afterToolCall';webhook: AgentHookWebhook & { delivery?: 'fetch'; responseHandling: 'toolCall' };}| {diff --git a/apps/server/src/services/agentRuntime/hooks/webhookPayload.ts b/apps/server/src/services/agentRuntime/hooks/webhookPayload.tsindex 4a63e327910..d5636739197 100644--- a/apps/server/src/services/agentRuntime/hooks/webhookPayload.ts+++ b/apps/server/src/services/agentRuntime/hooks/webhookPayload.ts@@ -64,7 +64,7 @@ export const createWebhookPayloadBuilder = () => {event: T,webhook: Pick<AgentHookWebhook, 'body' | 'eventFields'>,metadata: { hookId: string; hookType: AgentHookType },- options: { signal?: AbortSignal } = {},+ options: { preserveToolResult?: boolean; signal?: AbortSignal } = {},): Promise<AgentHookWebhookPayload | undefined> => {const { signal } = options;if (signal?.aborted) return undefined;@@ -76,7 +76,8 @@ export const createWebhookPayloadBuilder = () => {}}const payload: AgentHookWebhookPayload = { ...selected, ...metadata, ...body };- if (metadata.hookType === 'afterToolCall' && payload.result) {+ // Controls inspect the complete result; observation payloads retain their legacy redaction.+ if (metadata.hookType === 'afterToolCall' && payload.result && !options.preserveToolResult) {payload.result = redactResultForEvents(payload.result as ToolRunResult);}delete payload.finalState;diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex 4c6f2c49d8e..0333b013f02 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -297,15 +297,18 @@ describe('AiAgentService.execAgent - resumeApproval', () => {},});- expect(mockResolveHumanApproval).toHaveBeenCalledWith([- {- id: 'tool-msg-1',- intervention: {- resolutionRequestId: expect.stringMatching(/^legacy_/),- status: 'approved',+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ {+ id: 'tool-msg-1',+ intervention: {+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'approved',+ },},- },- ]);+ ],+ { publishResult: true },+ );// `approved` decision never writes tool content β the content arrives// when the approved tool actually executes.expect(mockUpdateToolMessage).not.toHaveBeenCalled();@@ -342,12 +345,15 @@ describe('AiAgentService.execAgent - resumeApproval', () => {},});- expect(mockResolveHumanApproval).toHaveBeenCalledWith([- {- id: 'tool-msg-1',- intervention: { resolutionRequestId: approvalResolutionRequestId, status: 'approved' },- },- ]);+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ {+ id: 'tool-msg-1',+ intervention: { resolutionRequestId: approvalResolutionRequestId, status: 'approved' },+ },+ ],+ { publishResult: true },+ );expect(mockUpdateTopicMetadata).not.toHaveBeenCalled();});@@ -465,17 +471,20 @@ describe('AiAgentService.execAgent - resumeApproval', () => {},});- expect(mockResolveHumanApproval).toHaveBeenCalledWith([- {- content: `User reject this tool calling ${expectedSuffix}`,- id: 'tool-msg-1',- intervention: {- rejectedReason: rejectionReason,- resolutionRequestId: expect.stringMatching(/^legacy_/),- status: 'rejected',+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ {+ content: `User reject this tool calling ${expectedSuffix}`,+ id: 'tool-msg-1',+ intervention: {+ rejectedReason: rejectionReason,+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'rejected',+ },},- },- ]);+ ],+ { publishResult: true },+ );expect(mockCreateOperation).toHaveBeenCalledWith(expect.objectContaining({@@ -500,17 +509,20 @@ describe('AiAgentService.execAgent - resumeApproval', () => {},});- expect(mockResolveHumanApproval).toHaveBeenCalledWith([- {- content: 'User reject this tool calling without reason',- id: 'tool-msg-1',- intervention: {- rejectedReason: undefined,- resolutionRequestId: expect.stringMatching(/^legacy_/),- status: 'rejected',+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ {+ content: 'User reject this tool calling without reason',+ id: 'tool-msg-1',+ intervention: {+ rejectedReason: undefined,+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'rejected',+ },},- },- ]);+ ],+ { publishResult: true },+ );});it('restores the claimed rows when preparation fails before the continuation starts', async () => {@@ -534,6 +546,7 @@ describe('AiAgentService.execAgent - resumeApproval', () => {claimedResolutionRequestId,id: 'tool-msg-1',intervention: { status: 'pending' },+ pluginError: null,pluginState: null,replacePluginState: true,},@@ -1067,22 +1080,25 @@ describe('AiAgentService.execAgent - resumeApproval', () => {],});- expect(mockResolveHumanApproval).toHaveBeenCalledWith([- {- id: 'tool-msg-1',- intervention: {- resolutionRequestId: expect.stringMatching(/^legacy_/),- status: 'approved',+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ {+ id: 'tool-msg-1',+ intervention: {+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'approved',+ },},- },- {- id: 'tool-msg-2',- intervention: {- resolutionRequestId: expect.stringMatching(/^legacy_/),- status: 'approved',+ {+ id: 'tool-msg-2',+ intervention: {+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'approved',+ },},- },- ]);+ ],+ { publishResult: true },+ );expect(mockCreateOperation).toHaveBeenCalledWith(expect.objectContaining({initialContext: expect.objectContaining({@@ -1194,18 +1210,21 @@ describe('AiAgentService.stopPendingApproval', () => {// In place: the approval pause already wrote these rows. Inserting fresh// aborted rows would duplicate every tool AND leave the originals pending,// which is what keeps the approval cards on screen after a stop.- expect(mockResolveHumanApproval).toHaveBeenCalledWith([- {- content: 'Tool execution was aborted by user.',- id: 'tool-msg-1',- intervention: { status: 'aborted' },- },- {- content: 'Tool execution was aborted by user.',- id: 'tool-msg-2',- intervention: { status: 'aborted' },- },- ]);+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ {+ content: 'Tool execution was aborted by user.',+ id: 'tool-msg-1',+ intervention: { status: 'aborted' },+ },+ {+ content: 'Tool execution was aborted by user.',+ id: 'tool-msg-2',+ intervention: { status: 'aborted' },+ },+ ],+ { publishResult: true },+ );// The exact parked operation and sealed batch identity are validated; a// newer operation in the same topic can never be guessed and interrupted.@@ -1234,6 +1253,7 @@ describe('AiAgentService.stopPendingApproval', () => {intervention: { resolutionRequestId: approvalResolutionRequestId, status: 'aborted' },}),]),+ { publishResult: true },);});diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.tsindex c4af0b9bd62..2a56c39f92b 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';const {+ mockControlToolResult,mockCreateOperation,mockFindById,mockFindMessagePlugin,@@ -17,6 +18,7 @@ const {mockUpdatePluginState,mockUpdateToolMessage,} = vi.hoisted(() => ({+ mockControlToolResult: vi.fn(),mockCreateOperation: vi.fn(),mockFindById: vi.fn(),mockFindMessagePlugin: vi.fn(),@@ -125,6 +127,7 @@ vi.mock('@/database/models/userMemory/persona', () => ({vi.mock('@/server/services/agentRuntime', () => ({AgentRuntimeService: vi.fn().mockImplementation(function () {return {+ controlCompletedToolResult: mockControlToolResult,createOperation: mockCreateOperation,ensureInterventionContinuationStarted: vi.fn().mockResolvedValue('scheduled'),loadInterventionContinuationState: mockLoadInterventionContinuationState,@@ -206,6 +209,11 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {beforeEach(() => {vi.clearAllMocks();+ mockControlToolResult.mockImplementation(async ({ result }) => ({+ result,+ blocked: false,+ cancelled: false,+ }));mockCreateOperation.mockResolvedValue({autoStarted: true,messageId: 'queue-msg-1',@@ -223,7 +231,7 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {mockRestoreHumanApproval.mockResolvedValue(undefined);mockUpdateMessagePlugin.mockResolvedValue(undefined);mockUpdatePluginState.mockResolvedValue(undefined);- mockUpdateToolMessage.mockResolvedValue(undefined);+ mockUpdateToolMessage.mockResolvedValue({ success: true });service = new AiAgentService({} as unknown as LobeChatDatabase, 'user-1');});@@ -246,16 +254,19 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {// Content, intervention, and optional form state share one row-locking// first-winner boundary.- expect(mockResolveHumanApproval).toHaveBeenCalledWith([- expect.objectContaining({- content: 'My favorite color is blue',- id: 'tool-msg-1',- intervention: {- resolutionRequestId: expect.stringMatching(/^legacy_/),- status: 'approved',- },- }),- ]);+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ expect.objectContaining({+ content: 'My favorite color is blue',+ id: 'tool-msg-1',+ intervention: {+ resolutionRequestId: expect.stringMatching(/^legacy_/),+ status: 'approved',+ },+ }),+ ],+ { publishResult: true },+ );// Resumes from `tool_result` β NOT `human_approved_tool` (which would// re-dispatch the tool and overwrite the answer).@@ -274,6 +285,137 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {expect(call.initialContext.phase).not.toBe('human_approved_tool');});+ it('withholds a human tool answer before loading continuation history', async () => {+ const secret = 'synthetic-private-answer';+ const blocked = {+ content: 'Tool result withheld by afterToolCall hook.',+ error: 'hook_denied',+ state: {+ phase: 'afterToolCall',+ type: 'blocked',+ reason: 'Tool result withheld by afterToolCall hook.',+ },+ success: false,+ };+ mockControlToolResult.mockResolvedValue({+ result: blocked,+ blocked: true,+ cancelled: false,+ });+ mockUpdateToolMessage.mockResolvedValue({ success: true });+ await service.execAgent({+ ...baseParams,+ resumeToolResult: {+ content: secret,+ pluginState: { answer: secret },+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_ask',+ },+ });+ expect(mockControlToolResult).toHaveBeenCalledWith({+ operationId: undefined,+ toolMessageId: 'tool-msg-1',+ result: { content: secret, state: { answer: secret }, success: true },+ });+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ expect.objectContaining({+ content: blocked.content,+ pluginState: blocked.state,+ replacePluginState: true,+ }),+ ],+ { publishResult: true },+ );+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ expect.objectContaining({+ content: blocked.content,+ pluginError: 'hook_denied',+ replacePluginState: true,+ }),+ ],+ { publishResult: true },+ );+ expect(mockResolveHumanApproval.mock.invocationCallOrder[0]).toBeLessThan(+ mockMessageQuery.mock.invocationCallOrder[0],+ );+ expect(JSON.stringify(mockCreateOperation.mock.calls[0][0].initialContext)).not.toContain(+ secret,+ );+ });++ it('does not start a continuation when withholding the persisted answer fails', async () => {+ mockControlToolResult.mockResolvedValue({+ blocked: true,+ cancelled: false,+ result: {+ content: 'withheld',+ state: { phase: 'afterToolCall', type: 'blocked' },+ success: false,+ },+ });+ mockResolveHumanApproval.mockRejectedValueOnce(new Error('Failed to publish tool result'));+ await expect(+ service.execAgent({+ ...baseParams,+ resumeToolResult: {+ content: 'private answer',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_ask',+ },+ }),+ ).rejects.toThrow('Failed to publish tool result');+ expect(mockCreateOperation).not.toHaveBeenCalled();+ expect(mockMessageQuery).not.toHaveBeenCalled();+ });++ it('restores the original error on startup failure and clears it on an allowed retry', async () => {+ const originalError = { message: 'old tool error' };+ mockFindMessagePlugin.mockResolvedValue({ ...pendingToolPlugin, error: originalError });+ mockControlToolResult.mockResolvedValueOnce({+ blocked: true,+ cancelled: false,+ result: {+ content: 'withheld',+ error: 'hook_denied',+ state: { phase: 'afterToolCall', type: 'blocked' },+ success: false,+ },+ });+ mockCreateOperation.mockRejectedValueOnce(new Error('startup failed'));+ const params = {+ ...baseParams,+ resumeToolResult: {+ content: 'answer',+ parentMessageId: 'tool-msg-1',+ toolCallId: 'call_ask',+ },+ };+ await expect(service.execAgent(params)).resolves.toMatchObject({+ success: false,+ error: 'startup failed',+ });+ expect(mockRestoreHumanApproval).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'tool-msg-1', pluginError: originalError }),+ ]);+ mockControlToolResult.mockResolvedValueOnce({+ blocked: false,+ cancelled: false,+ result: { content: 'answer', success: true },+ });+ await service.execAgent(params);+ expect(mockResolveHumanApproval).toHaveBeenLastCalledWith(+ [+ expect.objectContaining({+ content: 'answer',+ pluginError: null,+ }),+ ],+ { publishResult: true },+ );+ });+it('persists pluginState when provided', async () => {await service.execAgent({...baseParams,@@ -285,11 +427,14 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {},});- expect(mockResolveHumanApproval).toHaveBeenCalledWith([- expect.objectContaining({- pluginState: { askUserAnswers: { 'favorite color?': 'blue' } },- }),- ]);+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ expect.objectContaining({+ pluginState: { askUserAnswers: { 'favorite color?': 'blue' } },+ }),+ ],+ { publishResult: true },+ );});it('does not persist pluginState when omitted', async () => {@@ -302,9 +447,10 @@ describe('AiAgentService.execAgent - resumeToolResult', () => {},});- expect(mockResolveHumanApproval).toHaveBeenCalledWith([- expect.objectContaining({ pluginState: undefined }),- ]);+ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [expect.objectContaining({ pluginState: undefined })],+ { publishResult: true },+ );});describe('validation guards', () => {diff --git a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts b/apps/server/src/services/aiAgent/hooks/threadRunHooks.tsindex 9c5d8718c59..8219cd48dc8 100644--- a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts+++ b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts@@ -182,7 +182,7 @@ export function createThreadHooks(messageModel: MessageModel,threadId: string,startedAt: string,- sourceMessageId: string,+ sourceMessageId: string | undefined,logScope: 'execSubAgent' | 'execVirtualSubAgent',usageBaseline: ThreadUsageBaseline = {},): AgentHook[] {@@ -255,13 +255,14 @@ export function createThreadHooks(}try {- // Update source message with summary+ // Bridged runs publish through result control; only standalone thread+ // runs own a source-message summary write here.const lastAssistantMessage = finalState.messages?.slice().reverse().find((m: { role: string }) => m.role === 'assistant');- if (lastAssistantMessage?.content) {+ if (sourceMessageId && lastAssistantMessage?.content) {await messageModel.update(sourceMessageId, {content: lastAssistantMessage.content,});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 2b5d12f634c..0427f7f3273 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -572,7 +572,8 @@ export class AiAgentService {this.messageModel,thread.id,thread.metadata?.startedAt ?? new Date().toISOString(),- thread.sourceMessageId,+ // The recovered group-member bridge owns result publication.+ undefined,'execVirtualSubAgent',pickThreadUsageBaseline(thread.metadata),);@@ -1149,9 +1150,13 @@ export class AiAgentService {approvedToolEntries,batchApprovalAnchorId,resumeApprovalPlugin,+ resolvedToolResult,} = await traceSendStage('approval_claim', () =>claimApprovalResume(- { messageModel: this.messageModel },+ {+ controlToolResult: (input) => this.agentRuntimeService.controlCompletedToolResult(input),+ messageModel: this.messageModel,+ },{appContext,approvalClaim,@@ -1453,7 +1458,7 @@ export class AiAgentService {resumeApprovalPlugin,resumeApprovals,resumeFromHistory: runFromHistory,- resumeToolResult,+ resumeToolResult: resolvedToolResult,runAttachments,selectedToolIds,topicBoundDeviceId: turn.topicBoundDeviceId,diff --git a/apps/server/src/services/aiAgent/intervention/InterventionController.ts b/apps/server/src/services/aiAgent/intervention/InterventionController.tsindex a7582ca3e7b..7f4d1b5ffda 100644--- a/apps/server/src/services/aiAgent/intervention/InterventionController.ts+++ b/apps/server/src/services/aiAgent/intervention/InterventionController.ts@@ -368,20 +368,19 @@ export class InterventionController {throw new Error('stopPendingApproval: interrupted operation has unsettled batch members');}- if (alreadyClaimedCount === 0) {- await this.deps.messageModel.resolveHumanApproval(- targets.map((target) => ({- content: STOPPED_TOOL_CONTENT,- id: target.id,- intervention: {- ...(approvalResolutionRequestId && {- resolutionRequestId: approvalResolutionRequestId,- }),- status: 'aborted',- },- })),- );- }+ await this.deps.messageModel.resolveHumanApproval(+ targets.map((target) => ({+ content: STOPPED_TOOL_CONTENT,+ id: target.id,+ intervention: {+ ...(approvalResolutionRequestId && {+ resolutionRequestId: approvalResolutionRequestId,+ }),+ status: 'aborted',+ },+ })),+ { publishResult: true },+ );// Read before the interrupt retires the runtime snapshot.const groupMember = await this.deps.agentRuntimeService.loadGroupMemberBridge(operationId);diff --git a/apps/server/src/services/aiAgent/pipeline/approvalResume.ts b/apps/server/src/services/aiAgent/pipeline/approvalResume.tsindex 299739a5bd5..45d6e69eca7 100644--- a/apps/server/src/services/aiAgent/pipeline/approvalResume.ts+++ b/apps/server/src/services/aiAgent/pipeline/approvalResume.ts@@ -62,6 +62,8 @@ export interface ClaimedApprovalResume {* tool row you happened to pick and on the order they were written in.*/batchApprovalAnchorId?: string;+ /** Sanitized input for any deferred continuation initialization. */+ resolvedToolResult?: InternalExecAgentParams['resumeToolResult'];/** Plugin row of the op-level anchor message (single-decision 16b context). */resumeApprovalPlugin?: MessagePluginItem;}@@ -89,7 +91,10 @@ export interface ClaimedApprovalResume {* the plugin row and must be fetched separately.*/export const claimApprovalResume = async (- deps: { messageModel: MessageModel },+ deps: {+ controlToolResult: AgentRuntimeService['controlCompletedToolResult'];+ messageModel: MessageModel;+ },input: ClaimApprovalResumeInput,): Promise<ClaimedApprovalResume> => {const {@@ -104,6 +109,7 @@ export const claimApprovalResume = async (resumeToolResult,} = input;+ let resolvedToolResult = resumeToolResult;let resumeApprovalPlugin: MessagePluginItem | undefined;const approvedToolEntries: {createdAt: Date;@@ -213,15 +219,16 @@ export const claimApprovalResume = async (...(typeof targetMessage.content === 'string' ? { content: targetMessage.content } : {}),id: targetMessage.id,intervention: (plugin.intervention ?? { status: 'pending' }) as Record<string, unknown>,+ pluginError: plugin.error ?? null,pluginState: (plugin.state ?? null) as Record<string, unknown> | null,replacePluginState: true,}));// Shared exactly-once boundary for Web, Mobile, Stop, and signed system// actions. All rows are locked and checked before the first write.- if (unclaimedDecisions.length > 0) {+ if (validatedDecisions.length > 0) {const claimState = await deps.messageModel.resolveHumanApproval(- unclaimedDecisions.map(({ entry }) => {+ validatedDecisions.map(({ entry }) => {if (entry.decision === 'approved') {return {id: entry.parentMessageId,@@ -243,6 +250,7 @@ export const claimApprovalResume = async (},};}),+ { publishResult: true },);if (claimState === 'applied') {approvalClaim.rollbackSnapshot = approvalRollbackSnapshot;@@ -343,21 +351,39 @@ export const claimApprovalResume = async (: [{claimedResolutionRequestId: approvalResolutionRequestId,- ...(typeof resumeParentMessage.content === 'string'- ? { content: resumeParentMessage.content }- : {}),+ content:+ typeof resumeParentMessage.content === 'string' ? resumeParentMessage.content : '',id: resumeToolResult.parentMessageId,intervention: (resumeToolResultPlugin.intervention ?? {status: 'pending',}) as Record<string, unknown>,+ pluginError: resumeToolResultPlugin.error ?? null,pluginState: (resumeToolResultPlugin.state ?? null) as Record<string, unknown> | null,replacePluginState: true,},];- if (!alreadyClaimed) {- const claimState = await deps.messageModel.resolveHumanApproval([+ const controlled = await deps.controlToolResult({+ operationId: approvalSourceOperationId,+ toolMessageId: resumeToolResult.parentMessageId,+ result: {+ content: resumeToolResult.content,+ state: resumeToolResult.pluginState,+ success: !skipped,+ },+ });+ const result = controlled.result;+ const withheld = controlled.blocked;+ resolvedToolResult = {+ ...resumeToolResult,+ content: result.content,+ pluginState: result.state,+ };+ // Source adapters only claim the decision. Publish the final hook result+ // with the claim in one transaction, or finish an existing same-owner claim.+ const claimState = await deps.messageModel.resolveHumanApproval(+ [{- content: resumeToolResult.content,+ content: result.content,id: resumeToolResult.parentMessageId,intervention: skipped? {@@ -367,12 +393,28 @@ export const claimApprovalResume = async (status: 'rejected',}: { resolutionRequestId: approvalResolutionRequestId, status: 'approved' },- pluginState: resumeToolResult.pluginState,+ pluginError: result.error ?? null,+ pluginState: result.state,+ ...(withheld && { replacePluginState: true }),},+ ],+ { publishResult: true },+ );+ if (claimState === 'applied' && !alreadyClaimed) {+ approvalClaim.rollbackSnapshot = approvalRollbackSnapshot;+ } else if (claimState === 'idempotent') {+ // A duplicate continuation must also use the first published result in+ // memory, including a denial, rather than the replay's incoming answer.+ const [stored, plugin] = await Promise.all([+ deps.messageModel.findById(resumeToolResult.parentMessageId),+ deps.messageModel.findMessagePlugin(resumeToolResult.parentMessageId),]);- if (claimState === 'applied') {- approvalClaim.rollbackSnapshot = approvalRollbackSnapshot;- }+ if (!stored) throw new Error('Resolved tool message is unavailable');+ resolvedToolResult = {+ ...resumeToolResult,+ content: stored.content ?? '',+ pluginState: plugin?.state ?? undefined,+ };}if (providedApprovalResolutionRequestId) {approvalClaim.continuationPrepared = true;@@ -393,6 +435,7 @@ export const claimApprovalResume = async (approvedToolEntries,batchApprovalAnchorId,resumeApprovalPlugin,+ resolvedToolResult,};};diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.tsindex 860edaf3e9e..5498e26a5ff 100644--- a/apps/server/src/services/aiAgent/subAgentRuns.ts+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts@@ -258,23 +258,24 @@ export const execAgentThreadRun = async (});}- // 3. Create hooks for updating Thread metadata and source message+ const hasCompletionBridge = Boolean(options.resumeParentOnComplete && parentOperationId);+ // 3. Thread hooks always own metadata. A completion bridge exclusively owns+ // the tool result so no summary can publish before its afterToolCall control.const threadHooks = createThreadHooks(deps.agentRuntimeService,deps.threadModel,deps.messageModel,thread.id,startedAt,- parentMessageId,+ hasCompletionBridge ? undefined : parentMessageId,options.logScope,usageBaseline,);// For the virtual sub-agent path, also register the completion bridge that// backfills the parent's placeholder tool message and resumes the parked- // parent op once the child run is done. Registered last so its tool-message- // backfill (content + pluginState) is the final write.+ // parent op once the child run is done.const hooks =- options.resumeParentOnComplete && parentOperationId+ hasCompletionBridge && parentOperationId? [...threadHooks,options.bridgeHookFactorydiff --git a/docs/development/agent-tool-result-hooks.md b/docs/development/agent-tool-result-hooks.mdnew file mode 100644index 00000000000..7a93a679326--- /dev/null+++ b/docs/development/agent-tool-result-hooks.md@@ -0,0 +1,97 @@+# Controlling tool results with afterToolCall++`afterToolCall` can synchronously decide whether a completed tool result may enter the next model turn. It uses the same flat HTTP allow/deny protocol as `beforeToolCall`.++This is a **result gate**. The tool has already executed, so denying its output does not undo file writes, network requests, child-agent work, or messages already posted to a shared conversation.++## Register a result control++```ts+const hooks = [+ {+ id: 'check-tool-result',+ type: 'afterToolCall',+ matcher: '^files/readFile$',+ webhook: {+ url: 'https://example.com/tool-policy',+ delivery: 'fetch',+ responseHandling: 'toolCall',+ onError: 'block',+ timeout: 5,+ },+ },+];+```++The webhook receives the normal tool correlation fields (`operationId`, native `toolCallId`, `assistantMessageId`, tool identifier/API, effective `args`, and available run context) plus `mocked` and `result`. For controls, `result` is the complete result returned to the server runtime, including content, error/state, execution timing, and Work-registration intent. It is sent **before** content truncation, archival, and observation-event redaction. The policy receiver is therefore a trusted destination for the original result, including any sensitive data it contains.++Reply with HTTP 200 and either:++```json+{ "decision": "allow" }+```++```json+{ "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`.++Matching controls run in registration order. A deny stops the remaining controls for that result. With no matching controls, normal behavior is unchanged. Ordinary `afterToolCall` handlers/webhooks remain notifications; their returned bodies do not control execution.++## 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+- 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-200 responses (including 204), invalid/missing decisions, oversized/malformed responses, network failures, and timeouts use the existing `onError` policy: `continue` by default, or `block` for fail-closed operation. 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++The existing `AGENT_HOOK_WEBHOOK_URL`, `AGENT_HOOK_WEBHOOK_TOKEN`, `AGENT_HOOK_WEBHOOK_EVENTS`, and `AGENT_HOOK_WEBHOOK_ON_ERROR` settings are reused.++`AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING` selects which configured events are controls:++| Value | beforeToolCall | afterToolCall |+| ------------------------------ | -------------- | ------------- |+| `ignore` (default) | Notification | Notification |+| `toolCall` (existing behavior) | Control | Notification |+| `toolResult` | Notification | Control |+| `toolCallAndResult` | Control | Control |++Only events listed in `AGENT_HOOK_WEBHOOK_EVENTS` are enabled. A control mode requires at least one corresponding event; unsupported values and incompatible configurations fail validation. Other lifecycle events remain notifications. The environment mode names are intentionally distinct from the per-hook registration's `responseHandling: 'toolCall'`, which identifies the shared decision protocol.++For after-only fail-closed checking:++```dotenv+AGENT_HOOK_WEBHOOK_URL=https://example.com/tool-policy+AGENT_HOOK_WEBHOOK_TOKEN=your-server-side-token+AGENT_HOOK_WEBHOOK_EVENTS=afterToolCall+AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING=toolResult+AGENT_HOOK_WEBHOOK_ON_ERROR=block+```++Existing deployments using `EVENTS=beforeToolCall,afterToolCall` with `RESPONSE_HANDLING=toolCall` keep their original behavior; after notifications do not silently become result controls. All executing server/worker processes need the intended configuration. Environment hooks continue to use current process configuration rather than persisted copies.++## Publication, configuration lifetime, and rollout++A result remains in memory while its hook runs. The runtime then writes either the allowed result or the sanitized denial, before streaming or loading the next model context. Message history reads the stored result directly; there is no persisted pending/allowed/blocked review marker and no result-review projection.++Human-answer source adapters only claim the decision and retain the answer in their private resolution/outbox. `MessageModel.resolveHumanApproval` defaults to claim-only; the runtime opts into `publishResult: true` after the hook returns, atomically writing content, error, and state. An already claimed answer follows the same publication path. Failed writes can retry; failed continuation startup restores the original approval snapshot. Cloud overrides must obey this claim-before-publication contract and must not write raw answers through other message APIs.++Caller webhook configuration stays on the private durable operation record in its existing serialized template format, so a cold worker can recover it after Redis expiry. The existing approval intervention and deferred callback identify the original operation; no additional message review metadata is needed. Environment hooks always come from the executing worker's current environment. After approval or deferred completion, evaluate each operation's caller hooks in order, followed by current environment hooks once. Caller hook IDs are scoped to their operation; identical IDs across operations do not deduplicate policies. Environment-only hooks do not require durable operation storage. Removing an environment hook stops it controlling future results; no matching control means allow. Newly configured environment hooks affect subsequent evaluations. Configured hook delivery failures follow `onError`; caller-policy storage failures propagate for retry.++Deferred completions write into the existing empty tool placeholder once. Later callbacks cannot replace its first final result, including a denial after the hook has been removed. This uses ordinary completion idempotency, not a persisted policy verdict. Receivers should still tolerate repeated control requests.++Roll out updated code and the claim-only source-adapter contract to all executing workers before enabling result controls. Results already published cannot be retroactively withdrawn.++## Execution boundaries++Controls cover the server runtime's ordinary and batched tools, local mocks, gateway-dispatched client/device results, and returned failures. Deferred child-agent results and isolated group-member result anchors and member startup failures are checked before their completion backfills, using the parent tool request and each destination `toolMessageId`. A multi-member call can therefore produce a control request for each result anchor and another for its final group receipt. Re-delivery may repeat a control request; receivers should be idempotent. Human tool-answer continuations are checked before loading the next conversation history, including already-claimed source resolutions.++These are server-runtime hooks. The legacy in-browser `ClientToolTransport` and independently running heterogeneous CLI agents do not acquire a server webhook dispatcher through this change. Gateway mode requires a configured `agentGatewayUrl`, enabled gateway mode, and no per-agent/user `disableGatewayMode` override. Do not put server webhook credentials in the browser.++The gate is not a general-purpose chat/UI/log redaction system. Previously published group-member messages, child-agent history, files already created by a tool, and independent copies of data are outside the withheld tool-result boundary. A later tool read is a new call and must be covered by the desired matcher/policy as well.diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex 7def6d10bf2..dba40624311 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -89,6 +89,10 @@ const requireToolTransport = (host: AgentRuntimeHost) => {const toolNameOf = (tool: ChatToolPayload) => `${tool.identifier}/${tool.apiName}`;+// Execution-entry denial is free; withholding an already executed result is not.+const isBlockedBeforeExecution = (result: ToolRunResult) =>+ result.state?.type === 'blocked' && result.state.phase !== 'afterToolCall';+const resolveToolSource = (state: AgentState, tool: ChatToolPayload): string | undefined =>selectToolSourceMap(state)[tool.identifier];@@ -464,12 +468,14 @@ const createToolMessage = async ({host,parentMessageId,result,+ resultBlocked,state,tool,}: {host: AgentRuntimeHost;parentMessageId: string;result: ToolRunResult;+ resultBlocked?: boolean;state: AgentState;tool: ChatToolPayload;}) => {@@ -488,9 +494,9 @@ const createToolMessage = async ({metadata: { toolExecutionTimeMs: result.executionTime ?? 0 },parentId: parentMessageId,plugin: tool as any,- pluginError: result.error,- ...(result.state?.type === 'blocked' && {- pluginIntervention: { rejectedReason: result.state.reason, status: 'rejected' },+ pluginError: result.error ?? null,+ ...((isBlockedBeforeExecution(result) || resultBlocked) && {+ pluginIntervention: { rejectedReason: result.state?.reason, status: 'rejected' },}),pluginState: result.state,role: 'tool',@@ -507,22 +513,25 @@ const createToolMessage = async ({const updateExistingToolMessage = async ({host,result,+ resultBlocked,toolMessageId,}: {host: AgentRuntimeHost;result: ToolRunResult;+ resultBlocked?: boolean;toolMessageId: string;}) => {try {await host.transports.messages.updateToolMessage(toolMessageId, {content: result.content,metadata: { toolExecutionTimeMs: result.executionTime ?? 0 },- pluginError: result.error,+ pluginError: result.error ?? null,pluginState: result.state,+ ...(resultBlocked && { replacePluginState: true }),});- if (result.state?.type === 'blocked') {+ if (isBlockedBeforeExecution(result) || resultBlocked) {await host.transports.messages.updateToolIntervention(toolMessageId, {- rejectedReason: result.state.reason,+ rejectedReason: result.state?.reason,status: 'rejected',});}@@ -665,10 +674,9 @@ export const callTool =executionTime,isSuccess,attempts: execution.attempts,- maxAttempts:- executionResult.state?.type === 'blocked'- ? 0- : (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,+ maxAttempts: isBlockedBeforeExecution(executionResult)+ ? 0+ : (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,payload,phase: TOOL_EXECUTION_PHASE,result: redactResultForEvents(executionResult),@@ -681,16 +689,27 @@ export const callTool =if (execution.toolMessageId) {toolMessageId = execution.toolMessageId;if (!execution.resultPersisted) {- await updateExistingToolMessage({ host, result: executionResult, toolMessageId });+ await updateExistingToolMessage({+ host,+ result: executionResult,+ toolMessageId,+ resultBlocked: execution.resultBlocked,+ });}} else if (payload.skipCreateToolMessage) {toolMessageId = payload.parentMessageId;- await updateExistingToolMessage({ host, result: executionResult, toolMessageId });+ await updateExistingToolMessage({+ host,+ result: executionResult,+ toolMessageId,+ resultBlocked: execution.resultBlocked,+ });} else {const toolMessage = await createToolMessage({host,parentMessageId: payload.parentMessageId,result: executionResult,+ resultBlocked: execution.resultBlocked,state,tool,});@@ -729,8 +748,9 @@ export const callTool =type: 'tool_result',});- const toolCost =- executionResult.state?.type === 'blocked' ? 0 : (tools.getCost?.(runContext.toolName) ?? 0);+ const toolCost = isBlockedBeforeExecution(executionResult)+ ? 0+ : (tools.getCost?.(runContext.toolName) ?? 0);const { usage, cost } = UsageCounter.accumulateTool({cost: newState.cost,executionTime,@@ -982,10 +1002,9 @@ export const callToolsBatch =executionTime,isSuccess,attempts: execution.attempts,- maxAttempts:- executionResult.state?.type === 'blocked'- ? 0- : (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,+ maxAttempts: isBlockedBeforeExecution(executionResult)+ ? 0+ : (tools.maxRetries ?? DEFAULT_TOOL_MAX_RETRIES) + 1,payload: { parentMessageId, toolCalling: tool },phase: TOOL_EXECUTION_PHASE,result: redactResultForEvents(executionResult),@@ -998,19 +1017,30 @@ export const callToolsBatch =if (execution.toolMessageId) {toolMessageId = execution.toolMessageId;if (!execution.resultPersisted) {- await updateExistingToolMessage({ host, result: executionResult, toolMessageId });+ await updateExistingToolMessage({+ host,+ result: executionResult,+ toolMessageId,+ resultBlocked: execution.resultBlocked,+ });}} else if (existingMessageId) {// Batch approval resume: fill the pending placeholder in place.// Creating a fresh row here would leave the approved-but-empty// original stranded under the same assistant.toolMessageId = existingMessageId;- await updateExistingToolMessage({ host, result: executionResult, toolMessageId });+ await updateExistingToolMessage({+ host,+ result: executionResult,+ toolMessageId,+ resultBlocked: execution.resultBlocked,+ });} else {const toolMessage = await createToolMessage({host,parentMessageId,result: executionResult,+ resultBlocked: execution.resultBlocked,state,tool,});@@ -1036,10 +1066,9 @@ export const callToolsBatch =type: 'tool_result',});- const toolCost =- executionResult.state?.type === 'blocked'- ? 0- : (tools.getCost?.(runContext.toolName) ?? 0);+ const toolCost = isBlockedBeforeExecution(executionResult)+ ? 0+ : (tools.getCost?.(runContext.toolName) ?? 0);resultEntry.usageParams = {executionTime,success: isSuccess,diff --git a/packages/agent-runtime/src/transport/message.ts b/packages/agent-runtime/src/transport/message.tsindex c48d1e8f82e..a4d4ab83eea 100644--- a/packages/agent-runtime/src/transport/message.ts+++ b/packages/agent-runtime/src/transport/message.ts@@ -47,6 +47,8 @@ export interface UpdateToolMessageInput {metadata?: Record<string, any>;pluginError?: unknown;pluginState?: Record<string, any>;+ /** A result gate must not retain keys from a previous complete result. */+ replacePluginState?: boolean;}/**diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.tsindex 1b9d0d5bf76..568d136ec23 100644--- a/packages/agent-runtime/src/transport/tool.ts+++ b/packages/agent-runtime/src/transport/tool.ts@@ -76,6 +76,8 @@ export interface ToolRunExecution {interrupted?: boolean;mocked?: boolean;result: ToolRunResult;+ /** Server-owned verdict; tools cannot supply this through their result. */+ resultBlocked?: boolean;/** The transport already persisted the result into its tool message. */resultPersisted?: boolean;/** Existing/pre-created tool message owned by the transport. */diff --git a/packages/agent-runtime/src/types/hooks.ts b/packages/agent-runtime/src/types/hooks.tsindex c329445cd06..c577db2840e 100644--- a/packages/agent-runtime/src/types/hooks.ts+++ b/packages/agent-runtime/src/types/hooks.ts@@ -20,7 +20,7 @@ import type { ToolRunResult } from '../transport/tool';*/export type AgentHookType =| 'afterStep' // After each step completes- | 'afterToolCall' // After a tool call completes (observation only)+ | 'afterToolCall' // After a tool call completes (supports result allow/deny controls)| 'beforeStep' // Before each step executes| 'beforeToolCall' // Before a tool call executes (supports mocking via event.mock())| 'beforeCallAgent' // Before calling a sub-agent@@ -212,7 +212,7 @@ export type BeforeToolCallObservationEvent = ToolCallHookContext;export interface AfterToolCallHookEvent extends ToolCallHookContext {/** Whether a beforeToolCall hook supplied the result through mock(). */mocked: boolean;- /** Structured result after archival, including errors and state (e.g. blocked). */+ /** Complete pre-archive result for controls; post-archive result for notifications. */result: ToolRunResult;}diff --git a/packages/business-server/src/agent-run/agentInterventionReview.ts b/packages/business-server/src/agent-run/agentInterventionReview.tsindex 2a15a0d48d7..4ef28663a88 100644--- a/packages/business-server/src/agent-run/agentInterventionReview.ts+++ b/packages/business-server/src/agent-run/agentInterventionReview.ts@@ -560,7 +560,13 @@ export async function getAgentInterventionReviewBySource(return { handled: false };}-/** Atomic, idempotent first-winner claim. OSS fails closed for token-based v2 resolution. */+/**+ * Atomic, idempotent first-winner claim. Keep submitted answers in the private+ * resolution/outbox; never write raw content or result state into chat messages.+ * Runtime dispatch applies afterToolCall before publishing the final result.+ * MessageModel.resolveHumanApproval defaults to this claim-only behavior.+ * OSS fails closed for token-based v2 resolution.+ */export async function resolveAgentIntervention(_params: ResolveAgentInterventionParams,): Promise<ResolveAgentInterventionResult> {@@ -571,6 +577,7 @@ export async function resolveAgentIntervention(* Authenticated Web bridge into the generic first-winner claim.** Cloud resolves the source locators and builds the canonical item action.+ * Like resolveAgentIntervention, it claims only; runtime dispatch publishes answers.* For a mixed partially-settled Stop it supplies a full-batch version/revision* snapshot while selecting only rows that are still pending; terminal siblings* remain immutable. OSS has no durable generic store and falls back to itsdiff --git a/packages/database/src/models/__tests__/messages/message.update.test.ts b/packages/database/src/models/__tests__/messages/message.update.test.tsindex 64803d46cfb..fb9d12e0a1a 100644--- a/packages/database/src/models/__tests__/messages/message.update.test.ts+++ b/packages/database/src/models/__tests__/messages/message.update.test.ts@@ -696,16 +696,19 @@ describe('MessageModel Update Tests', () => {it('preserves sealed operation/batch identity while applying a claim patch', async () => {await seedPendingTool('approval-preserves-identity');- await messageModel.resolveHumanApproval([- {- id: 'approval-preserves-identity',- intervention: {- resolutionRequestId: 'resolution-1',- status: 'approved',+ await messageModel.resolveHumanApproval(+ [+ {+ id: 'approval-preserves-identity',+ intervention: {+ resolutionRequestId: 'resolution-1',+ status: 'approved',+ },+ pluginState: { approvedBy: 'review' },},- pluginState: { approvedBy: 'review' },- },- ]);+ ],+ { publishResult: true },+ );const [plugin] = await serverDB.select()@@ -728,17 +731,20 @@ describe('MessageModel Update Tests', () => {});await expect(- messageModel.resolveHumanApproval([- {- content: 'must not commit',- id: 'approval-atomic-pending',- intervention: { resolutionRequestId: 'resolution-loser', status: 'approved' },- },- {- id: 'approval-atomic-settled',- intervention: { resolutionRequestId: 'resolution-loser', status: 'approved' },- },- ]),+ messageModel.resolveHumanApproval(+ [+ {+ content: 'must not commit',+ id: 'approval-atomic-pending',+ intervention: { resolutionRequestId: 'resolution-loser', status: 'approved' },+ },+ {+ id: 'approval-atomic-settled',+ intervention: { resolutionRequestId: 'resolution-loser', status: 'approved' },+ },+ ],+ { publishResult: true },+ ),).rejects.toBeInstanceOf(HumanApprovalAlreadyResolvedError);const [message] = await serverDB@@ -762,8 +768,8 @@ describe('MessageModel Update Tests', () => {};const results = await Promise.all([- messageModel.resolveHumanApproval([resolution]),- messageModel.resolveHumanApproval([resolution]),+ messageModel.resolveHumanApproval([resolution], { publishResult: true }),+ messageModel.resolveHumanApproval([resolution], { publishResult: true }),]);expect(results.sort()).toEqual(['applied', 'idempotent']);@@ -791,14 +797,17 @@ describe('MessageModel Update Tests', () => {pluginState: { preserved: true },};- await messageModel.resolveHumanApproval([- {- content: 'approved content',- id: original.id,- intervention: { resolutionRequestId: 'resolution-owner', status: 'approved' },- pluginState: { approvedBy: 'review' },- },- ]);+ await messageModel.resolveHumanApproval(+ [+ {+ content: 'approved content',+ id: original.id,+ intervention: { resolutionRequestId: 'resolution-owner', status: 'approved' },+ pluginState: { approvedBy: 'review' },+ },+ ],+ { publishResult: true },+ );await messageModel.restoreHumanApproval([{ ...original, claimedResolutionRequestId: 'resolution-loser' },]);@@ -917,6 +926,221 @@ describe('MessageModel Update Tests', () => {});});+ it('claims a source answer without publishing it before the runtime hook completes', async () => {+ await serverDB+ .insert(messages)+ .values({ id: 'source-claim', userId, role: 'tool', content: '' });+ await serverDB+ .insert(messagePlugins)+ .values({ id: 'source-claim', userId, intervention: { status: 'pending' } });+ await messageModel.resolveHumanApproval([+ {+ id: 'source-claim',+ content: 'unreviewed answer',+ pluginState: { answer: 'unreviewed answer' },+ intervention: { status: 'approved', resolutionRequestId: 'source-request' },+ },+ ]);+ expect((await messageModel.findById('source-claim'))?.content).toBe('');+ expect(+ (await messageModel.findMessagePlugin('source-claim'))?.state ?? {},+ ).not.toHaveProperty('answer');+ });++ it('keeps the first deferred completion when callbacks race', async () => {+ await serverDB+ .insert(messages)+ .values({ id: 'completion-race', userId, role: 'tool', content: '' });+ await serverDB.insert(messagePlugins).values({ id: 'completion-race', userId });+ const results = await Promise.all(+ ['first', 'late'].map((content) =>+ messageModel.updateToolMessage('completion-race', {+ content,+ pluginState: { content },+ onlyIfEmpty: true,+ }),+ ),+ );+ expect(results.filter((result) => result.applied)).toHaveLength(1);+ expect((await messageModel.findById('completion-race'))?.content).toBe('first');+ expect((await messageModel.findMessagePlugin('completion-race'))?.state).toEqual({+ content: 'first',+ });+ });++ it('publishes an already claimed answer atomically and retains it on replay', async () => {+ await serverDB+ .insert(messages)+ .values({ id: 'answer-once', userId, role: 'tool', content: '' });+ await serverDB.insert(messagePlugins).values({+ id: 'answer-once',+ userId,+ state: { old: true },+ intervention: { status: 'pending' },+ });+ const intervention = { status: 'approved', resolutionRequestId: 'answer-request' };+ await messageModel.resolveHumanApproval([+ { id: 'answer-once', intervention, content: 'raw answer' },+ ]);+ expect((await messageModel.queryByIds(['answer-once']))[0].content).toBe('');+ await messageModel.resolveHumanApproval(+ [+ {+ id: 'answer-once',+ intervention,+ content: 'Tool result withheld.',+ pluginError: 'hook_denied',+ pluginState: { type: 'blocked', phase: 'afterToolCall' },+ replacePluginState: true,+ },+ ],+ { publishResult: true },+ );+ expect(+ await messageModel.resolveHumanApproval(+ [+ {+ id: 'answer-once',+ intervention,+ content: 'raw replay',+ pluginError: null,+ pluginState: { answer: 'raw replay' },+ },+ ],+ { publishResult: true },+ ),+ ).toBe('idempotent');+ expect((await messageModel.findById('answer-once'))?.content).toBe('Tool result withheld.');+ expect(await messageModel.findMessagePlugin('answer-once')).toMatchObject({+ error: 'hook_denied',+ state: { type: 'blocked', phase: 'afterToolCall' },+ });+ expect((await messageModel.queryByIds(['answer-once']))[0].metadata ?? {}).not.toHaveProperty(+ 'toolResultControl',+ );+ });++ it.each([null, { message: 'original tool error' }])(+ 'restores the error snapshot after a denied approval continuation fails: %j',+ async (originalError) => {+ await serverDB.insert(messages).values({+ id: 'review-retry',+ userId,+ role: 'tool',+ content: '',+ });+ await serverDB.insert(messagePlugins).values({+ id: 'review-retry',+ userId,+ identifier: 'tool',+ toolCallId: 'retry-call',+ error: originalError,+ state: { awaitingAnswer: true },+ intervention: { status: 'pending' },+ });+ await messageModel.resolveHumanApproval([+ {+ id: 'review-retry',+ content: 'answer',+ intervention: { status: 'approved', resolutionRequestId: 'denied-attempt' },+ },+ ]);+ await messageModel.updateToolMessage('review-retry', {+ content: 'Tool result withheld by afterToolCall hook.',+ pluginError: 'hook_denied',+ pluginState: { phase: 'afterToolCall', type: 'blocked' },+ replacePluginState: true,+ });+ await messageModel.restoreHumanApproval([+ {+ id: 'review-retry',+ content: '',+ pluginState: { awaitingAnswer: true },+ pluginError: originalError,+ intervention: { status: 'pending' },+ claimedResolutionRequestId: 'denied-attempt',+ },+ ]);+ const [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, 'review-retry'));+ expect(plugin.error).toEqual(originalError);+ expect(plugin.state).toEqual({ awaitingAnswer: true });+ expect((await messageModel.findById('review-retry'))?.content).toBe('');+ },+ );++ it('replaces denied result state and prevents a later completion replay from restoring it', async () => {+ await serverDB+ .insert(messages)+ .values({ id: 'tool-withheld', userId, role: 'tool', content: '' });+ await serverDB.insert(messagePlugins).values({+ id: 'tool-withheld',+ toolCallId: 'withheld-call',+ identifier: 'tool',+ state: { private: 'private output' },+ error: { message: 'private output' },+ userId,+ });+ const blocked = { phase: 'afterToolCall', type: 'blocked', reason: 'Tool result withheld.' };+ expect(+ await messageModel.updateToolMessage('tool-withheld', {+ content: 'Tool result withheld.',+ pluginError: 'hook_denied',+ pluginState: blocked,+ replacePluginState: true,+ onlyIfEmpty: true,+ }),+ ).toMatchObject({ success: true, applied: true });+ expect(+ await messageModel.updateToolMessage('tool-withheld', {+ content: 'private output',+ pluginError: null,+ pluginState: { private: 'private output' },+ onlyIfEmpty: true,+ }),+ ).toMatchObject({ success: true, applied: false });+ const [message] = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.id, 'tool-withheld'));+ const [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, 'tool-withheld'));+ expect(message.content).toBe('Tool result withheld.');+ expect(plugin.state).toEqual(blocked);+ expect(plugin.error).toBe('hook_denied');+ });++ it('does not let result replacement modify another userβs tool message', async () => {+ await serverDB.insert(messages).values({+ id: 'foreign-withheld',+ userId: otherUserId,+ role: 'tool',+ content: 'foreign output',+ });+ await serverDB.insert(messagePlugins).values({+ id: 'foreign-withheld',+ identifier: 'tool',+ state: { private: 'foreign output' },+ userId: otherUserId,+ });+ const result = await messageModel.updateToolMessage('foreign-withheld', {+ content: 'withheld',+ pluginState: { phase: 'afterToolCall', type: 'blocked' },+ replacePluginState: true,+ onlyIfEmpty: true,+ });+ expect(result.success).toBe(false);+ const [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, 'foreign-withheld'));+ expect(plugin.state).toEqual({ private: 'foreign output' });+ });+it('preserves independent pluginState patches across concurrent tool-message updates', async () => {await serverDB.insert(messages).values({content: '',diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 1c92035a8fb..dd5dece096d 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -198,6 +198,7 @@ export interface HumanApprovalResolution {content?: string;id: string;intervention: Record<string, unknown>;+ pluginError?: MessagePluginItem['error'] | null;pluginState?: Record<string, unknown> | null;replacePluginState?: boolean;}@@ -4104,7 +4105,10 @@ export class MessageModel {return this.db.update(messages)- .set({ metadata: mergedMetadata, ...(usageToWrite && { usage: usageToWrite }) })+ .set({+ metadata: mergedMetadata,+ ...(usageToWrite && { usage: usageToWrite }),+ }).where(and(eq(messages.id, id), this.ownership()));};@@ -4141,10 +4145,13 @@ export class MessageModel {/*** Resolve an approval batch at one row-locking boundary. Every target is* checked before any write, so Web, Mobile, Stop, and notification actions- * cannot each win a subset of the same assistant turn.+ * cannot each win a subset of the same assistant turn. Source adapters claim+ * only; content/state remain in their private resolution until the runtime+ * passes publishResult after afterToolCall. Stop may publish its fixed receipt.*/resolveHumanApproval = async (resolutions: HumanApprovalResolution[],+ options: { publishResult?: boolean } = {},): Promise<'applied' | 'idempotent'> => {if (resolutions.length === 0) return 'idempotent';@@ -4154,6 +4161,14 @@ export class MessageModel {}return this.db.transaction(async (trx) => {+ // Match deferred completion's lock order (message before plugin).+ const lockedMessages = await trx+ .select({ id: messages.id, content: messages.content })+ .from(messages)+ .where(and(inArray(messages.id, ids), this.ownership()))+ .orderBy(messages.id)+ .for('update');+ const messagesById = new Map(lockedMessages.map((row) => [row.id, row]));const lockedRows = await trx.select({id: messagePlugins.id,@@ -4182,14 +4197,26 @@ export class MessageModel {throw new HumanApprovalAlreadyResolvedError(resolution.id);});const pendingCount = rowStates.filter((state) => state === 'pending').length;- if (pendingCount === 0) return 'idempotent';- if (pendingCount !== resolutions.length) {+ if (pendingCount === 0 && !options.publishResult) return 'idempotent';+ if (pendingCount !== 0 && pendingCount !== resolutions.length) {throw new Error('Human approval batch contains a partial idempotent claim');}+ let published = false;for (const resolution of resolutions) {+ // An already claimed source answer can publish exactly once. A replay+ // retains the first final content, including a hook denial.+ if (+ pendingCount === 0 &&+ (messagesById.get(resolution.id)?.content ||+ (resolution.content === undefined &&+ resolution.pluginState === undefined &&+ resolution.pluginError === undefined))+ )+ continue;+ published = true;const row = lockedById.get(resolution.id)!;- if (resolution.content !== undefined) {+ if (options.publishResult && resolution.content !== undefined) {const [updatedMessage] = await trx.update(messages).set({ content: resolution.content })@@ -4206,18 +4233,21 @@ export class MessageModel {// parked tool row was created so subsequent source reads, Stop,// and rollback still address the same sealed batch.intervention: merge(row.intervention || {}, resolution.intervention),- ...(resolution.pluginState !== undefined && {- state: resolution.replacePluginState- ? resolution.pluginState- : merge(row.state || {}, resolution.pluginState || {}),- }),+ ...(options.publishResult &&+ resolution.pluginError !== undefined && { error: resolution.pluginError }),+ ...(options.publishResult &&+ resolution.pluginState !== undefined && {+ state: resolution.replacePluginState+ ? resolution.pluginState+ : merge(row.state || {}, resolution.pluginState || {}),+ }),}).where(and(eq(messagePlugins.id, resolution.id), this.pluginsOwnership())).returning({ id: messagePlugins.id });if (!updatedPlugin) throw new Error(`Plugin not found: ${resolution.id}`);}- return 'applied';+ return published ? 'applied' : 'idempotent';});};@@ -4227,6 +4257,12 @@ export class MessageModel {await this.db.transaction(async (trx) => {const ids = resolutions.map(({ id }) => id);+ await trx+ .select({ id: messages.id })+ .from(messages)+ .where(and(inArray(messages.id, ids), this.ownership()))+ .orderBy(messages.id)+ .for('update');const lockedRows = await trx.select({ id: messagePlugins.id, intervention: messagePlugins.intervention }).from(messagePlugins)@@ -4255,6 +4291,7 @@ export class MessageModel {.update(messagePlugins).set({intervention: resolution.intervention,+ ...(resolution.pluginError !== undefined && { error: resolution.pluginError }),...(resolution.pluginState !== undefined && { state: resolution.pluginState }),}).where(and(eq(messagePlugins.id, resolution.id), this.pluginsOwnership()));@@ -4626,9 +4663,20 @@ export class MessageModel {metadata?: Record<string, any>;pluginError?: any;pluginState?: Record<string, any>;+ /** Replace rather than merge when withholding a complete tool result. */+ replacePluginState?: boolean;+ /** Finalize a deferred placeholder once; later callbacks cannot replace its result. */+ onlyIfEmpty?: boolean;},): Promise<{ applied: boolean; snapshotSeq?: number; success: boolean }> => {- const { content, heterogeneousToolState, metadata, pluginState, pluginError } = params;+ const {+ content,+ heterogeneousToolState,+ metadata,+ pluginState,+ pluginError,+ replacePluginState,+ } = params;// `undefined` while no branch has looked for the row yet; see `update` above// for why a write that matches nothing must not report success.@@ -4638,6 +4686,20 @@ export class MessageModel {try {await this.db.transaction(async (trx) => {+ if (params.onlyIfEmpty) {+ const [message] = await trx+ .select({ content: messages.content })+ .from(messages)+ .where(and(eq(messages.id, id), this.ownership()))+ .for('update');+ matchedRow = !!message;+ if (!message) return;+ if (message.content) {+ applied = false;+ return;+ }+ }+let existingMetadata: Record<string, any> | undefined;if (metadata !== undefined || heterogeneousToolState !== undefined) {@@ -4716,9 +4778,10 @@ export class MessageModel {// Snapshot writes replace the whole runtime state. Ordinary patches// own complete top-level keys and merge inside the UPDATE so an// answer write cannot race away an intervention-terminal write.- pluginUpdateData.state = heterogeneousToolState- ? pluginState- : sql`coalesce(${messagePlugins.state}, '{}'::jsonb) || ${JSON.stringify(pluginState)}::jsonb`;+ pluginUpdateData.state =+ heterogeneousToolState || replacePluginState+ ? pluginState+ : sql`coalesce(${messagePlugins.state}, '{}'::jsonb) || ${JSON.stringify(pluginState)}::jsonb`;}if (pluginError !== undefined) {diff --git a/packages/env/src/__tests__/agentHook.test.ts b/packages/env/src/__tests__/agentHook.test.tsindex 458364018f8..7c0478a8922 100644--- a/packages/env/src/__tests__/agentHook.test.ts+++ b/packages/env/src/__tests__/agentHook.test.ts@@ -56,7 +56,15 @@ describe('server hook environment', () => {expect(String(error)).not.toContain('synthetic-env-secret');});- it('requires beforeToolCall for control', () => {+ it('accepts afterToolCall-only result controls', () => {+ enable();+ vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolResult');+ vi.stubEnv('AGENT_HOOK_WEBHOOK_ON_ERROR', 'block');+ expect(getAgentHookConfig().AGENT_HOOK_WEBHOOK_EVENTS).toEqual(['afterToolCall']);+ });++ it('keeps toolCall before-only for existing deployment configurations', () => {enable();vi.stubEnv('AGENT_HOOK_WEBHOOK_EVENTS', 'afterToolCall');vi.stubEnv('AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING', 'toolCall');diff --git a/packages/env/src/agentHook.ts b/packages/env/src/agentHook.tsindex c9597b1bb4d..cc357d8b730 100644--- a/packages/env/src/agentHook.ts+++ b/packages/env/src/agentHook.ts@@ -34,7 +34,9 @@ export const getAgentHookConfig = () => {z.array(agentHookTypeSchema).min(1).optional(),),AGENT_HOOK_WEBHOOK_ON_ERROR: z.enum(['continue', 'block']).default('continue'),- AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING: z.enum(['ignore', 'toolCall']).default('ignore'),+ AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING: z+ .enum(['ignore', 'toolCall', 'toolResult', 'toolCallAndResult'])+ .default('ignore'),AGENT_HOOK_WEBHOOK_TOKEN: z.string().refine((token) => token.trim().length > 0)@@ -51,17 +53,26 @@ export const getAgentHookConfig = () => {}if (env.AGENT_HOOK_WEBHOOK_ON_ERROR === 'block' &&- env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING !== 'toolCall'+ env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'ignore')throw new Error(- 'AGENT_HOOK_WEBHOOK_ON_ERROR=block requires AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING=toolCall',+ 'AGENT_HOOK_WEBHOOK_ON_ERROR=block requires toolCall, toolResult, or toolCallAndResult response handling',);+ const controlEvents =+ env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolCall'+ ? ['beforeToolCall']+ : env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolResult'+ ? ['afterToolCall']+ : env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolCallAndResult'+ ? ['beforeToolCall', 'afterToolCall']+ : [];if (- env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING === 'toolCall' &&- !env.AGENT_HOOK_WEBHOOK_EVENTS?.includes('beforeToolCall')- )+ controlEvents.length > 0 &&+ !env.AGENT_HOOK_WEBHOOK_EVENTS?.some((type) => controlEvents.includes(type))+ ) {throw new Error(- 'AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING=toolCall requires beforeToolCall in AGENT_HOOK_WEBHOOK_EVENTS',+ `AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING=${env.AGENT_HOOK_WEBHOOK_RESPONSE_HANDLING} requires ${controlEvents.join(' or ')} in AGENT_HOOK_WEBHOOK_EVENTS`,);+ }return env;};diff --git a/packages/types/src/agentHook.test.ts b/packages/types/src/agentHook.test.tsindex f0c897ab88c..ad176d322cd 100644--- a/packages/types/src/agentHook.test.ts+++ b/packages/types/src/agentHook.test.ts@@ -32,6 +32,10 @@ describe('serialized hook contract', () => {const persisted = JSON.stringify(hook);expect(serializedAgentHookSchema.parse(JSON.parse(persisted))).toEqual(hook);});+ it.each(['beforeToolCall', 'afterToolCall'])('accepts synchronous %s controls', (type) => {+ const hook = { ...control, type };+ expect(serializedAgentHookSchema.parse(hook)).toEqual(hook);+ });it('accepts every legacy hook and notification body/selection', () => {for (const type of agentHookTypeSchema.options) {expect(@@ -49,7 +53,7 @@ describe('serialized hook contract', () => {}});it.each([- { ...control, type: 'afterToolCall' },+ { ...control, type: 'onToolCallError' },{ ...control, type: 'unknown' },{ ...control, matcher: '[' },{ ...control, matcher: { identifier: '^fs$', apiName: '^read' } },diff --git a/packages/types/src/agentHook.ts b/packages/types/src/agentHook.tsindex ddd5a53b102..dcf081562df 100644--- a/packages/types/src/agentHook.ts+++ b/packages/types/src/agentHook.ts@@ -92,10 +92,13 @@ export const serializedAgentHookSchema = z) {ctx.addIssue({ code: 'custom', message: 'Matchers are only supported for tool events' });}- if (hook.webhook.responseHandling === 'toolCall' && hook.type !== 'beforeToolCall') {+ if (+ hook.webhook.responseHandling === 'toolCall' &&+ !['beforeToolCall', 'afterToolCall'].includes(hook.type)+ ) {ctx.addIssue({code: 'custom',- message: 'toolCall response handling requires beforeToolCall',+ message: 'toolCall response handling requires beforeToolCall or afterToolCall',});}});diff --git a/packages/utils/src/toolResultControl.test.ts b/packages/utils/src/toolResultControl.test.tsnew file mode 100644index 00000000000..790906432c9--- /dev/null+++ b/packages/utils/src/toolResultControl.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { pickToolResultUsage } from './toolResultControl';++describe('tool result usage projection', () => {+ it('keeps finite billing facts only', () => {+ expect(+ pickToolResultUsage({+ totalCost: 0.25,+ totalTokens: 42,+ totalToolCalls: 2,+ totalInputTokens: Infinity,+ totalOutputTokens: 'secret',+ images: ['secret'],+ text: 'secret',+ }),+ ).toEqual({ totalCost: 0.25, totalTokens: 42, totalToolCalls: 2 });+ });+ it.each([null, undefined, 'secret', []])('does not expose malformed state %j', (value) => {+ expect(pickToolResultUsage(value)).toEqual({});+ });+});diff --git a/packages/utils/src/toolResultControl.ts b/packages/utils/src/toolResultControl.tsnew file mode 100644index 00000000000..d6e2bb2b36f--- /dev/null+++ b/packages/utils/src/toolResultControl.ts@@ -0,0 +1,20 @@+import { isRecord } from './object';++export const BLOCKED_TOOL_RESULT_CONTENT = 'Tool result withheld by afterToolCall hook.';++/** Keep billing facts without carrying result text, images, errors, or resource references. */+export function pickToolResultUsage(state: unknown): Record<string, number> {+ const usage: Record<string, number> = {};+ if (!isRecord(state)) return usage;+ for (const key of [+ 'totalCost',+ 'totalInputTokens',+ 'totalOutputTokens',+ 'totalToolCalls',+ 'totalTokens',+ ]) {+ const value = state[key];+ if (typeof value === 'number' && Number.isFinite(value)) usage[key] = value;+ }+ return usage;+}