π€― 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
β»οΈ refactor(agent-runtime): converge all terminal completion paths onto CompletionLifecycle (#16523)
Arvin Xue674ae3a7610
diff --git a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts b/apps/server/src/routers/lambda/__tests__/agentNotify.test.tsindex aa46956cb86..d2f9172c1b6 100644--- a/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentNotify.test.ts@@ -21,6 +21,18 @@ const mockMessageFindById = vi.fn();const mockMessageUpdate = vi.fn();const mockMessageCreate = vi.fn();const mockExecAgent = vi.fn();+const mockOpFindById = vi.fn();+const mockInstantiateVerifyPlan = vi.fn();++vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn(() => ({ findById: mockOpFindById })),+}));+// Partial mock: keep the real runVerifyOnCompletion (CompletionLifecycle's gate+// imports it from this barrel) and only stub the start-side plan instantiation.+vi.mock('@/server/services/verify', async (orig) => ({+ ...(await (orig as () => Promise<Record<string, unknown>>)()),+ instantiateVerifyPlanOnStart: mockInstantiateVerifyPlan,+}));vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn(() => ({@@ -89,6 +101,10 @@ describe('agentNotifyRouter.notify β remote hetero terminal signal', () => {// by earlier `lh notify` calls).mockMessageFindById.mockResolvedValue({ content: 'the final reply', topicId: TOPIC });mockTopicUpdateMetadata.mockResolvedValue(undefined);+ // Default: a non-task op so the plan-instantiation guard no-ops unless a+ // test opts into a task-bound op.+ mockOpFindById.mockResolvedValue({ parentOperationId: null, taskId: null });+ mockInstantiateVerifyPlan.mockResolvedValue(undefined);});afterEach(() => {@@ -123,6 +139,45 @@ describe('agentNotifyRouter.notify β remote hetero terminal signal', () => {);});+ it('durably ensures the verify plan for a task-bound run before the gate', async () => {+ // The start-side plan instantiation (execAgent) is fire-and-forget on a+ // SEPARATE CompletionLifecycle instance, so the completion-side gate here+ // can't await it β a fast remote task could reach the gate before the plan+ // persists and silently skip verify. This path must re-run the idempotent+ // instantiation for a top-level task op so the gate has a plan to read.+ const { onComplete } = registerHooks();+ mockOpFindById.mockResolvedValue({ parentOperationId: null, taskId: 'task-9' });++ await createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC });++ await vi.waitFor(() => expect(mockInstantiateVerifyPlan).toHaveBeenCalledTimes(1));+ // Ensured with the run's own operationId + taskId (3rd arg is the params object).+ expect(mockInstantiateVerifyPlan.mock.calls[0][2]).toMatchObject({+ operationId: OP,+ taskId: 'task-9',+ });+ // Ordered before the gate: the ensure resolves before completeOperation fires+ // onComplete (β runVerifyOnCompletion).+ await vi.waitFor(() => expect(onComplete).toHaveBeenCalledTimes(1));+ expect(mockInstantiateVerifyPlan.mock.invocationCallOrder[0]).toBeLessThan(+ onComplete.mock.invocationCallOrder[0],+ );+ });++ it('skips verify-plan instantiation for a repair / non-task run', async () => {+ registerHooks();+ // A repair op carries a parentOperationId β its plan comes from the repair+ // path, not the start-side instantiation.+ mockOpFindById.mockResolvedValue({ parentOperationId: 'parent-op', taskId: 'task-9' });++ await createCaller().notify({ content: '', done: true, role: 'assistant', topicId: TOPIC });++ await vi.waitFor(() =>+ expect(mockTopicUpdateMetadata).toHaveBeenCalledWith(TOPIC, { runningOperation: null }),+ );+ expect(mockInstantiateVerifyPlan).not.toHaveBeenCalled();+ });+it('error signal finalizes the run as failed and fires onError', async () => {const { onComplete, onError } = registerHooks();diff --git a/apps/server/src/routers/lambda/agentNotify.ts b/apps/server/src/routers/lambda/agentNotify.tsindex 823cde68b5f..987709527a3 100644--- a/apps/server/src/routers/lambda/agentNotify.ts+++ b/apps/server/src/routers/lambda/agentNotify.ts@@ -5,14 +5,16 @@ import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { AgentOperationModel } from '@/database/models/agentOperation';import { MessageModel } from '@/database/models/message';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 { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';import type { SerializedHook } from '@/server/services/agentRuntime/hooks/types';import { AiAgentService } from '@/server/services/aiAgent';+import { instantiateVerifyPlanOnStart } from '@/server/services/verify';// Module-level singleton so we don't create a new Redis connection per request.let _streamManager: ReturnType<typeof createStreamEventManager> | undefined;@@ -132,8 +134,7 @@ export const agentNotifyRouter = router({// Extract the operationId seeded by execAgent for remote hetero agents.// Used to publish notify_update / agent_runtime_end events to the gateway WS.const remoteOperationId = (topic.metadata as any)?.runningOperation?.operationId as- | string- | undefined;+ string | undefined;const agentId = inputAgentId ?? topic.agentId;if (!agentId) {@@ -165,31 +166,85 @@ export const agentNotifyRouter = router({});// 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.+ // this is its terminal funnel. Route it through CompletionLifecycle's+ // single entry β the SAME owner the CLI / in-process paths use β so+ // persistCompletion writes the terminal op row, onComplete/onError hooks+ // fire (task lifecycle β task done/failed + IM bot callback), and on+ // success the delivery-checker verify gate runs against the task's plan.+ // (Previously this fired the stripped-down dispatchTerminalHooks, which+ // skipped persist + verify β so openclaw/hermes tasks never auto-verified.)+ // Hooks were serialized onto runningOperation at dispatch time.const serializedHooks = (topic.metadata as any)?.runningOperation?.hooks as- | SerializedHook[]- | undefined;+ 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,- });+ // Mirror heteroFinish's done-path prep (this is the openclaw/hermes+ // equivalent terminal funnel). Skipped on the error path (verify is+ // done-only). Each step is self-guarded so a failure degrades instead+ // of aborting the terminal funnel.+ let goal: unknown = '';+ if (!terminalError) {+ // Guarantee the task's verify plan is DURABLY persisted before the gate+ // (completeOperation β runVerifyOnCompletion) reads it. The start-side+ // instantiation in execAgent is fire-and-forget on a SEPARATE+ // CompletionLifecycle instance, so its in-memory await can't bridge to+ // THIS notify request β a fast remote task could otherwise reach the+ // gate before the plan lands and silently skip verify (and the+ // verify-bound task deferral). instantiateVerifyPlanOnStart is+ // idempotent, so awaiting it here creates the plan only when the start+ // side hasn't yet, and is a no-op once it has.+ try {+ const op = await new AgentOperationModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).findById(remoteOperationId);+ if (op?.taskId && !op.parentOperationId) {+ await instantiateVerifyPlanOnStart(+ ctx.serverDB,+ ctx.userId,+ { operationId: remoteOperationId, taskId: op.taskId },+ ctx.workspaceId ?? undefined,+ );+ }+ } catch (err) {+ log('notify: ensure verify plan failed (non-fatal): %O', err);+ }+ // Resolve the run goal (first user turn) β the verify gate judges the+ // deliverable against it. Wrapped in try/catch (not just a promise+ // `.catch`) so a throwing/absent query degrades to an empty goal.+ try {+ const history = await ctx.messageModel.query({ pageSize: 50, topicId });+ goal = history.find((m) => m.role === 'user')?.content ?? '';+ } catch (err) {+ log('notify: failed to resolve verify goal (non-fatal): %O', err);+ }+ }+ await new CompletionLifecycle(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).completeOperation(+ {+ agentId,+ assistantMessageId: writtenMessageId,+ deliverable: lastAssistantContent,+ error: terminalError ?? undefined,+ goal,+ operationId: remoteOperationId,+ serializedHooks,+ topicId,+ userId: ctx.userId,+ },+ terminalError ? 'error' : 'done',+ // openclaw/hermes surface their failure via the runtime-end stream event+ // + their own message write, not the lifecycle's assistant-row error+ // write β keep that prior behavior on the error path.+ { skipErrorMessageWrite: true },+ );// The operation is finished β drop the running marker so a duplicate// terminal signal / reconnect doesn't re-fire the hooks.diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.tsindex 61d50599fa1..d668cc96d81 100644--- a/apps/server/src/routers/lambda/verify.ts+++ b/apps/server/src/routers/lambda/verify.ts@@ -24,6 +24,7 @@ import { publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { FileService } from '@/server/services/file';import {+ finalizeVerifyRun,VerifyExecutorService,VerifyFeedbackService,VerifyPlanGeneratorService,@@ -387,6 +388,24 @@ export const verifyRouter = router({).mutation(async ({ ctx, input }) => {await ctx.executorService.execute(input);+ // Settle the run through the SAME finalizer the completion-time gate uses+ // (runVerifyOnCompletion β finalizeVerifyRun): repair-aware tail (spawn a+ // repair round on auto_repair failures), then report + drive the bound task.+ // Without this, a verify triggered via the CLI (`lh verify run`, e.g. a+ // device/agent-testing run) would write verdicts and stop β never auto-repair.+ await finalizeVerifyRun(+ ctx.serverDB,+ ctx.userId,+ input.operationId,+ {+ report: {+ deliverable: input.deliverable,+ goal: input.goal,+ modelConfig: input.modelConfig,+ },+ },+ ctx.workspaceId ?? undefined,+ );const run = await ctx.runModel.findByOperation(input.operationId);return run ? ctx.resultModel.listByRun(run.id) : [];}),diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex b46daa66369..0b0c21e3e1b 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -15,12 +15,67 @@ import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observabimport { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/services/verify';-import { hookDispatcher } from './hooks';+import { hookDispatcher, type SerializedHook } from './hooks';const log = debug('lobe-server:completion-lifecycle');type SignalEvent = { [key: string]: unknown; type: string };+/**+ * Normalized terminal-completion input for {@link CompletionLifecycle.completeOperation}.+ *+ * This is the single typed shape every NON-in-process terminal path passes in β+ * heterogeneous CLI exit (`heteroFinish`), remote-agent done signal+ * (`agentNotify`), and synchronous dispatch failure+ * (`finalizeHeteroDispatchError`). `completeOperation` expands it into the+ * runtime `state` shape `dispatchHooks` consumes via one builder, so there is+ * exactly ONE place that mirrors the runtime state β no per-caller hand-rolled+ * synthetic state to drift.+ *+ * The in-process runtime keeps calling `dispatchHooks` with its real, rich+ * `state` directly (full message array, interruption, β¦) β it needs no synthesis.+ */+export interface OperationCompletionInput {+ /** Owning agent id β trace snapshot key + the lifecycle event's `agentId`. */+ agentId?: string;+ /** Final assistant message row id β anchors the verify card / error bubble. */+ assistantMessageId?: string;+ cost?: { total?: number | null } | null;+ /** Final assistant deliverable text β the verify gate's input + bot rendering. */+ deliverable?: string;+ /** Terminal error payload (error path only). */+ error?: unknown;+ /**+ * The user goal (first user turn) β the verify gate judges against it. Typed+ * `unknown` because message content is polymorphic (string or multimodal part+ * array); `dispatchHooks` normalizes it to text the same way it does the+ * in-process path's user turn.+ */+ goal?: unknown;+ /** Executed model β the verify gate keys off `op.model`, so hetero backfills it. */+ model?: string | null;+ operationId: string;+ /** Executed provider β see {@link OperationCompletionInput.model}. */+ provider?: string | null;+ /** Serialized webhook hooks (queue mode); ignored in local in-memory mode. */+ serializedHooks?: SerializedHook[];+ stepCount?: number | null;+ topicId?: string;+ /** Trace / usage aggregates (llm calls, tokens, tool calls). */+ usage?: unknown;+ userId?: string;+}++/** Options shared by {@link CompletionLifecycle.completeOperation} / `dispatchHooks`. */+export interface CompleteOperationOptions {+ /**+ * Skip writing the terminal error onto the assistant message row. Set by callers+ * that already wrote a bespoke error bubble before delegating (e.g. the hetero+ * dispatch-failure path, which surfaces a device-specific `detail`).+ */+ skipErrorMessageWrite?: boolean;+}+const toAgentSignalSnapshotEvents = (emission: Awaited<ReturnType<typeof emitAgentSignalSourceEvent>> | undefined,): SignalEvent[] => {@@ -352,13 +407,66 @@ export class CompletionLifecycle {}}+ /**+ * Expand a normalized {@link OperationCompletionInput} into the runtime `state`+ * shape `dispatchHooks` consumes. The SINGLE place that mirrors the runtime+ * state for non-in-process paths β goal/deliverable become the user/assistant+ * turns the gate reads, model/provider backfill the op row, hooks ride on+ * `metadata._hooks`. Replaces the per-caller hand-rolled synthetic state that+ * previously drifted (e.g. a verify field added here was missed by heteroFinish).+ */+ private buildStateFromInput(input: OperationCompletionInput) {+ return {+ cost: input.cost ?? { total: null },+ error: input.error ?? undefined,+ messages: [+ { content: input.goal ?? '', role: 'user' },+ { content: input.deliverable ?? '', role: 'assistant' },+ ],+ metadata: {+ _hooks: input.serializedHooks,+ agentId: input.agentId,+ assistantMessageId: input.assistantMessageId,+ topicId: input.topicId,+ userId: input.userId ?? this.userId,+ },+ model: input.model ?? undefined,+ provider: input.provider ?? undefined,+ stepCount: input.stepCount ?? null,+ usage: input.usage ?? undefined,+ };+ }++ /**+ * The single terminal-completion entry for every path that does NOT have the+ * in-process runtime's rich `state` in hand: heterogeneous CLI exit+ * (`heteroFinish`), remote-agent done signal (`agentNotify`), and synchronous+ * dispatch failure (`finalizeHeteroDispatchError`). Builds the synthetic state+ * once and runs the SAME pipeline the in-process runtime uses β persist the+ * terminal op row, fire onComplete/onError hooks, and (on `done`) run the+ * delivery-checker verify gate. This is what makes those paths true lifecycle+ * peers instead of firing a stripped-down hooks-only funnel.+ */+ async completeOperation(+ input: OperationCompletionInput,+ reason: 'done' | 'error',+ options?: CompleteOperationOptions,+ ): Promise<void> {+ await this.dispatchHooks(input.operationId, this.buildStateFromInput(input), reason, options);+ }+/*** Dispatch `onComplete` (and `onError` for `reason='error'`) hooks via* the global `hookDispatcher`. On the error path, also writes the error* back onto the assistant message row so the frontend can render it.* Fire-and-forget; always unregisters the operation from the dispatcher.*/- async dispatchHooks(operationId: string, state: any, reason: string): Promise<void> {+ async dispatchHooks(+ operationId: string,+ state: any,+ reason: string,+ options?: CompleteOperationOptions,+ ): Promise<void> {// `waiting_for_async_tool` parks the SAME operation: it persists the parked// status (the async-tool resume CAS reads it) but must NOT fire `onComplete`// or unregister hooks β the op resumes under this same id and reaches its@@ -419,7 +527,7 @@ export class CompletionLifecycle {await hookDispatcher.dispatch(operationId, 'onError', event, metadata._hooks);const assistantMessageId = metadata?.assistantMessageId;- if (assistantMessageId && state?.error) {+ if (assistantMessageId && state?.error && !options?.skipErrorMessageWrite) {// Preserve the semantic error type written by the runtime. Rebuilding// this as a generic AgentRuntimeError would lose UI routing data such// as quota context and force the client into the fallback card.diff --git a/apps/server/src/services/agentRuntime/hooks/dispatchTerminalHooks.ts b/apps/server/src/services/agentRuntime/hooks/dispatchTerminalHooks.tsdeleted file mode 100644index 2a2f7d8c632..00000000000--- a/apps/server/src/services/agentRuntime/hooks/dispatchTerminalHooks.ts+++ /dev/null@@ -1,80 +0,0 @@-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 5e1a80e7980..a1ab473ed9b 100644--- a/apps/server/src/services/agentRuntime/hooks/index.ts+++ b/apps/server/src/services/agentRuntime/hooks/index.ts@@ -1,4 +1,3 @@-export { dispatchTerminalHooks, type TerminalHookParams } from './dispatchTerminalHooks';export { HookDispatcher, hookDispatcher } from './HookDispatcher';export type {AgentHook,diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex dc865b76ca4..59110b9a646 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -91,7 +91,7 @@ import type {import { AgentRuntimeService } from '@/server/services/agentRuntime';import { getAbortError, isAbortError, throwIfAborted } from '@/server/services/agentRuntime/abort';import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';-import { dispatchTerminalHooks, hookDispatcher } from '@/server/services/agentRuntime/hooks';+import { hookDispatcher } from '@/server/services/agentRuntime/hooks';import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';import type {ExecGroupMemberParams,@@ -473,12 +473,13 @@ export class AiAgentService {* 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.+ * Routes through the SAME terminal funnel a normal exit uses β+ * `CompletionLifecycle.completeOperation` finalizes the op row and fires the+ * run's onComplete/onError hooks, 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.@@ -500,20 +501,27 @@ export class AiAgentService {error: { body: { detail }, message, type: 'ServerAgentRuntimeError' },});- // 1b. Mark the agent_operations row terminal. The row was inserted at- // recordStart, but a dispatch failure goes through THIS path, not- // heteroFinish β so without this the row stays status='running' forever- // and pollutes operation-lifecycle / verify views for failed starts.- try {- await this.agentOperationModel.recordCompletion(operationId, {- completedAt: new Date(),- completionReason: 'error',+ // 1b. Finalize the run through CompletionLifecycle's single entry β the SAME+ // owner the CLI exit (heteroFinish) / in-process paths use. It marks the+ // agent_operations row terminal (the row was inserted at recordStart, but a+ // dispatch failure goes through THIS path, not heteroFinish, so without+ // finalizing it the row stays status='running' forever) AND fires the run's+ // onComplete/onError hooks (task lifecycle β task failed + IM bot callback).+ // `skipErrorMessageWrite` keeps the bespoke device-specific bubble written+ // in step 1; verify is done-only, so it no-ops on this error path.+ await new CompletionLifecycle(this.db, this.userId, this.workspaceId).completeOperation(+ {+ agentId,+ assistantMessageId,error: { message, type: 'ServerAgentRuntimeError' },- status: 'error',- });- } catch (err) {- log('finalizeHeteroDispatchError: recordCompletion failed (non-fatal): %O', err);- }+ operationId,+ serializedHooks: hookDispatcher.getSerializedHooks(operationId),+ topicId,+ userId: this.userId,+ },+ 'error',+ { skipErrorMessageWrite: true },+ );// 2. Close the UI stream.try {@@ -528,21 +536,7 @@ export class AiAgentService {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 /+ // 3. 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 });@@ -1312,10 +1306,7 @@ export class AiAgentService {const heteroProviderType = agentConfig.agencyConfig?.heterogeneousProvider?.type;const isHeteroAgent = !!heteroProviderType || HETERO_AGENT_MODELS.has(model);const heteroType = (heteroProviderType ?? model) as- | 'claude-code'- | 'codex'- | 'hermes'- | 'openclaw';+ 'claude-code' | 'codex' | 'hermes' | 'openclaw';// ββ Shared turn setup (runs for BOTH hetero and normal agents) ββββββββββ// Everything up to and including persisting the turn is identical for both@@ -4219,8 +4210,7 @@ export class AiAgentService {if (topicId) {const topic = await this.topicModel.findById(topicId);const runningOp = (topic?.metadata as any)?.runningOperation as- | { deviceId?: string; heteroType?: string; operationId?: string }- | undefined;+ { deviceId?: string; heteroType?: string; operationId?: string } | undefined;if (runningOp?.deviceId &&diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.tsindex b67dd48c63b..240b0bebac0 100644--- a/apps/server/src/services/heterogeneousAgent/index.ts+++ b/apps/server/src/services/heterogeneousAgent/index.ts@@ -320,50 +320,42 @@ export class HeterogeneousAgentService {}}- // Route the terminal transition through CompletionLifecycle β the SAME owner- // the in-process runtime uses β instead of the stripped-down dispatchTerminalHooks.- // This is what makes the hetero run a true lifecycle peer: persistCompletion- // writes the terminal op row (model/provider backfilled from the CLI stream via- // `state.model/provider`), onComplete/onError hooks fire through hookDispatcher,+ // Route the terminal transition through CompletionLifecycle's single entry β+ // the SAME owner the in-process runtime uses β instead of the stripped-down+ // dispatchTerminalHooks. This is what makes the hetero run a true lifecycle+ // peer: persistCompletion writes the terminal op row (model/provider backfilled+ // from the CLI stream), onComplete/onError hooks fire through hookDispatcher,// and on success the delivery-checker card + verify gate run against the task's- // plan. We synthesize the runtime `state` shape CompletionLifecycle reads:- // metadata (agentId/topicId/userId/assistantMessageId/_hooks), the goal+reply- // messages, and the trace aggregates mapped into usage/cost.- const syntheticState = {- cost: { total: totals?.totalCost ?? null },- error: error ?? undefined,- messages: [- { content: goalContent, role: 'user' },- { content: lastAssistantContent ?? '', role: 'assistant' },- ],- metadata: {- _hooks: serializedHooks,+ // plan. `completeOperation` owns the (formerly hand-rolled) synthetic-state+ // build, so the goal+reply turns and trace aggregates are mapped in ONE place.+ await new CompletionLifecycle(this.db, this.userId, this.workspaceId).completeOperation(+ {agentId,assistantMessageId,+ cost: { total: totals?.totalCost ?? null },+ deliverable: lastAssistantContent ?? '',+ error: error ?? undefined,+ goal: goalContent,+ // Backfilled executed model/provider β the verify gate bails when absent.+ model: totals?.model,+ operationId,+ provider: totals?.provider,+ serializedHooks,+ stepCount: totals?.stepCount ?? null,topicId,- userId: this.userId,- },- // Backfilled executed model/provider β persistCompletion writes these and the- // verify gate (lifecycle.ts) bails when op.model/provider are absent.- model: totals?.model,- provider: totals?.provider,- stepCount: totals?.stepCount ?? null,- usage: {- llm: {- apiCalls: totals?.llmCalls ?? null,- tokens: {- input: totals?.totalInputTokens ?? null,- output: totals?.totalOutputTokens ?? null,- total: totals?.totalTokens ?? null,+ usage: {+ llm: {+ apiCalls: totals?.llmCalls ?? null,+ tokens: {+ input: totals?.totalInputTokens ?? null,+ output: totals?.totalOutputTokens ?? null,+ total: totals?.totalTokens ?? null,+ },},+ tools: { totalCalls: totals?.toolCalls ?? null },},- tools: { totalCalls: totals?.toolCalls ?? null },+ userId: this.userId,},- };-- await new CompletionLifecycle(this.db, this.userId, this.workspaceId).dispatchHooks(- operationId,- syntheticState,completionReason,);log('heteroFinish: dispatched completion lifecycle for op=%s result=%s', operationId, result);