π€― 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): unify heterogeneous agent terminal hooks (#16193)
Arvin Xue93e659ed260
diff --git a/apps/cli/src/tools/heteroTask.ts b/apps/cli/src/tools/heteroTask.tsindex f1f3578ed97..5fe66fb732f 100644--- a/apps/cli/src/tools/heteroTask.ts+++ b/apps/cli/src/tools/heteroTask.ts@@ -92,16 +92,19 @@ async function sendAutoNotify(}/**- * Signal remote hetero task completion to the server so it can publish- * `agent_runtime_end` to the gateway WS and close the frontend subscription.- * Called on clean process exit (code=0, no signal) β error exits go through- * `sendAutoNotify` which writes an error message AND triggers completion via- * the `done` flag.+ * Signal remote hetero task termination to the server so it can publish+ * `agent_runtime_end`, close the frontend subscription, and fire the run's+ * lifecycle hooks (task lifecycle + IM bot callback).+ *+ * Pass `error` to finalize the run as FAILED (non-zero process exit) β the+ * server marks the owning task failed and renders the error. Omit it for a+ * clean completion (the agent already sent its final message via `lh notify`).*/-async function sendDoneSignal(+async function sendTerminalSignal(topicId: string,agentId?: string,workspaceId?: string,+ error?: { message: string; type?: string },): Promise<void> {try {const client = await getTrpcClient(workspaceId);@@ -109,11 +112,12 @@ async function sendDoneSignal(agentId,content: '',done: true,+ ...(error ? { error } : {}),role: 'assistant',topicId,});} catch (err) {- log.error('Failed to send done signal:', err instanceof Error ? err.message : String(err));+ log.error('Failed to send terminal signal:', err instanceof Error ? err.message : String(err));}}@@ -224,23 +228,32 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<stringlog.info(`OpenClaw task started: taskId=${taskId} pid=${pid} agent=${openclawAgent}`);// On exit: notify the server so it can close the frontend gateway WS subscription.- // - Abnormal exit (signal or non-zero code): write an error message bubble.+ // - Failed exit (non-zero code, no signal): write an error bubble AND finalize+ // the run as failed so the owning task is marked failed.+ // - Cancelled (killed by signal, e.g. interruptTask): write a notice + a plain+ // terminal signal β cancellation is not a failure.// - Clean exit (code=0, no signal): openclaw already sent its final message via- // `lh notify`; just send a done signal to publish `agent_runtime_end`.+ // `lh notify`; just send a terminal signal to publish `agent_runtime_end`.child.on('close', (code, signal) => {removeTask(taskId);if (code !== 0 || signal !== null) {- const text = signal+ const cancelled = signal !== null;+ const text = cancelled? `Task cancelled (signal: ${signal})`: `Task failed (exit code: ${code})`;- // Send error message first, THEN signal done (sequential).- // Fire-and-forget both, but ensure done is always sent even if notify fails.+ // Write the notice bubble first, THEN signal terminal (sequential).+ // Fire-and-forget both, but ensure the terminal signal is always sent.void sendAutoNotify(topicId, taskId, text, agentId, workspaceId).finally(() =>- sendDoneSignal(topicId, agentId, workspaceId),+ sendTerminalSignal(+ topicId,+ agentId,+ workspaceId,+ cancelled ? undefined : { message: text, type: 'HeteroProcessError' },+ ),);} else {// Clean exit β openclaw already sent its final message; just signal done.- void sendDoneSignal(topicId, agentId, workspaceId);+ void sendTerminalSignal(topicId, agentId, workspaceId);}});@@ -301,11 +314,17 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<stringremoveTask(taskId);if (code !== 0 || signal !== null) {- const text = signal+ const cancelled = signal !== null;+ const text = cancelled? `Task cancelled (signal: ${signal})`: `Task failed (exit code: ${code})`;void sendAutoNotify(topicId, taskId, text, agentId, workspaceId).finally(() =>- sendDoneSignal(topicId, agentId, workspaceId),+ sendTerminalSignal(+ topicId,+ agentId,+ workspaceId,+ cancelled ? undefined : { message: text, type: 'HeteroProcessError' },+ ),);return;}@@ -319,10 +338,10 @@ export async function runHeteroTask(params: RunHeteroTaskParams): Promise<stringif (response) {void sendAutoNotify(topicId, taskId, response, agentId, workspaceId).finally(() =>- sendDoneSignal(topicId, agentId, workspaceId),+ sendTerminalSignal(topicId, agentId, workspaceId),);} else {- void sendDoneSignal(topicId, agentId, workspaceId);+ void sendTerminalSignal(topicId, agentId, workspaceId);}});diff --git a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts b/apps/server/src/routers/lambda/__tests__/agentNotify.test.tsnew file mode 100644index 00000000000..aa46956cb86--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts@@ -0,0 +1,148 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '@/server/services/agentRuntime/hooks';+import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';++// serverDatabase middleware calls getServerDB(); stub it (our model mocks+// ignore the db handle anyway).+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => ({})),+}));++// RBAC middleware β pass-through.+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(() => (opts: any) => opts.next({ ctx: opts.ctx })),+}));++const mockTopicFindById = vi.fn();+const mockTopicUpdateMetadata = vi.fn();+const mockMessageFindById = vi.fn();+const mockMessageUpdate = vi.fn();+const mockMessageCreate = vi.fn();+const mockExecAgent = vi.fn();++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn(() => ({+ findById: mockTopicFindById,+ updateMetadata: mockTopicUpdateMetadata,+ })),+}));+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn(() => ({+ create: mockMessageCreate,+ findById: mockMessageFindById,+ update: mockMessageUpdate,+ })),+}));+vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn(() => ({ execAgent: mockExecAgent })),+}));++const mockPublishAgentRuntimeEnd = vi.fn();+const mockPublishStreamEvent = vi.fn();+vi.mock('@/server/modules/AgentRuntime/factory', async (orig) => ({+ ...(await (orig as () => Promise<Record<string, unknown>>)()),+ createStreamEventManager: vi.fn(() => ({+ publishAgentRuntimeEnd: mockPublishAgentRuntimeEnd,+ publishStreamEvent: mockPublishStreamEvent,+ })),+}));++// Imported after the mocks above are registered.+const { agentNotifyRouter } = await import('../agentNotify');++const OP = 'op-remote-1';+const TOPIC = 'topic-remote-1';+const FINAL_MSG_ID = 'msg-final';++const createCaller = () =>+ agentNotifyRouter.createCaller({ serverDB: {}, userId: 'user-1' } as any);++/** Register spy handlers on the real dispatcher (local mode β in-memory). */+const registerHooks = () => {+ const onComplete = vi.fn(async (_event: any) => {});+ const onError = vi.fn(async (_event: any) => {});+ const hooks: AgentHook[] = [+ { handler: onComplete, id: 'task-on-complete', type: 'onComplete' },+ { handler: onError, id: 'task-on-error', type: 'onError' },+ ];+ hookDispatcher.register(OP, hooks);+ return { onComplete, onError };+};++describe('agentNotifyRouter.notify β remote hetero terminal signal', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // Topic carries the seeded running operation (id + final-reply placeholder).+ mockTopicFindById.mockResolvedValue({+ agentId: 'agent-1',+ metadata: {+ runningOperation: {+ assistantMessageId: FINAL_MSG_ID,+ hooks: [{ id: 'task-on-complete', type: 'onComplete', webhook: { url: '/wh' } }],+ operationId: OP,+ },+ },+ });+ // The placeholder message holds the agent's final reply (written in-place+ // by earlier `lh notify` calls).+ mockMessageFindById.mockResolvedValue({ content: 'the final reply', topicId: TOPIC });+ mockTopicUpdateMetadata.mockResolvedValue(undefined);+ });++ afterEach(() => {+ hookDispatcher.unregister(OP);+ });++ it('empty done signal finalizes success AND carries the final reply into the hooks', async () => {+ const { onComplete, onError } = registerHooks();++ await createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC });++ // Stream closed as success.+ expect(mockPublishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: OP, reason: 'success' }),+ );++ // onComplete fired (fire-and-forget) with the reloaded final reply β the+ // regression guard: an empty done signal must still pass the placeholder id+ // so lastAssistantContent isn't undefined (else bot reply + handoff/review/+ // brief get skipped).+ await vi.waitFor(() => expect(onComplete).toHaveBeenCalledTimes(1));+ expect(onComplete.mock.calls[0][0]).toMatchObject({+ lastAssistantContent: 'the final reply',+ operationId: OP,+ reason: 'done',+ });+ expect(onError).not.toHaveBeenCalled();++ // Running marker dropped so a duplicate done can't re-fire.+ await vi.waitFor(() =>+ expect(mockTopicUpdateMetadata).toHaveBeenCalledWith(TOPIC, { runningOperation: null }),+ );+ });++ it('error signal finalizes the run as failed and fires onError', async () => {+ const { onComplete, onError } = registerHooks();++ await createCaller().notify({+ content: '',+ error: { message: 'remote crashed', type: 'HeteroProcessError' },+ role: 'assistant',+ topicId: TOPIC,+ });++ expect(mockPublishAgentRuntimeEnd).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: OP, reason: 'error' }),+ );++ await vi.waitFor(() => expect(onError).toHaveBeenCalledTimes(1));+ expect(onError.mock.calls[0][0]).toMatchObject({+ errorMessage: 'remote crashed',+ errorType: 'HeteroProcessError',+ reason: 'error',+ });+ expect(onComplete).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/routers/lambda/agentNotify.ts b/apps/server/src/routers/lambda/agentNotify.tsindex 7e8cec23bdd..823cde68b5f 100644--- a/apps/server/src/routers/lambda/agentNotify.ts+++ b/apps/server/src/routers/lambda/agentNotify.ts@@ -10,6 +10,8 @@ import { TopicModel } from '@/database/models/topic';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';+import { dispatchTerminalHooks } from '@/server/services/agentRuntime/hooks';+import type { SerializedHook } from '@/server/services/agentRuntime/hooks/types';import { AiAgentService } from '@/server/services/aiAgent';// Module-level singleton so we don't create a new Redis connection per request.@@ -52,6 +54,16 @@ const NotifySchema = z.object({* Can be combined with content (final message + done) or sent alone (just done).*/done: z.boolean().optional(),+ /**+ * Terminal error for a remote hetero run (openclaw / hermes). The notify+ * channel otherwise only carries success, so a remote agent that crashes /+ * fails has no way to fail its run. When present the run is finalized as+ * FAILED instead of succeeded β `agent_runtime_end` carries `reason='error'`+ * and the onError/onComplete hooks fire with this message, so the owning task+ * is marked failed and any IM bot callback renders the error. Implies a+ * terminal signal (treated like `done: true`).+ */+ error: z.object({ message: z.string(), type: z.string().optional() }).optional(),/*** When role is 'assistant': update an existing message instead of creating a* new one. The caller is responsible for passing the messageId returned by the@@ -89,9 +101,14 @@ export const agentNotifyRouter = router({role = 'user',continue: shouldContinue = false,done = false,+ error: terminalError,messageId,} = input;+ // An error is itself a terminal signal β finalize the run even if the+ // remote agent didn't also set `done`.+ const isTerminal = done || !!terminalError;+log('notify: topicId=%s, agentId=%s, role=%s, continue=%s, done=%s, messageId=%s, content=%s',topicId,@@ -134,15 +151,49 @@ export const agentNotifyRouter = router({if (!remoteOperationId) return;try {const stream = getStreamManager();- if (done) {+ if (isTerminal) {// Signal task completion β frontend gateway WS subscription closes.+ // A `terminalError` finalizes the run as failed; otherwise it succeeded.await stream.publishAgentRuntimeEnd({- finalState: { reason: 'success' },+ finalState: terminalError+ ? { error: terminalError.message, reason: 'error' }+ : { reason: 'success' },operationId: remoteOperationId,- reason: 'success',- reasonDetail: 'Remote hetero agent task completed',+ reason: terminalError ? 'error' : 'success',+ reasonDetail: terminalError?.message ?? 'Remote hetero agent task completed',stepIndex: 0,});++ // Remote hetero (openclaw / hermes) has no `heteroFinish` callback, so+ // this is its terminal funnel. Fire the run's onComplete (+ onError on+ // failure) hooks through the shared dispatcher β the same mechanism the+ // CLI / normal LLM paths use β so the task lifecycle (onTopicComplete β+ // task done/failed) and any IM bot completion callback run. Hooks were+ // serialized onto runningOperation at dispatch time.+ const serializedHooks = (topic.metadata as any)?.runningOperation?.hooks as+ | SerializedHook[]+ | undefined;+ let lastAssistantContent: string | undefined = content || undefined;+ if (!lastAssistantContent && writtenMessageId) {+ const msg = await ctx.messageModel.findById(writtenMessageId).catch(() => undefined);+ lastAssistantContent = (msg?.content as string | undefined) ?? undefined;+ }+ await dispatchTerminalHooks({+ agentId,+ ...(terminalError+ ? { errorMessage: terminalError.message, errorType: terminalError.type }+ : {}),+ lastAssistantContent,+ operationId: remoteOperationId,+ reason: terminalError ? 'error' : 'done',+ serializedHooks,+ topicId,+ userId: ctx.userId,+ });++ // The operation is finished β drop the running marker so a duplicate+ // terminal signal / reconnect doesn't re-fire the hooks.+ await ctx.topicModel.updateMetadata(topicId, { runningOperation: null }).catch(() => {});} else {// Lightweight invalidation β frontend calls fetchAndReplaceMessages.await stream.publishStreamEvent(remoteOperationId, {@@ -184,9 +235,14 @@ export const agentNotifyRouter = router({});}- // done=true with empty content + existing placeholder β just signal completion, no update.- if (done && !content) {- void publishRemoteHeteroEvent();+ // Terminal signal (done or error) with empty content + existing+ // placeholder β just finalize the run, no message update. Pass the+ // resolved id so the finalizer can reload the agent's final reply+ // (written in-place via earlier `lh notify` calls) into+ // `lastAssistantContent` β bot completion callbacks and the task+ // lifecycle follow-ups (handoff / auto-review / brief) depend on it.+ if (isTerminal && !content) {+ void publishRemoteHeteroEvent(resolvedMessageId);return { messageId: resolvedMessageId, operationId: undefined, topicId };}await ctx.messageModel.update(resolvedMessageId, { content });@@ -205,8 +261,9 @@ export const agentNotifyRouter = router({return { messageId: resolvedMessageId, operationId: undefined, topicId };}- // done=true with no messageId and empty content β just signal completion, no DB write.- if (done && !content) {+ // Terminal signal (done or error) with no messageId and empty content β+ // just finalize the run, no DB write.+ if (isTerminal && !content) {void publishRemoteHeteroEvent();return { messageId: undefined, operationId: undefined, topicId };}diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex a99cfb3cbf5..89157426b3e 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -16,10 +16,9 @@ import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { MessageModel } from '@/database/models/message';-import { TaskModel } from '@/database/models/task';import { ThreadModel } from '@/database/models/thread';import { TopicModel } from '@/database/models/topic';-import { taskTopics, topics } from '@/database/schemas';+import { topics } from '@/database/schemas';import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentRuntimeService } from '@/server/services/agentRuntime';@@ -27,7 +26,6 @@ import { AiAgentService } from '@/server/services/aiAgent';import { AiChatService } from '@/server/services/aiChat';import { getFileProxyUrl } from '@/server/services/file';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';-import { TaskLifecycleService } from '@/server/services/taskLifecycle';const log = debug('lobe-server:ai-agent-router');@@ -1258,6 +1256,11 @@ export const aiAgentRouter = router({workspaceId: wsId,});+ // heteroFinish now owns the full terminal transition: it fires the run's+ // onComplete/onError hooks through the shared hookDispatcher, which drives+ // the task lifecycle (onTopicComplete) and any IM bot completion callback β+ // the same mechanism the normal LLM runtime uses. No bespoke lifecycle call+ // here anymore; this is just the server-to-server ack endpoint.await heteroService.heteroFinish({agentType,error,@@ -1267,51 +1270,6 @@ export const aiAgentRouter = router({topicId,});- // Trigger task lifecycle transition β mirrors the onComplete hook that the- // normal LLM execAgent path dispatches after AgentRuntimeService finishes.- // The hetero path spawns the sandbox fire-and-forget and returns early, so- // the hook is never registered or dispatched; we must call onTopicComplete- // explicitly here when the CLI signals process exit.- //- // Guard: heteroFinish can be called more than once for the same operation- // (signal path sends cancelled, normal exit sends the real result, and- // transient transport failures can replay). onTopicComplete is NOT- // idempotent (reason='error' creates briefs), so skip the call when the- // topic is already in a terminal state.- const TERMINAL_TOPIC_STATUSES = new Set(['canceled', 'completed', 'failed', 'timeout']);- try {- // System-level lookup: heteroFinish is a server-to-server callback from- // the CLI and doesn't carry a workspace context. Resolve the task topic- // (and downstream models) using the row's own `workspaceId`.- const [taskTopicRow] = await ctx.serverDB- .select()- .from(taskTopics)- .where(and(eq(taskTopics.topicId, topicId), eq(taskTopics.userId, ctx.userId)))- .limit(1);- if (taskTopicRow && !TERMINAL_TOPIC_STATUSES.has(taskTopicRow.status)) {- const wsId = taskTopicRow.workspaceId ?? undefined;- const taskModel = new TaskModel(ctx.serverDB, ctx.userId, wsId);- const task = await taskModel.findById(taskTopicRow.taskId);- if (task) {- const reason =- result === 'success' ? 'done' : result === 'cancelled' ? 'interrupted' : 'error';- const taskLifecycle = new TaskLifecycleService(ctx.serverDB, ctx.userId, wsId);- await taskLifecycle.onTopicComplete({- errorMessage: error?.message,- operationId,- reason,- taskId: task.id,- taskIdentifier: task.identifier,- topicId,- });- }- }- } catch (lifecycleErr: any) {- // Non-fatal: log but do not fail the heteroFinish ack. The CLI has- // already finished; failing here would cause it to retry unnecessarily.- log('heteroFinish: task lifecycle update failed (non-fatal): %s', lifecycleErr?.message);- }-return { ack: true as const };} catch (err: any) {log('heteroFinish failed: %s', err?.message);diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex feddb4c7f66..354ab1930a6 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -3,6 +3,7 @@ import {type RecentTopic,type RecentTopicGroup,type RecentTopicGroupMember,+ serializedAgentHookSchema,} from '@lobechat/types';import { cleanObject } from '@lobechat/utils';import { inArray } from 'drizzle-orm';@@ -683,13 +684,7 @@ export const topicRouter = router({runningOperation: z.object({assistantMessageId: z.string(),- completionWebhook: z- .object({- body: z.record(z.unknown()).optional(),- delivery: z.enum(['fetch', 'qstash']).optional(),- url: z.string(),- })- .optional(),+ hooks: z.array(serializedAgentHookSchema).optional(),operationId: z.string(),scope: z.string().optional(),threadId: z.string().nullish(),diff --git a/apps/server/src/services/agentRuntime/hooks/dispatchTerminalHooks.ts b/apps/server/src/services/agentRuntime/hooks/dispatchTerminalHooks.tsnew file mode 100644index 00000000000..2a2f7d8c632--- /dev/null+++ b/apps/server/src/services/agentRuntime/hooks/dispatchTerminalHooks.ts@@ -0,0 +1,80 @@+import type { AgentHookEvent } from '@lobechat/agent-runtime';+import debug from 'debug';++import { hookDispatcher } from './HookDispatcher';+import type { SerializedHook } from './types';++const log = debug('lobe-server:hook-dispatcher');++export interface TerminalHookParams {+ /** Owning agent id, when known. Optional β the task/bot handlers don't require it. */+ agentId?: string;+ /** Human-readable error message (error path only). */+ errorMessage?: string;+ /** Stable error taxonomy type (error path only), e.g. 'ServerAgentRuntimeError'. */+ errorType?: string;+ /** Final assistant text, for bot-callback rendering / task handoff. */+ lastAssistantContent?: string;+ operationId: string;+ reason: 'done' | 'error' | 'interrupted';+ /**+ * Serialized webhook hooks for queue mode (read from+ * `topic.metadata.runningOperation.hooks` or `getSerializedHooks`). Ignored in+ * local mode, where `dispatch` calls the in-memory handlers instead.+ */+ serializedHooks?: SerializedHook[];+ topicId?: string;+ userId: string;+}++/**+ * Fire `onComplete` (and `onError` on the error path) lifecycle hooks for a+ * terminal run through the shared {@link hookDispatcher} β the same mechanism+ * the normal LLM runtime uses via `CompletionLifecycle.dispatchHooks`.+ *+ * This is the single funnel the heterogeneous-agent paths route through so that+ * the task lifecycle (`onTopicComplete`) and IM bot completion callbacks fire+ * uniformly regardless of how the run ended: a CLI process exit+ * (`heteroFinish`), a remote-agent `agentNotify` done signal, or a synchronous+ * dispatch failure (device offline β DEVICE_NOT_FOUND, no bound device, β¦).+ *+ * Always unregisters the operation's hooks afterward, mirroring+ * `CompletionLifecycle.dispatchHooks`. Hook errors are swallowed by the+ * dispatcher and never propagate to the caller.+ */+export async function dispatchTerminalHooks(params: TerminalHookParams): Promise<void> {+ const {+ agentId,+ errorMessage,+ errorType,+ lastAssistantContent,+ operationId,+ reason,+ serializedHooks,+ topicId,+ userId,+ } = params;++ const event: AgentHookEvent = {+ agentId: agentId ?? '',+ errorMessage,+ errorType,+ lastAssistantContent,+ operationId,+ reason,+ status: reason,+ topicId,+ userId,+ };++ try {+ await hookDispatcher.dispatch(operationId, 'onComplete', event, serializedHooks);+ if (reason === 'error') {+ await hookDispatcher.dispatch(operationId, 'onError', event, serializedHooks);+ }+ } catch (error) {+ log('[%s] dispatchTerminalHooks error (non-fatal): %O', operationId, error);+ } finally {+ hookDispatcher.unregister(operationId);+ }+}diff --git a/apps/server/src/services/agentRuntime/hooks/index.ts b/apps/server/src/services/agentRuntime/hooks/index.tsindex a1ab473ed9b..5e1a80e7980 100644--- a/apps/server/src/services/agentRuntime/hooks/index.ts+++ b/apps/server/src/services/agentRuntime/hooks/index.ts@@ -1,3 +1,4 @@+export { dispatchTerminalHooks, type TerminalHookParams } from './dispatchTerminalHooks';export { HookDispatcher, hookDispatcher } from './HookDispatcher';export type {AgentHook,diff --git a/apps/server/src/services/agentRuntime/hooks/types.ts b/apps/server/src/services/agentRuntime/hooks/types.tsindex 3e57eb43eac..7c593535a61 100644--- a/apps/server/src/services/agentRuntime/hooks/types.ts+++ b/apps/server/src/services/agentRuntime/hooks/types.ts@@ -6,6 +6,7 @@*/import type { AgentHookEvent, AgentHookType } from '@lobechat/agent-runtime';+import type { AgentHookWebhookConfig, SerializedAgentHook } from '@lobechat/types';export type {AfterCallAgentHookEvent,@@ -29,15 +30,15 @@ export type {// ββ Server-side Hook Types βββββββββββββββββββββββββββββββ/**- * Webhook delivery configuration for production mode+ * Webhook delivery configuration for production mode.+ *+ * Runtime-precise refinement of the serialized wire shape+ * ({@link AgentHookWebhookConfig} in `@lobechat/types`, used for persistence /+ * zod validation): the shared `body` / `delivery` / `url` are inherited, while+ * `eventFields` is narrowed to `keyof AgentHookEvent` and the server-only+ * `fallback` policy is added.*/-export interface AgentHookWebhook {- /** Custom data merged into webhook payload */- body?: Record<string, unknown>;-- /** Delivery method: 'fetch' (plain HTTP) or 'qstash' (guaranteed delivery). Default: 'qstash' */- delivery?: 'fetch' | 'qstash';-+export interface AgentHookWebhook extends Omit<AgentHookWebhookConfig, 'eventFields'> {/** Event fields to include in the webhook payload. Defaults to all serializable event fields. */eventFields?: (keyof AgentHookEvent)[];@@ -49,9 +50,6 @@ export interface AgentHookWebhook {* it only masks the delivery failure as a silently-dropped 401.*/fallback?: 'fetch' | 'none';-- /** Webhook endpoint URL (relative or absolute) */- url: string;}/**@@ -74,11 +72,16 @@ export interface AgentHook {// ββ Serialized Hook (for Redis persistence) ββββββββββββββ/**- * Serialized hook config stored in AgentState.metadata._hooks- * Only contains webhook info (handler functions can't be serialized)+ * Serialized hook config stored in AgentState.metadata._hooks (and on+ * `topic.metadata.runningOperation.hooks`). Only contains webhook info β+ * handler functions can't be serialized.+ *+ * Runtime-precise refinement of the wire shape ({@link SerializedAgentHook} in+ * `@lobechat/types`): `type` is narrowed to `AgentHookType` and `webhook` to+ * {@link AgentHookWebhook}. A persisted hook read back off topic metadata casts+ * up to this.*/-export interface SerializedHook {- id: string;+export interface SerializedHook extends Omit<SerializedAgentHook, 'type' | 'webhook'> {type: AgentHookType;webhook: AgentHookWebhook;}diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 002e5f6d924..5687421874b 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -72,6 +72,7 @@ import {import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';import { signOperationJwt, signUserJWT } from '@/libs/trpc/utils/internalJwt';+import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import type { EvalContext, ServerAgentToolsContext } from '@/server/modules/Mecha';import { createServerAgentToolsEngine } from '@/server/modules/Mecha';@@ -86,7 +87,7 @@ import type {} from '@/server/services/agentRuntime';import { AgentRuntimeService } from '@/server/services/agentRuntime';import { getAbortError, isAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';-import { hookDispatcher } from '@/server/services/agentRuntime/hooks';+import { dispatchTerminalHooks, hookDispatcher } from '@/server/services/agentRuntime/hooks';import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';import type {ExecGroupMemberParams,@@ -389,6 +390,77 @@ export class AiAgentService {return row ? this.workspaceId : undefined;}+ /**+ * Finalize a hetero run that fails *synchronously at dispatch* β before the+ * CLI/agent process ever starts (device offline β DEVICE_NOT_FOUND, no bound+ * device, access denied, sandbox spawn rejected). These paths never produce a+ * `heteroFinish` (CLI exit) or `agentNotify` done callback, so without this+ * each one would strand the run: the assistant bubble would show an error but+ * the UI stream would never close and a long-run task would hang in `running`.+ *+ * Routes through the SAME terminal funnel a normal exit uses β it fires the+ * run's onComplete/onError hooks via `dispatchTerminalHooks`, so the task+ * lifecycle (onTopicComplete β task failed) and any IM bot completion callback+ * fire exactly as they would for a real failure β then closes the UI stream and+ * clears the (never-started) running operation. The hooks were registered and+ * serialized onto `runningOperation` at dispatch time.+ *+ * Stream-close / hook dispatch / metadata clear are best-effort: a failure+ * there must not mask the original dispatch error the caller surfaces.+ */+ private async finalizeHeteroDispatchError(params: {+ agentId?: string;+ assistantMessageId: string;+ detail: string;+ message: string;+ operationId: string;+ topicId: string;+ }): Promise<void> {+ const { agentId, assistantMessageId, detail, message, operationId, topicId } = params;++ // 1. Error bubble β written first so a stream subscriber reacting to the+ // end event below re-reads a message that already carries the error.+ await this.messageModel.update(assistantMessageId, {+ content: '',+ error: { body: { detail }, message, type: 'ServerAgentRuntimeError' },+ });++ // 2. Close the UI stream.+ try {+ await createStreamEventManager().publishAgentRuntimeEnd({+ finalState: { error: detail },+ operationId,+ reason: 'error',+ reasonDetail: detail,+ stepIndex: 0,+ });+ } catch (err) {+ log('finalizeHeteroDispatchError: publishAgentRuntimeEnd failed (non-fatal): %O', err);+ }++ // 3. Fire onComplete/onError hooks (task lifecycle + bot callback). Hooks+ // were registered in-memory (local mode) and serialized onto+ // runningOperation (queue mode) at dispatch time.+ await dispatchTerminalHooks({+ agentId,+ errorMessage: message,+ errorType: 'ServerAgentRuntimeError',+ operationId,+ reason: 'error',+ serializedHooks: hookDispatcher.getSerializedHooks(operationId),+ topicId,+ userId: this.userId,+ });++ // 4. The operation never started β drop the running marker so reconnect /+ // heteroIngest validation and the next turn don't see a stale operation.+ try {+ await this.topicModel.updateMetadata(topicId, { runningOperation: null });+ } catch (err) {+ log('finalizeHeteroDispatchError: clear runningOperation failed (non-fatal): %O', err);+ }+ }+/*** Resolve the "workspace init" scan (project skills + AGENTS.md) for a run* bound to a device's project directory. Reads the cache on@@ -1352,13 +1424,24 @@ export class AiAgentService {const remoteDeviceId =requestedDeviceId || agentConfig.agencyConfig?.boundDeviceId || undefined;- // Seed topic.metadata.runningOperation so heteroIngest can validate the operation.- // completionWebhook is stored so heteroFinish can call back to the IM bot-callback- // endpoint even though the hetero path bypasses the normal hook registration flow.+ // Register the run's lifecycle hooks so the hetero terminal path fires+ // onComplete/onError through the same `hookDispatcher` the normal LLM+ // runtime uses β driving the task lifecycle (onTopicComplete) and IM bot+ // completion callbacks uniformly. The hetero block returns before+ // AgentRuntimeService (which registers hooks for normal runs), so we do it+ // here. Local mode dispatches these in-memory handlers; queue mode+ // delivers the serialized webhooks persisted on runningOperation below.+ if (hooks?.length) hookDispatcher.register(operationId, hooks);+ const serializedHooks = hookDispatcher.getSerializedHooks(operationId);++ // Seed topic.metadata.runningOperation so heteroIngest can validate the+ // operation, and so every terminal site (heteroFinish, agentNotify done,+ // dispatch failure) can re-fire the serialized hooks across a process+ // boundary in queue mode.await this.topicModel.updateMetadata(topicId, {runningOperation: {assistantMessageId: assistantMessageRecord.id,- completionWebhook: hooks?.find((h) => h.type === 'onComplete')?.webhook,+ hooks: serializedHooks,// Store deviceId + heteroType so interruptTask can cancel remote processes...(isRemoteHetero && remoteDeviceId? { deviceId: remoteDeviceId, heteroType }@@ -1383,13 +1466,13 @@ export class AiAgentService {'execAgent: device access denied for remote hetero dispatch (reason=%s)',deviceAccessReason,);- await this.messageModel.update(assistantMessageRecord.id, {- content: '',- error: {- body: { detail: 'This sender is not allowed to run agents on a bound device.' },- message: 'Device access denied',- type: 'ServerAgentRuntimeError',- },+ await this.finalizeHeteroDispatchError({+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ detail: 'This sender is not allowed to run agents on a bound device.',+ message: 'Device access denied',+ operationId,+ topicId,});return {agentId: resolvedAgentId,@@ -1408,13 +1491,13 @@ export class AiAgentService {}if (!remoteDeviceId) {log('execAgent: openclaw/hermes requires a bound device (boundDeviceId not set)');- await this.messageModel.update(assistantMessageRecord.id, {- content: '',- error: {- body: { detail: 'No device bound to this agent. Configure boundDeviceId.' },- message: 'No bound device for remote hetero agent',- type: 'ServerAgentRuntimeError',- },+ await this.finalizeHeteroDispatchError({+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ detail: 'No device bound to this agent. Configure boundDeviceId.',+ message: 'No bound device for remote hetero agent',+ operationId,+ topicId,});return {agentId: resolvedAgentId,@@ -1434,7 +1517,6 @@ export class AiAgentService {// Open the stream channel so the gateway WS subscription can receive// notify_update events published by agentNotify.notify.- const { createStreamEventManager } = await import('@/server/modules/AgentRuntime/factory');const streamManager = createStreamEventManager();await streamManager.publishAgentRuntimeInit(operationId, {@@ -1473,22 +1555,13 @@ export class AiAgentService {);if (!result.success) {log('execAgent: remote hetero dispatch failed: %s', result.error);- await streamManager- .publishAgentRuntimeEnd({- finalState: { error: result.error },- operationId,- reason: 'error',- reasonDetail: result.error,- stepIndex: 0,- })- .catch(() => {});- await this.messageModel.update(assistantMessageRecord.id, {- content: '',- error: {- body: { detail: result.error },- message: result.error ?? 'Device dispatch failed',- type: 'ServerAgentRuntimeError',- },+ await this.finalizeHeteroDispatchError({+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ detail: result.error ?? 'Device dispatch failed',+ message: result.error ?? 'Device dispatch failed',+ operationId,+ topicId,});return {agentId: resolvedAgentId,@@ -1533,16 +1606,14 @@ export class AiAgentService {const dispatchDeviceId = heteroPlan.kind === 'device' ? heteroPlan.deviceId : undefined;if (!dispatchDeviceId) {log('execAgent: hetero executionTarget=device but no boundDeviceId set');- await this.messageModel.update(assistantMessageRecord.id, {- content: '',- error: {- body: {- detail:- 'No device bound. Pick a device in the Execution Device switcher, or switch to Cloud sandbox.',- },- message: 'No bound device for hetero agent',- type: 'ServerAgentRuntimeError',- },+ await this.finalizeHeteroDispatchError({+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ detail:+ 'No device bound. Pick a device in the Execution Device switcher, or switch to Cloud sandbox.',+ message: 'No bound device for hetero agent',+ operationId,+ topicId,});return {agentId: resolvedAgentId,@@ -1611,13 +1682,13 @@ export class AiAgentService {});if (!result.success) {log('execAgent: hetero device dispatch failed: %s', result.error);- await this.messageModel.update(assistantMessageRecord.id, {- content: '',- error: {- body: { detail: result.error },- message: result.error ?? 'Device dispatch failed',- type: 'ServerAgentRuntimeError',- },+ await this.finalizeHeteroDispatchError({+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ detail: result.error ?? 'Device dispatch failed',+ message: result.error ?? 'Device dispatch failed',+ operationId,+ topicId,});return {agentId: resolvedAgentId,@@ -1644,8 +1715,22 @@ export class AiAgentService {agentType: heteroType as 'claude-code' | 'codex',args: heteroExecArgs,marketService: this.marketService,- }).catch((err) => {+ }).catch(async (err) => {+ // Fire-and-forget: execAgent has already returned `autoStarted`, and+ // the sandbox never reached the point of calling heteroFinish. Drive+ // the same terminal funnel so the stranded run surfaces an error and+ // its task is marked failed instead of hanging in `running`.log('execAgent: hetero sandbox spawn failed: %O', err);+ await this.finalizeHeteroDispatchError({+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ detail: err instanceof Error ? err.message : String(err),+ message: 'Hetero sandbox spawn failed',+ operationId,+ topicId,+ }).catch((finalizeErr) =>+ log('execAgent: sandbox-failure finalize failed: %O', finalizeErr),+ );});}}diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.tsindex 305eaf3a9bd..ca341d21b87 100644--- a/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts+++ b/apps/server/src/services/heterogeneousAgent/__tests__/index.test.ts@@ -3,6 +3,8 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { describe, expect, it, vi } from 'vitest';import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';+import { hookDispatcher } from '@/server/services/agentRuntime/hooks';+import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';import type { HeterogeneousPersistenceHandler } from '..';import { HeterogeneousAgentService, StaleHeteroOperationError } from '..';@@ -262,5 +264,82 @@ describe('HeterogeneousAgentService', () => {reason: 'cancelled',});});++ // The unified terminal funnel: heteroFinish must drive the run's lifecycle+ // hooks through the shared hookDispatcher (the same mechanism the normal LLM+ // path uses), which is what marks the owning task done/failed and fires any+ // IM bot completion callback. These register a local-mode handler hook for+ // the operation and assert heteroFinish dispatches it.+ const registerHook = (operationId: string): { onComplete: any; onError: any } => {+ const onComplete = vi.fn(async () => {});+ const onError = vi.fn(async () => {});+ const hooks: AgentHook[] = [+ { handler: onComplete, id: 'task-on-complete', type: 'onComplete' },+ { handler: onError, id: 'task-on-error', type: 'onError' },+ ];+ hookDispatcher.register(operationId, hooks);+ return { onComplete, onError };+ };++ it('fires onComplete (reason=done) hooks on a successful run', async () => {+ const { service } = createService();+ const { onComplete, onError } = registerHook('op-hook-success');++ await service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-hook-success',+ result: 'success',+ topicId: 'topic-hook-1',+ });++ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onComplete.mock.calls[0][0]).toMatchObject({+ operationId: 'op-hook-success',+ reason: 'done',+ });+ expect(onError).not.toHaveBeenCalled();+ // Hooks are unregistered after dispatch so a replay can't double-fire.+ expect(hookDispatcher.hasHooks('op-hook-success')).toBe(false);+ });++ it('fires both onComplete and onError (reason=error) hooks on a failed run', async () => {+ const { service } = createService();+ const { onComplete, onError } = registerHook('op-hook-error');++ await service.heteroFinish({+ agentType: 'codex',+ error: { message: 'auth required', type: 'AuthRequired' },+ operationId: 'op-hook-error',+ result: 'error',+ topicId: 'topic-hook-2',+ });++ expect(onComplete).toHaveBeenCalledTimes(1);+ expect(onError).toHaveBeenCalledTimes(1);+ expect(onError.mock.calls[0][0]).toMatchObject({+ errorMessage: 'auth required',+ errorType: 'AuthRequired',+ operationId: 'op-hook-error',+ reason: 'error',+ });+ });++ it('does NOT fire hooks on a cancelled run (the real result fires them)', async () => {+ const { service } = createService();+ const { onComplete, onError } = registerHook('op-hook-cancelled');++ await service.heteroFinish({+ agentType: 'claude-code',+ operationId: 'op-hook-cancelled',+ result: 'cancelled',+ topicId: 'topic-hook-3',+ });++ expect(onComplete).not.toHaveBeenCalled();+ expect(onError).not.toHaveBeenCalled();+ // Still registered β the subsequent success/error call will dispatch them.+ expect(hookDispatcher.hasHooks('op-hook-cancelled')).toBe(true);+ hookDispatcher.unregister('op-hook-cancelled');+ });});});diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex f2655063513..7994e6e1551 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -7,8 +7,8 @@ import { ThreadModel } from '@/database/models/thread';import { TopicModel } from '@/database/models/topic';import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';-import { deliverWebhook } from '@/server/services/agentRuntime/hooks/HookDispatcher';-import type { AgentHookWebhook } from '@/server/services/agentRuntime/hooks/types';+import { dispatchTerminalHooks } from '@/server/services/agentRuntime/hooks';+import type { SerializedHook } from '@/server/services/agentRuntime/hooks/types';import {HeterogeneousPersistenceHandler,@@ -181,27 +181,27 @@ export class HeterogeneousAgentService {type: 'agent_runtime_end',});- // Fire the IM bot-callback completion webhook if one was registered.- // The hetero path bypasses the normal AgentHook registration flow, so- // we persist the webhook config in topic.metadata.runningOperation and- // deliver it here instead.+ // Drive the run's lifecycle hooks (onComplete / onError) through the same+ // `hookDispatcher` the normal LLM runtime uses, so the task lifecycle+ // (onTopicComplete β task done/failed) and any IM bot completion callback+ // fire uniformly. The hooks were registered in-memory (local mode) and+ // serialized onto runningOperation (queue mode) at dispatch time.//// Skip on `cancelled` β heteroFinish may be called twice: first with// result=cancelled (termination signal) then with result=success/error- // (normal process exit). We must NOT clear runningOperation on cancelled- // so the subsequent success/error call can still find completionWebhook- // and assistantMessageId. runningOperation is only cleared on the- // delivering call (success/error) so reconnect doesn't retrigger after- // completion β mirrors RuntimeExecutors cleanup for the normal LLM path.- // Transport-level retries of the same result are accepted: BotCallbackService- // reads the latest DB content each time, so duplicates are idempotent.+ // (normal process exit). We must NOT clear runningOperation or fire hooks on+ // cancelled so the subsequent success/error call still finds the hooks ++ // assistantMessageId and dispatches exactly once. (cancelledβinterrupted is a+ // no-op for the task lifecycle anyway β onTopicComplete has no interrupted+ // branch β and suppresses a spurious bot "stopped" message before the real+ // result lands.)if (result === 'cancelled') return;- let completionWebhook: AgentHookWebhook | undefined;+ let serializedHooks: SerializedHook[] | undefined;let assistantMessageId: string | undefined;try {const topic = await this.topicModel.findById(topicId);- completionWebhook = topic?.metadata?.runningOperation?.completionWebhook;+ serializedHooks = topic?.metadata?.runningOperation?.hooks as SerializedHook[] | undefined;// Prefer heteroCurrentMsgId β the persistence handler updates this pointer// on every step boundary, so it refers to the LAST assistant message with// the complete final content. Fall back to the initial placeholder id@@ -217,37 +217,31 @@ export class HeterogeneousAgentService {log('heteroFinish: failed to clear runningOperation (non-fatal): %O', err);}- if (completionWebhook?.url) {+ // Read the final assistant content + owning agent so the bot-callback+ // handler has lastAssistantContent to render and the event carries agentId.+ let lastAssistantContent: string | undefined;+ let agentId: string | undefined;+ if (assistantMessageId) {try {- // Read the final assistant message content so BotCallbackService.handleCompletion- // has lastAssistantContent to render. Without it the handler skips delivery.- let lastAssistantContent: string | undefined;- if (assistantMessageId) {- const msg = await this.messageModel.findById(assistantMessageId);- lastAssistantContent = msg?.content as string | undefined;- }-- // Map hetero result β reason expected by handleCompletion- const reason = result === 'success' ? 'done' : 'error';-- await deliverWebhook(completionWebhook, {- // Dynamic completion fields (event-like payload)- ...(error ? { errorMessage: error.message, errorType: error.type } : {}),- hookId: 'bot-completion',- hookType: 'onComplete',- lastAssistantContent,- operationId,- reason,- // Static IM context stored at hook registration time β spread last so- // platform fields (applicationId, platformThreadId, type, userPrompt)- // are authoritative, matching HookDispatcher's { ...event, ...body } order.- ...completionWebhook.body,- });- log('heteroFinish: completionWebhook delivered for op=%s result=%s', operationId, result);+ const msg = await this.messageModel.findById(assistantMessageId);+ lastAssistantContent = msg?.content as string | undefined;+ agentId = msg?.agentId ?? undefined;} catch (err) {- log('heteroFinish: completionWebhook delivery failed (non-fatal): %O', err);+ log('heteroFinish: failed to read final assistant message (non-fatal): %O', err);}}++ await dispatchTerminalHooks({+ agentId,+ ...(error ? { errorMessage: error.message, errorType: error.type } : {}),+ lastAssistantContent,+ operationId,+ reason: result === 'success' ? 'done' : 'error',+ serializedHooks,+ topicId,+ userId: this.userId,+ });+ log('heteroFinish: dispatched terminal hooks for op=%s result=%s', operationId, result);}/**diff --git a/packages/types/src/agentHook.ts b/packages/types/src/agentHook.tsnew file mode 100644index 00000000000..18b277260da--- /dev/null+++ b/packages/types/src/agentHook.ts@@ -0,0 +1,32 @@+import { z } from 'zod';++/**+ * Serialized webhook config for an agent lifecycle hook β the wire shape+ * persisted on a running operation and delivered in queue mode.+ *+ * This is the transport view. The server's runtime `AgentHookWebhook` is a+ * richer superset (its `eventFields` is keyed to `AgentHookEvent`); reading a+ * persisted hook back casts up to it.+ */+export const agentHookWebhookSchema = z.object({+ body: z.record(z.unknown()).optional(),+ delivery: z.enum(['fetch', 'qstash']).optional(),+ eventFields: z.array(z.string()).optional(),+ url: z.string(),+});++/**+ * Serialized agent lifecycle hook (onComplete / onError / β¦). Only hooks+ * carrying a webhook are serializable β handler closures can't cross a process+ * boundary β so this is what gets persisted (e.g. on+ * `topic.metadata.runningOperation.hooks`) and replayed through the shared+ * hookDispatcher by every terminal site.+ */+export const serializedAgentHookSchema = z.object({+ id: z.string(),+ type: z.string(),+ webhook: agentHookWebhookSchema,+});++export type AgentHookWebhookConfig = z.infer<typeof agentHookWebhookSchema>;+export type SerializedAgentHook = z.infer<typeof serializedAgentHookSchema>;diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 64c732f8ac5..58041b2f174 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -1,6 +1,7 @@export * from './agent';export * from './agentExecution';export * from './agentGroup';+export * from './agentHook';export * from './aiChat';export * from './aiProvider';export * from './artifact';diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex fed57fd974f..9a6b6e9307f 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -1,5 +1,6 @@import { z } from 'zod';+import type { SerializedAgentHook } from '../agentHook';import type { BaseDataModel } from '../meta';// Type definitions@@ -158,16 +159,20 @@ export interface ChatTopicMetadata {runningOperation?: {assistantMessageId: string;/**- * Webhook to fire when the operation completes.- * Populated by the IM bot path so heterogeneous agents (Claude Code / Codex)- * can call back to the bot-callback endpoint even though they bypass the- * normal hook registration flow.+ * Serialized lifecycle hooks (onComplete / onError) registered for this run.+ *+ * Persisted so the heterogeneous-agent terminal path can fire them through+ * the same `hookDispatcher` the normal LLM runtime uses, instead of a+ * bespoke single-webhook callback. Read by every hetero terminal site β+ * the CLI exit (`aiAgent.heteroFinish`), the remote-agent `agentNotify`+ * done signal, and a synchronous dispatch failure β so the task lifecycle+ * (`onTopicComplete`) and IM bot completion callbacks fire uniformly.+ *+ * Only hooks carrying a webhook config are serializable (handler closures+ * can't cross a process boundary); queue mode delivers these webhooks while+ * local mode dispatches the in-memory handlers registered at dispatch time.*/- completionWebhook?: {- body?: Record<string, unknown>;- delivery?: 'fetch' | 'qstash';- url: string;- };+ hooks?: SerializedAgentHook[];operationId: string;scope?: string;threadId?: string | null;