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(hetero): persist agent_operations + execution-trace snapshot for heterogeneous runs (#16237)

Arvin Xubaf4e7584b92
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 44f1724893e..bf7df777422 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -307,6 +307,7 @@ export class AiAgentService {
private readonly db: LobeChatDatabase;
private readonly agentDocumentsService: AgentDocumentsService;
private readonly agentModel: AgentModel;
+ private readonly agentOperationModel: AgentOperationModel;
private readonly agentService: AgentService;
private readonly messageModel: MessageModel;
private readonly connectorModel: ConnectorModel;
@@ -332,6 +333,7 @@ export class AiAgentService {
const wsId = this.workspaceId;
this.agentDocumentsService = new AgentDocumentsService(db, userId, wsId);
this.agentModel = new AgentModel(db, userId, wsId);
+ this.agentOperationModel = new AgentOperationModel(db, userId, wsId);
this.agentService = new AgentService(db, userId, wsId);
this.messageModel = new MessageModel(db, userId, wsId);
this.connectorModel = new ConnectorModel(db, userId, wsId);
@@ -425,6 +427,21 @@ 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',
+ error: { message, type: 'ServerAgentRuntimeError' },
+ status: 'error',
+ });
+ } catch (err) {
+ log('finalizeHeteroDispatchError: recordCompletion failed (non-fatal): %O', err);
+ }
+
// 2. Close the UI stream.
try {
await createStreamEventManager().publishAgentRuntimeEnd({
@@ -1329,6 +1346,31 @@ export class AiAgentService {
const isRemoteHetero = isRemoteHeterogeneousType(heteroType);
const operationId = nanoid();
+ // Persist a first-class agent_operations row for the hetero run. The id is
+ // generated here (authoritative) and flows through to heteroIngest /
+ // heteroFinish unchanged. Without this row the run is invisible to the
+ // operation lifecycle: verify (ensureForOperation), repair (parent chain),
+ // judge (op.model/provider) and tracing all key off it. Terminal state +
+ // the trace snapshot are written back in heteroFinish. Non-fatal: a
+ // tracing/op-row insert hiccup must never fail the user's run (verify just
+ // degrades to off for this run).
+ try {
+ await this.agentOperationModel.recordStart({
+ agentId: persistAgentId,
+ chatGroupId: appContext?.groupId ?? null,
+ maxSteps,
+ model,
+ operationId,
+ provider,
+ taskId: operationTaskId ?? null,
+ threadId: appContext?.threadId ?? null,
+ topicId,
+ trigger,
+ });
+ } catch (err) {
+ log('execAgent: hetero recordStart failed (non-fatal): %O', err);
+ }
+
// Read resume session id for next-turn continuity.
const heteroService = new HeterogeneousAgentService(this.db, this.userId, {
workspaceId: this.workspaceId,
@@ -3289,11 +3331,7 @@ export class AiAgentService {
// Inherit the supervisor op's trigger so member rows stay attributable.
let inheritedTrigger: string | undefined;
try {
- const parentOp = await new AgentOperationModel(
- this.db,
- this.userId,
- this.workspaceId,
- ).findById(parentOperationId);
+ const parentOp = await this.agentOperationModel.findById(parentOperationId);
inheritedTrigger = parentOp?.trigger ?? undefined;
} catch (error) {
log('execAgentMember: failed to read parent operation trigger: %O', error);
@@ -3445,11 +3483,7 @@ export class AiAgentService {
let inheritedTrigger: string | undefined;
if (parentOperationId) {
try {
- const parentOp = await new AgentOperationModel(
- this.db,
- this.userId,
- this.workspaceId,
- ).findById(parentOperationId);
+ const parentOp = await this.agentOperationModel.findById(parentOperationId);
inheritedTrigger = parentOp?.trigger ?? undefined;
} catch (error) {
log('%s: failed to read parent operation trigger: %O', options.logScope, error);
diff --git a/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts b/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts
new file mode 100644
index 00000000000..db9f6f38491
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/HeteroTraceRecorder.ts
@@ -0,0 +1,270 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import type { ExecutionSnapshot, ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';
+import debug from 'debug';
+
+import { buildFinalSnapshotKey } from '@/server/modules/AgentTracing';
+
+const log = debug('lobe-server:hetero-trace-recorder');
+
+export interface HeteroFinalizeParams {
+ agentId?: string | null;
+ completionReason: 'done' | 'error' | 'interrupted';
+ error?: { message: string; type: string };
+ topicId?: string | null;
+ userId?: string | null;
+}
+
+/** Roll-up returned by {@link HeteroTraceRecorder.finalize}, fed into the
+ * operation row's aggregate columns by `heteroFinish`. */
+export interface HeteroTraceTotals {
+ llmCalls: number;
+ stepCount: number;
+ toolCalls: number;
+ totalCost: number;
+ totalInputTokens: number;
+ totalOutputTokens: number;
+ totalTokens: number;
+ traceS3Key: string;
+}
+
+/** Authoritative run-level usage from Claude Code's final `result_usage` event,
+ * stashed on the partial so finalize prefers it over summing per-turn steps. */
+interface HeteroSessionUsage {
+ totalCost?: number;
+ totalInputTokens?: number;
+ totalOutputTokens?: number;
+ totalTokens?: number;
+}
+
+const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined);
+const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined);
+
+/**
+ * Hetero-native execution-trace recorder. Unlike the built-in
+ * {@link OperationTraceRecorder} β€” which is coupled to the homogeneous runtime's
+ * `AgentState` / `StepPresentationData` β€” this folds the raw `AgentStreamEvent`
+ * stream a heterogeneous CLI (Claude Code / Codex) emits into `StepSnapshot[]`,
+ * keyed by `stepIndex`, accumulating across ingest batches in the partial store
+ * and finalizing into the same `ExecutionSnapshot` S3 layout the built-in path
+ * uses. Context-engine fields are intentionally never set (hetero has no CE).
+ */
+export class HeteroTraceRecorder {
+ constructor(private readonly store: ISnapshotStore | null) {}
+
+ get enabled(): boolean {
+ return this.store !== null;
+ }
+
+ /** Fold a batch of events into per-stepIndex steps, accumulating into the
+ * partial snapshot. Best-effort: tracing must never break ingest. */
+ async appendBatch(operationId: string, events: AgentStreamEvent[]): Promise<void> {
+ if (!this.store || events.length === 0) return;
+
+ try {
+ const partial = (await this.store.loadPartial(operationId)) ?? {};
+ if (!partial.steps) partial.steps = [];
+ if (!partial.startedAt) partial.startedAt = events[0].timestamp;
+
+ const byIndex = new Map<number, StepSnapshot>();
+ for (const s of partial.steps) byIndex.set(s.stepIndex, s);
+
+ for (const event of events) this.applyEvent(partial, byIndex, event);
+
+ await this.store.savePartial(operationId, partial);
+ } catch (e) {
+ log('[%s] appendBatch failed (non-fatal): %O', operationId, e);
+ }
+ }
+
+ /** Assemble the final `ExecutionSnapshot` from the partial, persist it, and
+ * return the aggregate roll-up for the operation row. */
+ async finalize(
+ operationId: string,
+ params: HeteroFinalizeParams,
+ ): Promise<HeteroTraceTotals | null> {
+ if (!this.store) return null;
+
+ try {
+ const partial = await this.store.loadPartial(operationId);
+ if (!partial) return null;
+
+ const steps = (partial.steps ?? []).slice().sort((a, b) => a.stepIndex - b.stepIndex);
+
+ // Prefer the authoritative session totals (CC's final `result_usage`) over
+ // summing per-turn steps β€” summing double-counts (see applyEvent).
+ const session = (
+ partial as Partial<ExecutionSnapshot> & {
+ heteroSessionUsage?: HeteroSessionUsage;
+ }
+ ).heteroSessionUsage;
+ const totalTokens =
+ session?.totalTokens ?? steps.reduce((sum, s) => sum + (s.totalTokens || 0), 0);
+ const totalInputTokens =
+ session?.totalInputTokens ?? steps.reduce((sum, s) => sum + (s.inputTokens || 0), 0);
+ const totalOutputTokens =
+ session?.totalOutputTokens ?? steps.reduce((sum, s) => sum + (s.outputTokens || 0), 0);
+ const totalCost = session?.totalCost ?? steps.reduce((sum, s) => sum + (s.totalCost || 0), 0);
+
+ const agentId = params.agentId ?? undefined;
+ const topicId = params.topicId ?? undefined;
+
+ const snapshot: ExecutionSnapshot = {
+ agentId,
+ completedAt: Date.now(),
+ completionReason: params.completionReason,
+ error: params.error,
+ model: partial.model,
+ operationId,
+ provider: partial.provider,
+ startedAt: partial.startedAt ?? Date.now(),
+ steps,
+ topicId,
+ totalCost,
+ totalSteps: steps.length,
+ totalTokens,
+ traceId: operationId,
+ userId: params.userId ?? undefined,
+ };
+
+ await this.store.save(snapshot);
+ await this.store.removePartial(operationId);
+
+ return {
+ llmCalls: steps.filter((s) => s.stepType === 'call_llm').length,
+ stepCount: steps.length,
+ toolCalls: steps.filter((s) => s.stepType === 'call_tool').length,
+ totalCost,
+ totalInputTokens,
+ totalOutputTokens,
+ totalTokens,
+ traceS3Key: buildFinalSnapshotKey(agentId ?? 'unknown', topicId ?? 'unknown', operationId),
+ };
+ } catch (e) {
+ log('[%s] finalize failed (non-fatal): %O', operationId, e);
+ return null;
+ }
+ }
+
+ private applyEvent(
+ partial: Partial<ExecutionSnapshot>,
+ byIndex: Map<number, StepSnapshot>,
+ event: AgentStreamEvent,
+ ): void {
+ const data = (event.data ?? {}) as Record<string, any>;
+
+ // Header: capture model / provider from the first event that carries them
+ // (stream_start, step_complete). Mirrors initPartialHeader in the built-in
+ // recorder so the trace + S3 key resolve to the right model.
+ if (!partial.model) partial.model = str(data.model);
+ if (!partial.provider) partial.provider = str(data.provider);
+
+ let step = byIndex.get(event.stepIndex);
+ if (!step) {
+ step = {
+ completedAt: event.timestamp,
+ executionTimeMs: 0,
+ startedAt: event.timestamp,
+ stepIndex: event.stepIndex,
+ stepType: 'call_llm',
+ totalCost: 0,
+ totalTokens: 0,
+ };
+ byIndex.set(event.stepIndex, step);
+ partial.steps!.push(step);
+ }
+
+ step.startedAt = Math.min(step.startedAt, event.timestamp);
+ step.completedAt = Math.max(step.completedAt, event.timestamp);
+ step.executionTimeMs = step.completedAt - step.startedAt;
+
+ switch (event.type) {
+ case 'stream_chunk': {
+ if (data.chunkType === 'text' && typeof data.content === 'string') {
+ step.content = (step.content ?? '') + data.content;
+ } else if (data.chunkType === 'reasoning' && typeof data.reasoning === 'string') {
+ step.reasoning = (step.reasoning ?? '') + data.reasoning;
+ } else if (data.chunkType === 'tools_calling' && Array.isArray(data.toolsCalling)) {
+ step.stepType = 'call_tool';
+ step.toolsCalling = data.toolsCalling.map((t: any) => ({
+ apiName: str(t?.apiName) ?? '',
+ arguments: str(t?.arguments),
+ identifier: str(t?.identifier) ?? str(t?.id) ?? '',
+ }));
+ }
+ break;
+ }
+ case 'tool_start':
+ case 'tool_execute': {
+ step.stepType = 'call_tool';
+ break;
+ }
+ case 'tool_end': {
+ step.stepType = 'call_tool';
+ const tool = (data.toolCalling ?? {}) as Record<string, unknown>;
+ step.toolsResult = [
+ ...(step.toolsResult ?? []),
+ {
+ apiName: str(tool.apiName) ?? '',
+ identifier: str(tool.identifier) ?? str(data.toolCallId) ?? '',
+ isSuccess: typeof data.isSuccess === 'boolean' ? data.isSuccess : undefined,
+ output: str(data.result),
+ },
+ ];
+ break;
+ }
+ case 'tool_result': {
+ step.stepType = 'call_tool';
+ step.toolsResult = [
+ ...(step.toolsResult ?? []),
+ {
+ apiName: '',
+ identifier: str(data.toolCallId) ?? '',
+ isSuccess: data.isError ? false : true,
+ output: str(data.content),
+ },
+ ];
+ break;
+ }
+ case 'step_complete': {
+ const usage = data.usage as Record<string, unknown> | undefined;
+ const inT = usage ? num(usage.totalInputTokens) : undefined;
+ const outT = usage ? num(usage.totalOutputTokens) : undefined;
+ const tot = usage ? num(usage.totalTokens) : undefined;
+ const cost = num(data.costUsd);
+
+ // Claude Code emits one `turn_metadata` per turn (incremental usage) and
+ // a single final `result_usage` carrying the authoritative SESSION
+ // totals. Folding `result_usage` onto a step then summing steps at
+ // finalize double-counts (per-turn turns + the grand total). So route
+ // `result_usage` to a run-level field and only fold turn_metadata steps.
+ if (data.phase === 'result_usage') {
+ const target = partial as Partial<ExecutionSnapshot> & {
+ heteroSessionUsage?: HeteroSessionUsage;
+ };
+ target.heteroSessionUsage = {
+ totalCost: cost ?? target.heteroSessionUsage?.totalCost,
+ totalInputTokens: inT ?? target.heteroSessionUsage?.totalInputTokens,
+ totalOutputTokens: outT ?? target.heteroSessionUsage?.totalOutputTokens,
+ totalTokens:
+ tot ??
+ (inT !== undefined || outT !== undefined
+ ? (inT ?? 0) + (outT ?? 0)
+ : target.heteroSessionUsage?.totalTokens),
+ };
+ break;
+ }
+
+ if (inT !== undefined) step.inputTokens = inT;
+ if (outT !== undefined) step.outputTokens = outT;
+ if (tot !== undefined) step.totalTokens = tot;
+ else if (inT !== undefined || outT !== undefined)
+ step.totalTokens = (inT ?? 0) + (outT ?? 0);
+ if (cost !== undefined) step.totalCost = cost;
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ }
+}
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts
new file mode 100644
index 00000000000..28e69ff9e0e
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeteroTraceRecorder.test.ts
@@ -0,0 +1,168 @@
+import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import type { ExecutionSnapshot, ISnapshotStore } from '@lobechat/agent-tracing';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { HeteroTraceRecorder } from '../HeteroTraceRecorder';
+
+/** Minimal in-memory snapshot store for folding assertions. */
+class FakeSnapshotStore implements ISnapshotStore {
+ partials = new Map<string, Partial<ExecutionSnapshot>>();
+ saved = new Map<string, ExecutionSnapshot>();
+
+ async loadPartial(operationId: string) {
+ const p = this.partials.get(operationId);
+ // return a deep clone so the recorder mutating the loaded object doesn't
+ // accidentally short-circuit the persist round-trip we want to exercise.
+ return p ? (JSON.parse(JSON.stringify(p)) as Partial<ExecutionSnapshot>) : null;
+ }
+ async savePartial(operationId: string, partial: Partial<ExecutionSnapshot>) {
+ this.partials.set(operationId, partial);
+ }
+ async removePartial(operationId: string) {
+ this.partials.delete(operationId);
+ }
+ async save(snapshot: ExecutionSnapshot) {
+ this.saved.set(snapshot.operationId, snapshot);
+ }
+ async get() {
+ return null;
+ }
+ async getLatest() {
+ return null;
+ }
+ async list() {
+ return [];
+ }
+ async listPartials() {
+ return [...this.partials.keys()];
+ }
+}
+
+const ev = (
+ type: AgentStreamEvent['type'],
+ stepIndex: number,
+ timestamp: number,
+ data: Record<string, unknown>,
+): AgentStreamEvent => ({ data, operationId: 'op-1', stepIndex, timestamp, type });
+
+describe('HeteroTraceRecorder', () => {
+ let store: FakeSnapshotStore;
+ let recorder: HeteroTraceRecorder;
+
+ beforeEach(() => {
+ store = new FakeSnapshotStore();
+ recorder = new HeteroTraceRecorder(store);
+ });
+
+ it('is disabled and no-ops when the store is null', async () => {
+ const disabled = new HeteroTraceRecorder(null);
+ expect(disabled.enabled).toBe(false);
+ await disabled.appendBatch('op-1', [
+ ev('stream_chunk', 0, 1, { chunkType: 'text', content: 'x' }),
+ ]);
+ expect(await disabled.finalize('op-1', { completionReason: 'done' })).toBeNull();
+ });
+
+ it('folds events into per-stepIndex steps and finalizes an ExecutionSnapshot', async () => {
+ // Batch 1: header + step 0 text + a tool call
+ await recorder.appendBatch('op-1', [
+ ev('stream_start', 0, 100, {
+ assistantMessage: { id: 'm' },
+ model: 'sonnet',
+ provider: 'anthropic',
+ }),
+ ev('stream_chunk', 0, 110, { chunkType: 'text', content: 'Hello ' }),
+ ev('stream_chunk', 0, 120, { chunkType: 'reasoning', reasoning: 'think' }),
+ ev('stream_chunk', 0, 130, {
+ chunkType: 'tools_calling',
+ toolsCalling: [{ apiName: 'Bash', arguments: '{"cmd":"ls"}', identifier: 'claude-code' }],
+ }),
+ ]);
+ // Batch 2: step 0 tool_end + usage, then a pure-text step 1 (accumulates across batches)
+ await recorder.appendBatch('op-1', [
+ ev('tool_end', 0, 140, {
+ isSuccess: true,
+ toolCalling: { apiName: 'Bash', identifier: 'claude-code' },
+ }),
+ ev('step_complete', 0, 150, {
+ phase: 'turn_metadata',
+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },
+ }),
+ ev('stream_chunk', 1, 200, { chunkType: 'text', content: 'done' }),
+ ev('step_complete', 1, 205, { phase: 'turn_metadata', usage: { totalTokens: 8 } }),
+ // Final result_usage carries the authoritative SESSION total (25) β€” which
+ // is deliberately NOT the sum of the per-turn steps (15 + 8 = 23), proving
+ // finalize prefers it and does not double-count.
+ ev('step_complete', 1, 210, {
+ costUsd: 0.002,
+ phase: 'result_usage',
+ usage: { totalInputTokens: 12, totalOutputTokens: 13, totalTokens: 25 },
+ }),
+ ]);
+
+ const totals = await recorder.finalize('op-1', {
+ agentId: 'agent-1',
+ completionReason: 'done',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ expect(totals).toMatchObject({
+ llmCalls: 1,
+ stepCount: 2,
+ toolCalls: 1,
+ totalInputTokens: 12,
+ totalOutputTokens: 13,
+ totalTokens: 25, // session total, not the 23 step sum
+ });
+ expect(totals!.totalCost).toBeCloseTo(0.002);
+ expect(totals!.traceS3Key).toBe('agent-traces/agent-1/topic-1/op-1.json.zst');
+
+ const snap = store.saved.get('op-1')!;
+ expect(snap).toBeDefined();
+ expect(snap).toMatchObject({
+ agentId: 'agent-1',
+ completionReason: 'done',
+ model: 'sonnet',
+ operationId: 'op-1',
+ provider: 'anthropic',
+ topicId: 'topic-1',
+ totalSteps: 2,
+ totalTokens: 25, // session total
+ traceId: 'op-1',
+ userId: 'user-1',
+ });
+ expect(snap.totalCost).toBeCloseTo(0.002);
+
+ const [step0, step1] = snap.steps;
+ expect(step0.stepIndex).toBe(0);
+ expect(step0.stepType).toBe('call_tool'); // had a tool call
+ expect(step0.content).toBe('Hello ');
+ expect(step0.reasoning).toBe('think');
+ expect(step0.toolsCalling).toEqual([
+ { apiName: 'Bash', arguments: '{"cmd":"ls"}', identifier: 'claude-code' },
+ ]);
+ expect(step0.toolsResult?.[0]).toMatchObject({ apiName: 'Bash', isSuccess: true });
+ expect(step0.inputTokens).toBe(10);
+ expect(step0.outputTokens).toBe(5);
+ expect(step0.totalTokens).toBe(15);
+ expect(step0.executionTimeMs).toBe(50); // 150 - 100
+
+ expect(step1.stepIndex).toBe(1);
+ expect(step1.stepType).toBe('call_llm'); // pure text
+ expect(step1.content).toBe('done');
+ expect(step1.totalTokens).toBe(8); // its own turn_metadata, NOT the session total
+ expect(step1.totalCost).toBe(0); // result_usage cost is a session total, not folded per-step
+
+ // context-engine is never populated for hetero steps
+ expect(step0.contextEngine).toBeUndefined();
+ expect(step1.contextEngine).toBeUndefined();
+
+ // partial cleaned up after finalize
+ expect(store.partials.has('op-1')).toBe(false);
+ });
+
+ it('returns null from finalize when no partial was accumulated', async () => {
+ expect(await recorder.finalize('never-seen', { completionReason: 'done' })).toBeNull();
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index 7994e6e1551..9728657c6f4 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -1,7 +1,9 @@
import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';
+import type { ISnapshotStore } from '@lobechat/agent-tracing';
import type { LobeChatDatabase } from '@lobechat/database';
import debug from 'debug';
+import { AgentOperationModel } from '@/database/models/agentOperation';
import { MessageModel } from '@/database/models/message';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
@@ -9,11 +11,13 @@ import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory'
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
import { dispatchTerminalHooks } from '@/server/services/agentRuntime/hooks';
import type { SerializedHook } from '@/server/services/agentRuntime/hooks/types';
+import { createDefaultSnapshotStore } from '@/server/services/agentRuntime/snapshotStore';
import {
HeterogeneousPersistenceHandler,
StaleHeteroOperationError,
} from './HeterogeneousPersistenceHandler';
+import { HeteroTraceRecorder } from './HeteroTraceRecorder';
const log = debug('lobe-server:hetero-agent-service');
@@ -49,6 +53,8 @@ export interface HeterogeneousFinishParams {
export interface HeterogeneousAgentServiceOptions {
/** Inject a pre-built persistence handler (used by tests). */
persistenceHandler?: HeterogeneousPersistenceHandler;
+ /** Inject a snapshot store (used by tests); defaults to the env-resolved store. */
+ snapshotStore?: ISnapshotStore | null;
/** Inject a pre-built manager (used by tests). */
streamEventManager?: IStreamEventManager;
/** Inject a pre-built TopicModel (used by tests for the resume helper). */
@@ -74,9 +80,11 @@ export interface HeterogeneousAgentServiceOptions {
export class HeterogeneousAgentService {
private readonly db: LobeChatDatabase;
private readonly messageModel: MessageModel;
+ private readonly operationModel: AgentOperationModel;
private readonly persistenceHandler: HeterogeneousPersistenceHandler;
private readonly streamEventManager: IStreamEventManager;
private readonly topicModel: TopicModel;
+ private readonly traceRecorder: HeteroTraceRecorder;
private readonly userId: string;
constructor(
@@ -88,8 +96,12 @@ export class HeterogeneousAgentService {
this.userId = userId;
const workspaceId = options.workspaceId;
this.messageModel = new MessageModel(db, userId, workspaceId);
+ this.operationModel = new AgentOperationModel(db, userId, workspaceId);
this.streamEventManager = options.streamEventManager ?? createStreamEventManager();
this.topicModel = options.topicModel ?? new TopicModel(db, userId, workspaceId);
+ this.traceRecorder = new HeteroTraceRecorder(
+ options.snapshotStore !== undefined ? options.snapshotStore : createDefaultSnapshotStore(),
+ );
this.persistenceHandler =
options.persistenceHandler ??
new HeterogeneousPersistenceHandler({
@@ -144,6 +156,14 @@ export class HeterogeneousAgentService {
type: event.type,
});
}
+
+ // Accumulate the execution-trace snapshot LAST. The recorder has no
+ // per-event idempotency, so it must run only after every step that can throw
+ // and trigger a BatchIngester retry of this same batch β€” otherwise a publish
+ // failure above would re-fold these events and double-count the snapshot.
+ // It's the final statement and best-effort (never throws), so it folds each
+ // batch exactly once (on the attempt that gets this far).
+ await this.traceRecorder.appendBatch(operationId, events);
}
async heteroFinish(params: HeterogeneousFinishParams): Promise<void> {
@@ -231,6 +251,39 @@ export class HeterogeneousAgentService {
}
}
+ // Finalize the trace snapshot + write the operation's terminal state. Runs
+ // on the real terminal only (cancelled returned above), so a run gets one
+ // snapshot + one completion. Aggregates come from the accumulated steps;
+ // missing fields stay null (schema treats null as "not measured"). This
+ // makes the hetero run a verify/tracing peer of the built-in agent.
+ // `result` is narrowed to 'success' | 'error' here β€” 'cancelled' returned above.
+ const completionReason = result === 'success' ? ('done' as const) : ('error' as const);
+ try {
+ const totals = await this.traceRecorder.finalize(operationId, {
+ agentId,
+ completionReason,
+ error,
+ topicId,
+ userId: this.userId,
+ });
+ await this.operationModel.recordCompletion(operationId, {
+ completedAt: new Date(),
+ completionReason,
+ error: error ?? null,
+ llmCalls: totals?.llmCalls ?? null,
+ status: completionReason,
+ stepCount: totals?.stepCount ?? null,
+ toolCalls: totals?.toolCalls ?? null,
+ totalCost: totals?.totalCost ?? null,
+ totalInputTokens: totals?.totalInputTokens ?? null,
+ totalOutputTokens: totals?.totalOutputTokens ?? null,
+ totalTokens: totals?.totalTokens ?? null,
+ traceS3Key: totals?.traceS3Key ?? null,
+ });
+ } catch (err) {
+ log('heteroFinish: recordCompletion/finalize failed (non-fatal): %O', err);
+ }
+
await dispatchTerminalHooks({
agentId,
...(error ? { errorMessage: error.message, errorType: error.type } : {}),