π€― 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(builtin-tool): add onBeforeCall / onAfterCall lifecycle hooks (#14719)
Arvin Xuda7e18281d4e
diff --git a/packages/builtin-tool-task/package.json b/packages/builtin-tool-task/package.jsonindex 078e5cdd4ea..fb48630299b 100644--- a/packages/builtin-tool-task/package.json+++ b/packages/builtin-tool-task/package.json@@ -4,7 +4,6 @@"private": true,"exports": {".": "./src/index.ts",- "./executor": "./src/executor/index.ts","./client": "./src/client/index.ts"},"main": "./src/index.ts",diff --git a/packages/builtin-tool-task/src/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.tssimilarity index 86%rename from packages/builtin-tool-task/src/executor/index.tsrename to packages/builtin-tool-task/src/client/executor/index.tsindex caea02d43ba..8c489740319 100644--- a/packages/builtin-tool-task/src/executor/index.ts+++ b/packages/builtin-tool-task/src/client/executor/index.ts@@ -13,15 +13,17 @@ import type {BuiltinToolResult,TaskAutomationMode,TaskStatus,+ ToolAfterCallContext,} from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';import debug from 'debug';import { taskService } from '@/services/task';import { getTaskStoreState } from '@/store/task';+import { findSubtaskParentId } from '@/store/task/slices/detail/reducer';-import { normalizeListTasksParams } from '../listTasks';-import { TaskIdentifier } from '../manifest';+import { normalizeListTasksParams } from '../../listTasks';+import { TaskIdentifier } from '../../manifest';import type {AddTaskCommentParams,CreateTaskParams,@@ -29,15 +31,91 @@ import type {DeleteTaskCommentParams,RunTasksItemResult,UpdateTaskCommentParams,-} from '../types';-import { TaskApiName } from '../types';+} from '../../types';+import { TaskApiName } from '../../types';const log = debug('lobe-task:executor');+// APIs whose execution mutates state that's surfaced in the renderer's task+// list or detail caches. Used by `onAfterCall` to decide what to revalidate.+const LIST_MUTATING_APIS = new Set<string>([+ TaskApiName.createTask,+ TaskApiName.createTasks,+ TaskApiName.deleteTask,+ TaskApiName.editTask,+ TaskApiName.runTask,+ TaskApiName.runTasks,+ TaskApiName.setTaskSchedule,+ TaskApiName.updateTaskStatus,+]);++const DETAIL_MUTATING_APIS = new Set<string>([+ TaskApiName.addTaskComment,+ TaskApiName.deleteTaskComment,+ TaskApiName.editTask,+ TaskApiName.runTask,+ TaskApiName.setTaskSchedule,+ TaskApiName.updateTaskComment,+ TaskApiName.updateTaskStatus,+ TaskApiName.viewTask,+]);++const extractIdentifier = (params: unknown, result: BuiltinToolResult): string | undefined => {+ const fromState = (result.state as { identifier?: unknown } | undefined)?.identifier;+ if (typeof fromState === 'string' && fromState.length > 0) return fromState;+ const fromParams = (params as { identifier?: unknown } | null | undefined)?.identifier;+ if (typeof fromParams === 'string' && fromParams.length > 0) return fromParams;+ return undefined;+};+class TaskExecutor extends BaseExecutor<typeof TaskApiName> {readonly identifier = TaskIdentifier;protected readonly apiEnum = TaskApiName;+ onAfterCall = async ({ apiName, params, result }: ToolAfterCallContext): Promise<void> => {+ if (!result.success) return;++ const store = getTaskStoreState();+ const identifier = extractIdentifier(params, result);++ // Build the set of task-detail keys to revalidate. Mirrors the pattern+ // used by `updateTask` in the detail slice so subtask deletions / edits+ // bubble up: when we mutate a subtask we must also refresh the parent+ // whose `subtasks[]` array embeds it, otherwise the parent's view keeps+ // showing the stale child until a manual reload.+ const detailTargets = new Set<string>();+ const touchesDetail = DETAIL_MUTATING_APIS.has(apiName) || LIST_MUTATING_APIS.has(apiName);+ if (touchesDetail) {+ if (identifier) {+ // `deleteTask` is not in DETAIL_MUTATING_APIS (the row is gone), but+ // edit/status/etc. need their own detail key revalidated.+ if (DETAIL_MUTATING_APIS.has(apiName)) detailTargets.add(identifier);++ const parentId = findSubtaskParentId(store.taskDetailMap, identifier);+ if (parentId) detailTargets.add(parentId);+ }++ // Defensive: refresh whatever detail page the user is currently+ // viewing β covers e.g. a `createTask` whose new identifier we don't+ // yet know in the local map but whose parent the user is staring at.+ const { activeTaskId } = store;+ if (activeTaskId) detailTargets.add(activeTaskId);+ }++ const refreshes: Promise<unknown>[] = [];+ if (LIST_MUTATING_APIS.has(apiName)) {+ refreshes.push(store.refreshTaskList());+ }+ for (const id of detailTargets) {+ refreshes.push(store.internal_refreshTaskDetail(id));+ }++ if (refreshes.length === 0) return;+ await Promise.all(refreshes).catch((error) => {+ log('[TaskExecutor] onAfterCall - refresh failed:', error);+ });+ };+addTaskComment = async (params: AddTaskCommentParams,ctx?: BuiltinToolContext,diff --git a/packages/builtin-tool-task/src/client/index.ts b/packages/builtin-tool-task/src/client/index.tsindex f3473a9d335..f3f684dbfd6 100644--- a/packages/builtin-tool-task/src/client/index.ts+++ b/packages/builtin-tool-task/src/client/index.ts@@ -18,6 +18,9 @@ export {// Render components (read-only snapshots)export { CreateTaskRender, CreateTasksRender, RunTasksRender, TaskRenders } from './Render';+// Client-side executor (browser runtime adapter for the agent)+export { taskExecutor } from './executor';+// Re-export manifest and types for convenienceexport { TaskIdentifier, TaskManifest } from '../manifest';export * from '../types';diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 10ccd9441d9..448f49fd654 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -715,6 +715,52 @@ export interface IBuiltinToolExecutor {* @returns The execution result*/invoke: (apiName: string, params: any, ctx: BuiltinToolContext) => Promise<BuiltinToolResult>;++ /**+ * Optional renderer-side hook fired AFTER a tool call completes β regardless+ * of whether it actually executed in the client (this executor) or server-side+ * (server runtime). Use to invalidate SWR caches, refresh stores, or trigger+ * any other UI-side reaction to the mutation. Implementations should narrow+ * `ctx.params` themselves based on `ctx.apiName`.+ */+ onAfterCall?: (ctx: ToolAfterCallContext) => void | Promise<void>;++ /**+ * Optional renderer-side hook fired BEFORE a tool call dispatches, regardless+ * of whether the tool will execute client- or server-side. Use to optimistically+ * update UI, set loading states, etc.+ */+ onBeforeCall?: (ctx: ToolBeforeCallContext) => void | Promise<void>;+}++/**+ * Shared base for all renderer-side tool lifecycle hooks. New fields go here+ * (or on the variants below) β keeping the call signature as a single object+ * so additions stay non-breaking.+ */+export interface ToolHookContext {+ /** API name being invoked (e.g. `'deleteTask'`). */+ apiName: string;+ /** Tool identifier (e.g. `'lobe-task'`). */+ identifier: string;+ /**+ * Parsed tool arguments. Arrives JSON-decoded when the event comes off the+ * agent stream; never the raw string. Hook implementations narrow per+ * `apiName`.+ */+ params: unknown;+ /**+ * Stable id for this specific tool invocation (`ChatToolPayload.id`).+ * Useful for correlating before/after hooks against the same call.+ */+ toolCallId?: string;+}++export interface ToolBeforeCallContext extends ToolHookContext {}++export interface ToolAfterCallContext extends ToolHookContext {+ /** Execution result returned by either the client executor or server runtime. */+ result: BuiltinToolResult;}/**diff --git a/src/features/AgentTasks/AgentTaskList/EmptyState.tsx b/src/features/AgentTasks/AgentTaskList/EmptyState.tsxindex 12bbe6994d6..4095e4fc91d 100644--- a/src/features/AgentTasks/AgentTaskList/EmptyState.tsx+++ b/src/features/AgentTasks/AgentTaskList/EmptyState.tsx@@ -13,7 +13,7 @@ import WideScreenContainer from '@/features/WideScreenContainer';import CreateTaskInlineEntry from './CreateTaskInlineEntry';-const HERO_MAX_WIDTH = 720;+const HERO_MAX_WIDTH = 960;const EMPTY_STATE_RECOMMEND_COUNT = 10;const styles = createStaticStyles(({ css }) => ({diff --git a/src/server/services/toolExecution/serverRuntimes/task.ts b/src/server/services/toolExecution/serverRuntimes/task.tsindex cca26fb6cfd..d0fdc989dcc 100644--- a/src/server/services/toolExecution/serverRuntimes/task.ts+++ b/src/server/services/toolExecution/serverRuntimes/task.ts@@ -9,7 +9,7 @@ import {formatTaskList,priorityLabel,} from '@lobechat/prompts';-import type { TaskStatus } from '@lobechat/types';+import type { TaskAutomationMode, TaskStatus } from '@lobechat/types';import { AgentModel } from '@/database/models/agent';import { TaskModel } from '@/database/models/task';@@ -332,6 +332,86 @@ export const createTaskRuntime = ({}},+ setTaskSchedule: async (args: {+ automationMode?: TaskAutomationMode | null;+ heartbeatInterval?: number;+ identifier: string;+ maxExecutions?: number | null;+ schedulePattern?: string | null;+ scheduleTimezone?: string | null;+ }) => {+ const task = await taskModel.resolve(args.identifier);+ if (!task) return { content: `Task not found: ${args.identifier}`, success: false };++ const changes: string[] = [];+ const ops: Promise<unknown>[] = [];++ // Mirrors client executor: schedule columns go through taskCaller.update;+ // maxExecutions lives in `tasks.config.schedule.maxExecutions` (JSONB) and+ // routes through updateConfig so server-side merge preserves siblings.+ const scheduleUpdate: {+ automationMode?: TaskAutomationMode | null;+ heartbeatInterval?: number;+ schedulePattern?: string | null;+ scheduleTimezone?: string | null;+ } = {};+ if (args.automationMode !== undefined) {+ scheduleUpdate.automationMode = args.automationMode;+ changes.push(+ args.automationMode ? `automation mode β ${args.automationMode}` : 'automation disabled',+ );+ }+ if (args.heartbeatInterval !== undefined) {+ scheduleUpdate.heartbeatInterval = args.heartbeatInterval;+ changes.push(+ args.heartbeatInterval > 0+ ? `heartbeat interval β ${args.heartbeatInterval}s`+ : 'heartbeat interval cleared',+ );+ }+ if (args.schedulePattern !== undefined) {+ scheduleUpdate.schedulePattern = args.schedulePattern;+ changes.push(+ args.schedulePattern+ ? `schedule pattern β "${args.schedulePattern}"`+ : 'schedule pattern cleared',+ );+ }+ if (args.scheduleTimezone !== undefined) {+ scheduleUpdate.scheduleTimezone = args.scheduleTimezone;+ changes.push(+ args.scheduleTimezone+ ? `schedule timezone β ${args.scheduleTimezone}`+ : 'schedule timezone cleared',+ );+ }+ if (Object.keys(scheduleUpdate).length > 0) {+ ops.push(taskCaller.update({ id: task.id, ...scheduleUpdate }));+ }++ if (args.maxExecutions !== undefined) {+ ops.push(+ taskCaller.updateConfig({+ config: { schedule: { maxExecutions: args.maxExecutions } },+ id: task.id,+ }),+ );+ changes.push(+ args.maxExecutions === null+ ? 'max executions cleared (unlimited)'+ : `max executions β ${args.maxExecutions}`,+ );+ }++ if (ops.length === 0) {+ return { content: 'No schedule fields provided; nothing to update.', success: false };+ }++ await Promise.all(ops);++ return { content: formatTaskEdited(task.identifier, changes), success: true };+ },+runTask: async (args: { continueTopicId?: string; identifier?: string; prompt?: string }) => {const id = args.identifier?.trim() || taskId;if (!id) {diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.tsindex 15535c9ed25..5203b6a855d 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts@@ -20,6 +20,11 @@ vi.mock('@/store/chat/slices/aiChat/actions/agentSignalBridge', () => ({emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),}));+const getExecutorMock = vi.fn();+vi.mock('@/store/tool/slices/builtin/executors', () => ({+ getExecutor: (...args: unknown[]) => getExecutorMock(...args),+}));+// βββ Test Helpers βββfunction createMockStore() {@@ -351,6 +356,109 @@ describe('createGatewayEventHandler', () => {expect(store.replaceMessages).toHaveBeenCalled();});++ it('should dispatch onAfterCall when payload is wrapped as { parentMessageId, toolCalling } (real gateway shape)', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const onAfterCall = vi.fn().mockResolvedValue(undefined);+ getExecutorMock.mockReturnValueOnce({ onAfterCall });++ handler(+ makeEvent('tool_end', {+ isSuccess: true,+ payload: {+ parentMessageId: 'msg-parent',+ toolCalling: {+ apiName: 'deleteTask',+ arguments: JSON.stringify({ identifier: 'T-3' }),+ id: 'tc-1',+ identifier: 'lobe-task',+ },+ },+ result: { content: 'Task deleted', success: true },+ }),+ );+ await flush();++ expect(getExecutorMock).toHaveBeenCalledWith('lobe-task');+ expect(onAfterCall).toHaveBeenCalledWith({+ apiName: 'deleteTask',+ identifier: 'lobe-task',+ params: { identifier: 'T-3' },+ result: { content: 'Task deleted', success: true },+ toolCallId: 'tc-1',+ });+ });++ it('should also dispatch onAfterCall when payload is the flat ChatToolPayload', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const onAfterCall = vi.fn().mockResolvedValue(undefined);+ getExecutorMock.mockReturnValueOnce({ onAfterCall });++ handler(+ makeEvent('tool_end', {+ isSuccess: true,+ payload: {+ apiName: 'createTask',+ arguments: JSON.stringify({ name: 'New', instruction: 'do thing' }),+ id: 'tc-2',+ identifier: 'lobe-task',+ },+ result: { success: true },+ }),+ );+ await flush();++ expect(onAfterCall).toHaveBeenCalledWith(+ expect.objectContaining({+ apiName: 'createTask',+ identifier: 'lobe-task',+ toolCallId: 'tc-2',+ }),+ );+ });++ it('should skip onAfterCall when payload identifier/apiName are missing', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const onAfterCall = vi.fn();+ getExecutorMock.mockReturnValue({ onAfterCall });++ handler(makeEvent('tool_end', { isSuccess: true, payload: { parentMessageId: 'x' } }));+ await flush();++ expect(onAfterCall).not.toHaveBeenCalled();+ });+ });++ describe('tool_start', () => {+ it('should dispatch onBeforeCall with the unwrapped ChatToolPayload', async () => {+ const store = createMockStore();+ const handler = createHandler(store);+ const onBeforeCall = vi.fn().mockResolvedValue(undefined);+ getExecutorMock.mockReturnValueOnce({ onBeforeCall });++ handler(+ makeEvent('tool_start', {+ parentMessageId: 'msg-parent',+ toolCalling: {+ apiName: 'editTask',+ arguments: JSON.stringify({ identifier: 'T-5', name: 'renamed' }),+ id: 'tc-3',+ identifier: 'lobe-task',+ },+ }),+ );+ await flush();++ expect(onBeforeCall).toHaveBeenCalledWith({+ apiName: 'editTask',+ identifier: 'lobe-task',+ params: { identifier: 'T-5', name: 'renamed' },+ toolCallId: 'tc-3',+ });+ });});describe('step_complete', () => {diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.tsindex 20e50de646b..5a8bc7d5e12 100644--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts@@ -3,9 +3,11 @@ import type {StepCompleteData,StreamChunkData,StreamStartData,+ ToolEndData,ToolExecuteData,+ ToolStartData,} from '@lobechat/agent-gateway-client';-import type { ChatMessageError, ConversationContext } from '@lobechat/types';+import type { BuiltinToolResult, ChatMessageError, ConversationContext } from '@lobechat/types';import { AgentRuntimeErrorType } from '@lobechat/types';import { messageService } from '@/services/message';@@ -13,6 +15,16 @@ import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actimport type { ChatStore } from '@/store/chat/store';import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';+// Lazy-loaded to break the import cycle:+// gateway.ts β gatewayEventHandler.ts β executors/index.ts (which pulls in+// tool client barrels that import `@/store/chat/store`) β chat store+// creation β `new GatewayActionImpl(...)` while gateway.ts is still+// mid-evaluation, so the class binding is undefined.+const loadGetExecutor = async () => {+ const mod = await import('@/store/tool/slices/builtin/executors');+ return mod.getExecutor;+};+/*** Fetch messages from DB and replace them in the chat store's dbMessagesMap.* This updates the ConversationArea component via React subscription:@@ -24,6 +36,100 @@ const fetchAndReplaceMessages = async (get: () => ChatStore, context: Conversatireturn messages;};+interface ChatToolPayloadLike {+ apiName?: unknown;+ arguments?: unknown;+ id?: unknown;+ identifier?: unknown;+}++interface ToolPayloadIdentity {+ apiName: string;+ identifier: string;+ params: unknown;+ toolCallId?: string;+}++/**+ * Extract `{ identifier, apiName, params, toolCallId }` from a stream event's+ * tool payload. Returns `undefined` when the payload is malformed so the+ * caller can skip dispatch without throwing.+ */+const readToolPayload = (+ payload: ChatToolPayloadLike | undefined,+): ToolPayloadIdentity | undefined => {+ const identifier = typeof payload?.identifier === 'string' ? payload.identifier : undefined;+ const apiName = typeof payload?.apiName === 'string' ? payload.apiName : undefined;+ if (!identifier || !apiName) return undefined;++ let params: unknown = payload?.arguments;+ if (typeof params === 'string') {+ try {+ params = JSON.parse(params);+ } catch {+ params = {};+ }+ } else if (params == null) {+ params = {};+ }++ const toolCallId = typeof payload?.id === 'string' ? payload.id : undefined;+ return { apiName, identifier, params, toolCallId };+};++/**+ * Route a `tool_start` event to the executor's optional `onBeforeCall` hook so+ * tool packages can react before their own mutations dispatch (e.g.+ * optimistic UI). Fires for both client- and server-runtime tools.+ */+const dispatchOnBeforeCall = async (data: ToolStartData | undefined): Promise<void> => {+ const payload = data?.toolCalling as ChatToolPayloadLike | undefined;+ const identity = readToolPayload(payload);+ if (!identity) return;++ const getExecutor = await loadGetExecutor();+ const executor = getExecutor(identity.identifier);+ if (!executor?.onBeforeCall) return;++ await executor.onBeforeCall(identity);+};++/**+ * Real gateway `tool_end` events ship `data.payload` as the+ * `{ parentMessageId, toolCalling }` wrapper, NOT a flat `ChatToolPayload`+ * (see `src/server/modules/AgentRuntime/RuntimeExecutors.ts` β both the+ * single-tool and batch publish sites). Unwrap defensively, falling back to+ * the flat shape so we tolerate test fixtures / future emission paths that+ * pass the payload directly.+ */+const unwrapToolPayload = (raw: unknown): ChatToolPayloadLike | undefined => {+ if (!raw || typeof raw !== 'object') return undefined;+ const wrapper = raw as { toolCalling?: unknown };+ if (wrapper.toolCalling && typeof wrapper.toolCalling === 'object') {+ return wrapper.toolCalling as ChatToolPayloadLike;+ }+ return raw as ChatToolPayloadLike;+};++/**+ * Route a `tool_end` event to the executor's optional `onAfterCall` hook so+ * tool packages can react to their own mutations (e.g. invalidate store+ * caches) regardless of whether the tool ran client- or server-side.+ */+const dispatchOnAfterCall = async (data: ToolEndData | undefined): Promise<void> => {+ const identity = readToolPayload(unwrapToolPayload(data?.payload));+ if (!identity) return;++ const getExecutor = await loadGetExecutor();+ const executor = getExecutor(identity.identifier);+ if (!executor?.onAfterCall) return;++ await executor.onAfterCall({+ ...identity,+ result: (data?.result ?? {}) as BuiltinToolResult,+ });+};+type GatewayMessageLike = { id: string; role?: string };type HeteroStreamStartData = StreamStartData & { newStep?: boolean };@@ -249,6 +355,10 @@ export const createGatewayEventHandler = (case 'tool_start': {// Server creates tool messages in DB.// Loading is already active from stream_start (not cleared by stream_end).+ const data = event.data as ToolStartData | undefined;+ enqueue(async () => {+ await dispatchOnBeforeCall(data).catch(console.error);+ });break;}@@ -286,8 +396,12 @@ export const createGatewayEventHandler = (}case 'tool_end': {+ const data = event.data as ToolEndData | undefined;enqueue(async () => {- await fetchAndReplaceMessages(get, context).catch(console.error);+ await Promise.all([+ fetchAndReplaceMessages(get, context).catch(console.error),+ dispatchOnAfterCall(data).catch(console.error),+ ]);});break;}diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.tsindex c5fc8504e10..da9ef8e29a9 100644--- a/src/store/tool/slices/builtin/executors/index.ts+++ b/src/store/tool/slices/builtin/executors/index.ts@@ -15,7 +15,7 @@ import { knowledgeBaseExecutor } from '@lobechat/builtin-tool-knowledge-base/cliimport { lobeAgentExecutor } from '@lobechat/builtin-tool-lobe-agent/client';import { localSystemExecutor } from '@lobechat/builtin-tool-local-system/executor';import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';-import { taskExecutor } from '@lobechat/builtin-tool-task/executor';+import { taskExecutor } from '@lobechat/builtin-tool-task/client';import type { BuiltinToolContext, BuiltinToolResult, IBuiltinToolExecutor } from '../types';import { activatorExecutor } from './lobe-activator';