Skip to content

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

✨ feat(agent-runtime): persist agent operations to `agent_operations` table (#14736)

Arvin Xua77234107e08
diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.ts
new file mode 100644
index 00000000000..5a314bb3732
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentOperation.test.ts
@@ -0,0 +1,186 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agentOperations, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentOperationModel } from '../agentOperation';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'agent-operation-test-user-id';
+const otherUserId = 'agent-operation-test-other-user';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(agentOperations);
+ await serverDB.delete(users);
+});
+
+describe('AgentOperationModel', () => {
+ describe('recordStart', () => {
+ it('inserts a row with status=running and the provided ids', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-start-1';
+
+ await model.recordStart({
+ appContext: { scope: 'chat', sourceMessageId: 'msg-1' },
+ maxSteps: 20,
+ model: 'gpt-4o',
+ modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },
+ operationId,
+ provider: 'openai',
+ trigger: 'chat',
+ });
+
+ const row = await model.findById(operationId);
+ expect(row).toMatchObject({
+ appContext: { scope: 'chat', sourceMessageId: 'msg-1' },
+ id: operationId,
+ maxSteps: 20,
+ model: 'gpt-4o',
+ modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },
+ provider: 'openai',
+ status: 'running',
+ trigger: 'chat',
+ userId,
+ });
+ expect(row?.startedAt).toBeInstanceOf(Date);
+ expect(row?.completedAt).toBeNull();
+ });
+
+ it('is idempotent on the primary key', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-start-2';
+
+ await model.recordStart({ operationId });
+ // Second call must not throw — primary-key conflict is swallowed.
+ await model.recordStart({ operationId });
+
+ const rows = await serverDB
+ .select()
+ .from(agentOperations)
+ .where(eq(agentOperations.id, operationId));
+ expect(rows).toHaveLength(1);
+ });
+ });
+
+ describe('recordCompletion', () => {
+ it('updates the row to a terminal status with aggregates and trace key', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-complete-1';
+
+ const completedAt = new Date('2026-05-13T01:23:45.000Z');
+ await model.recordStart({ operationId });
+ await model.recordCompletion(operationId, {
+ completedAt,
+ completionReason: 'done',
+ cost: { total: 0.123 },
+ llmCalls: 4,
+ processingTimeMs: 5432,
+ status: 'done',
+ stepCount: 7,
+ toolCalls: 2,
+ totalCost: 0.123,
+ totalInputTokens: 1000,
+ totalOutputTokens: 200,
+ totalTokens: 1200,
+ traceS3Key: 'agent-traces/agent-x/topic-x/op-complete-1.json',
+ usage: { llm: { apiCalls: 4 } },
+ });
+
+ const row = await model.findById(operationId);
+ expect(row).toMatchObject({
+ completionReason: 'done',
+ cost: { total: 0.123 },
+ llmCalls: 4,
+ processingTimeMs: 5432,
+ status: 'done',
+ stepCount: 7,
+ toolCalls: 2,
+ totalCost: 0.123,
+ totalInputTokens: 1000,
+ totalOutputTokens: 200,
+ totalTokens: 1200,
+ traceS3Key: 'agent-traces/agent-x/topic-x/op-complete-1.json',
+ });
+ expect(row?.completedAt?.toISOString()).toBe(completedAt.toISOString());
+ });
+
+ it('leaves completedAt null when not explicitly provided (e.g. waiting_for_human)', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-waiting';
+
+ await model.recordStart({ operationId });
+ await model.recordCompletion(operationId, {
+ completionReason: 'waiting_for_human',
+ status: 'waiting_for_human',
+ });
+
+ const row = await model.findById(operationId);
+ expect(row?.status).toBe('waiting_for_human');
+ expect(row?.completedAt).toBeNull();
+ });
+
+ it('writes error and interruption payloads on failure paths', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-complete-error';
+
+ await model.recordStart({ operationId });
+ await model.recordCompletion(operationId, {
+ completedAt: new Date(),
+ completionReason: 'error',
+ error: { message: 'boom', type: 'AgentRuntimeError' },
+ interruption: {
+ canResume: false,
+ interruptedAt: '2026-05-13T00:00:00.000Z',
+ reason: 'rate_limited',
+ },
+ status: 'error',
+ });
+
+ const row = await model.findById(operationId);
+ expect(row?.status).toBe('error');
+ expect(row?.completionReason).toBe('error');
+ expect(row?.error).toMatchObject({ message: 'boom', type: 'AgentRuntimeError' });
+ expect(row?.interruption).toMatchObject({ canResume: false, reason: 'rate_limited' });
+ });
+
+ it('is a no-op when the start row was never written', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ // No prior recordStart — recordCompletion must not throw and must not
+ // create a phantom row.
+ await model.recordCompletion('op-missing', { status: 'done', completionReason: 'done' });
+
+ const row = await model.findById('op-missing');
+ expect(row).toBeNull();
+ });
+
+ it('does not flip another user’s row when their operationId is known', async () => {
+ const ownerModel = new AgentOperationModel(serverDB, userId);
+ const attackerModel = new AgentOperationModel(serverDB, otherUserId);
+ const operationId = 'op-cross-user';
+
+ await ownerModel.recordStart({ operationId });
+ await attackerModel.recordCompletion(operationId, {
+ completedAt: new Date(),
+ completionReason: 'error',
+ error: { message: 'spoofed', type: 'AgentRuntimeError' },
+ status: 'error',
+ });
+
+ // Owner's row must still read as running — the cross-user update is
+ // filtered out by the userId scope in the WHERE clause.
+ const row = await ownerModel.findById(operationId);
+ expect(row?.status).toBe('running');
+ expect(row?.error).toBeNull();
+ // The attacker cannot read the row either.
+ expect(await attackerModel.findById(operationId)).toBeNull();
+ });
+ });
+});
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
new file mode 100644
index 00000000000..061bf064cd2
--- /dev/null
+++ b/packages/database/src/models/agentOperation.ts
@@ -0,0 +1,138 @@
+import { and, eq } from 'drizzle-orm';
+
+import type {
+ AgentOperationAppContext,
+ AgentOperationError,
+ AgentOperationInterruption,
+ NewAgentOperation,
+} from '../schemas/agentOperations';
+import { agentOperations } from '../schemas/agentOperations';
+import type { LobeChatDatabase } from '../type';
+
+export interface RecordOperationStartParams {
+ agentId?: string | null;
+ appContext?: AgentOperationAppContext;
+ chatGroupId?: string | null;
+ maxSteps?: number;
+ model?: string;
+ modelRuntimeConfig?: Record<string, unknown>;
+ operationId: string;
+ parentOperationId?: string | null;
+ provider?: string;
+ startedAt?: Date;
+ taskId?: string | null;
+ threadId?: string | null;
+ topicId?: string | null;
+ trigger?: string;
+}
+
+export interface RecordOperationCompletionParams {
+ completedAt?: Date;
+ completionReason?:
+ | 'done'
+ | 'error'
+ | 'interrupted'
+ | 'max_steps'
+ | 'cost_limit'
+ | 'waiting_for_human';
+ cost?: Record<string, unknown> | null;
+ error?: AgentOperationError | null;
+ interruption?: AgentOperationInterruption | null;
+ llmCalls?: number | null;
+ processingTimeMs?: number | null;
+ status: 'running' | 'waiting_for_human' | 'done' | 'error' | 'interrupted';
+ stepCount?: number | null;
+ toolCalls?: number | null;
+ totalCost?: number | null;
+ totalInputTokens?: number | null;
+ totalOutputTokens?: number | null;
+ totalTokens?: number | null;
+ traceS3Key?: string | null;
+ usage?: Record<string, unknown> | null;
+}
+
+export class AgentOperationModel {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.db = db;
+ this.userId = userId;
+ }
+
+ /**
+ * Insert the initial row when an operation is created. Idempotent via
+ * `onConflictDoNothing` on the primary key so resumed operations don't
+ * blow up on the second createOperation call.
+ */
+ async recordStart(params: RecordOperationStartParams): Promise<void> {
+ const values: NewAgentOperation = {
+ agentId: params.agentId ?? null,
+ appContext: params.appContext,
+ chatGroupId: params.chatGroupId ?? null,
+ id: params.operationId,
+ maxSteps: params.maxSteps,
+ model: params.model,
+ modelRuntimeConfig: params.modelRuntimeConfig,
+ parentOperationId: params.parentOperationId ?? null,
+ provider: params.provider,
+ startedAt: params.startedAt ?? new Date(),
+ status: 'running',
+ taskId: params.taskId ?? null,
+ threadId: params.threadId ?? null,
+ topicId: params.topicId ?? null,
+ trigger: params.trigger,
+ userId: this.userId,
+ };
+
+ await this.db.insert(agentOperations).values(values).onConflictDoNothing();
+ }
+
+ /**
+ * Update the row when the operation reaches a terminal state. Scoped by
+ * `userId` so a leaked operationId can't be used to flip another user's
+ * row. No-op when the start row was never written.
+ */
+ async recordCompletion(
+ operationId: string,
+ params: RecordOperationCompletionParams,
+ ): Promise<void> {
+ const updates: Partial<NewAgentOperation> = {
+ completionReason: params.completionReason,
+ status: params.status,
+ };
+
+ // Only set completedAt when explicitly provided so callers can mark a
+ // non-terminal status (e.g. waiting_for_human) without falsely stamping
+ // completion time.
+ if (params.completedAt !== undefined) updates.completedAt = params.completedAt;
+ if (params.processingTimeMs !== undefined) updates.processingTimeMs = params.processingTimeMs;
+ if (params.stepCount !== undefined) updates.stepCount = params.stepCount;
+ if (params.totalCost !== undefined) updates.totalCost = params.totalCost;
+ if (params.totalTokens !== undefined) updates.totalTokens = params.totalTokens;
+ if (params.totalInputTokens !== undefined) updates.totalInputTokens = params.totalInputTokens;
+ if (params.totalOutputTokens !== undefined)
+ updates.totalOutputTokens = params.totalOutputTokens;
+ if (params.llmCalls !== undefined) updates.llmCalls = params.llmCalls;
+ if (params.toolCalls !== undefined) updates.toolCalls = params.toolCalls;
+ if (params.cost !== undefined) updates.cost = params.cost;
+ if (params.usage !== undefined) updates.usage = params.usage;
+ if (params.error !== undefined) updates.error = params.error;
+ if (params.interruption !== undefined) updates.interruption = params.interruption;
+ if (params.traceS3Key !== undefined) updates.traceS3Key = params.traceS3Key;
+
+ await this.db
+ .update(agentOperations)
+ .set(updates)
+ .where(and(eq(agentOperations.id, operationId), eq(agentOperations.userId, this.userId)));
+ }
+
+ async findById(operationId: string) {
+ const [row] = await this.db
+ .select()
+ .from(agentOperations)
+ .where(and(eq(agentOperations.id, operationId), eq(agentOperations.userId, this.userId)))
+ .limit(1);
+ return row ?? null;
+ }
+}
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 78e6dbffbe0..c7902c9d70f 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -65,6 +65,12 @@ export interface ExecAgentParams {
instructions?: string;
/** Override the agent's default model */
model?: string;
+ /**
+ * Parent operation ID when this run is a sub-agent invocation. Forwarded
+ * to `agent_operations.parent_operation_id` so analytics can join the
+ * sub-tree back to its root.
+ */
+ parentOperationId?: string;
/** The user input/prompt */
prompt: string;
/** Override the agent's default provider */
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index 12c97ae370e..1c2ebfa769d 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -188,7 +188,7 @@ export class AgentRuntimeService {
this.serverDB = db;
this.userId = userId;
this.messageModel = new MessageModel(db, this.userId);
- this.completionLifecycle = new CompletionLifecycle(db, userId, this.messageModel);
+ this.completionLifecycle = new CompletionLifecycle(db, userId);
this.humanIntervention = new HumanInterventionHandler(db, this.messageModel);
// Initialize ToolExecutionService with dependencies
@@ -277,11 +277,38 @@ export class AgentRuntimeService {
userMemory,
deviceSystemInfo,
operationSkillSet,
+ parentOperationId,
signal,
userTimezone,
initialStepCount = 0,
} = params;
+ // Persist initial agent_operations row. CompletionLifecycle owns both
+ // ends of the persistence lifecycle (start row here, terminal update
+ // in dispatchHooks) and swallows DB errors so runtime startup is never
+ // blocked.
+ await this.completionLifecycle.recordStart({
+ agentId: appContext?.agentId ?? null,
+ appContext: {
+ defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,
+ documentId: appContext?.documentId,
+ groupId: appContext?.groupId,
+ scope: appContext?.scope,
+ sourceMessageId: appContext?.sourceMessageId,
+ },
+ chatGroupId: appContext?.groupId ?? null,
+ maxSteps,
+ model: modelRuntimeConfig?.model,
+ modelRuntimeConfig,
+ operationId,
+ parentOperationId: parentOperationId ?? null,
+ provider: modelRuntimeConfig?.provider,
+ taskId: appContext?.taskId ?? null,
+ threadId: appContext?.threadId ?? null,
+ topicId: appContext?.topicId ?? null,
+ trigger: appContext?.trigger,
+ });
+
const operationToolSet = toolSet;
let operationCreated = false;
let hooksRegistered = false;
diff --git a/src/server/services/agentRuntime/CompletionLifecycle.ts b/src/server/services/agentRuntime/CompletionLifecycle.ts
index 0084cd97677..954a65464a4 100644
--- a/src/server/services/agentRuntime/CompletionLifecycle.ts
+++ b/src/server/services/agentRuntime/CompletionLifecycle.ts
@@ -1,6 +1,10 @@
import debug from 'debug';
-import type { MessageModel } from '@/database/models/message';
+import {
+ AgentOperationModel,
+ type RecordOperationStartParams,
+} from '@/database/models/agentOperation';
+import { MessageModel } from '@/database/models/message';
import { type LobeChatDatabase } from '@/database/type';
import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
@@ -34,11 +38,103 @@ const toAgentSignalSnapshotEvents = (
* always runs.
*/
export class CompletionLifecycle {
+ private readonly messageModel: MessageModel;
+ private readonly agentOperationModel: AgentOperationModel;
+
constructor(
private readonly serverDB: LobeChatDatabase,
private readonly userId: string,
- private readonly messageModel: MessageModel,
- ) {}
+ ) {
+ this.messageModel = new MessageModel(serverDB, userId);
+ this.agentOperationModel = new AgentOperationModel(serverDB, userId);
+ }
+
+ /**
+ * Persist the initial `agent_operations` row when an operation is created.
+ * Fire-and-forget: a DB outage here must never block the runtime startup
+ * path — `dispatchHooks` will still finalize the row if one was written.
+ */
+ async recordStart(params: RecordOperationStartParams): Promise<void> {
+ try {
+ await this.agentOperationModel.recordStart(params);
+ } catch (error) {
+ log('[%s] Failed to record operation start (non-fatal): %O', params.operationId, error);
+ }
+ }
+
+ /**
+ * Map a completion reason to the terminal `agent_operations.status` value.
+ * `waiting_for_human` keeps `status='waiting_for_human'` so analytics can
+ * distinguish paused ops from terminal ones.
+ */
+ private statusForReason(reason: string): 'done' | 'error' | 'interrupted' | 'waiting_for_human' {
+ switch (reason) {
+ case 'error': {
+ return 'error';
+ }
+ case 'interrupted': {
+ return 'interrupted';
+ }
+ case 'waiting_for_human': {
+ return 'waiting_for_human';
+ }
+ default: {
+ return 'done';
+ }
+ }
+ }
+
+ /**
+ * Persist terminal state to `agent_operations`. Fire-and-forget: a DB
+ * outage must never block hook dispatch or the executor's terminal
+ * cleanup path.
+ */
+ private async persistCompletion(operationId: string, state: any, reason: string): Promise<void> {
+ const completionReason: any =
+ reason === 'max_steps' || reason === 'cost_limit' || reason === 'waiting_for_human'
+ ? reason
+ : this.statusForReason(reason);
+
+ const metadata = state?.metadata ?? {};
+ const agentId = metadata?.agentId;
+ const topicId = metadata?.topicId;
+ const traceS3Key =
+ agentId && topicId ? `agent-traces/${agentId}/${topicId}/${operationId}.json` : null;
+
+ const processingTimeMs = state?.createdAt
+ ? Date.now() - new Date(state.createdAt).getTime()
+ : null;
+
+ const status = this.statusForReason(reason);
+ // `waiting_for_human` is a pause, not a true terminal state — leave
+ // completedAt null so analytics doesn't read a paused op as completed.
+ // The next dispatchHooks call (when the human resumes and the op truly
+ // ends) will overwrite both fields.
+ const completedAt = status === 'waiting_for_human' ? undefined : new Date();
+
+ try {
+ await this.agentOperationModel.recordCompletion(operationId, {
+ completedAt,
+ completionReason,
+ cost: state?.cost ?? null,
+ error: state?.error ?? null,
+ interruption: state?.interruption ?? null,
+ llmCalls: state?.usage?.llm?.apiCalls ?? null,
+ processingTimeMs,
+ status,
+ stepCount: state?.stepCount ?? null,
+ toolCalls: state?.usage?.tools?.totalCalls ?? null,
+ totalCost: state?.cost?.total ?? null,
+ totalInputTokens: state?.usage?.llm?.tokens?.input ?? null,
+ totalOutputTokens: state?.usage?.llm?.tokens?.output ?? null,
+ totalTokens: state?.usage?.llm?.tokens?.total ?? null,
+ traceS3Key,
+ usage: state?.usage ?? null,
+ });
+ } catch (error) {
+ log('[%s] Failed to persist operation completion (non-fatal): %O', operationId, error);
+ }
+ }
/**
* Extract a human-readable error message from the agent state error object.
@@ -140,6 +236,10 @@ export class CompletionLifecycle {
try {
const { event, metadata } = this.buildLifecycleEvent(operationId, state, reason);
+ // Finalize the agent_operations row before user hooks fire so
+ // downstream consumers see the row in its terminal shape.
+ await this.persistCompletion(operationId, state, reason);
+
await hookDispatcher.dispatch(operationId, 'onComplete', event, metadata._hooks);
if (reason === 'error') {
diff --git a/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index 6851a633f6d..af72016c72f 100644
--- a/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/src/server/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -3,8 +3,7 @@ import { describe, expect, it } from 'vitest';
import { CompletionLifecycle } from '../CompletionLifecycle';
-const buildLifecycle = () =>
- new CompletionLifecycle({} as any, 'user-1', { update: async () => undefined } as any);
+const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
describe('CompletionLifecycle.extractErrorMessage', () => {
it('extracts message from ChatCompletionErrorPayload (InsufficientBudgetForModel)', () => {
diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.ts
index 212b1acde71..c6f92599001 100644
--- a/src/server/services/agentRuntime/types.ts
+++ b/src/server/services/agentRuntime/types.ts
@@ -197,6 +197,13 @@ export interface OperationCreationParams {
operationId: string;
/** Operation-level skill set for SkillResolver */
operationSkillSet?: OperationSkillSet;
+ /**
+ * Operation ID of the parent run when this operation is a sub-agent
+ * invocation (e.g. spawned via `execSubAgentTask`). Persisted to
+ * `agent_operations.parent_operation_id` so analytics can join the
+ * sub-tree back to its root.
+ */
+ parentOperationId?: string;
queueRetries?: number;
queueRetryDelay?: string;
/** Abort startup before the first step is scheduled */
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 8a5a73fa29c..3f97c0a5804 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -322,6 +322,7 @@ export class AiAgentService {
queueRetries,
queueRetryDelay,
parentMessageId,
+ parentOperationId,
resume,
resumeApproval,
} = params;
@@ -1919,6 +1920,7 @@ export class AiAgentService {
modelRuntimeConfig: { model, provider },
hooks,
operationId,
+ parentOperationId,
signal,
queueRetries,
queueRetryDelay,
@@ -2154,6 +2156,7 @@ export class AiAgentService {
appContext: { groupId, threadId: thread.id, topicId },
autoStart: true,
hooks: threadHooks,
+ parentOperationId,
prompt: instruction,
userInterventionConfig: { approvalMode: 'headless' },
});