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(cli): record local hetero agent runs as execution snapshots (#18874)

Arvin Xuedbcbe32332e
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index c4809c754dc..704d6f40885 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -70,6 +70,7 @@ import {
import { executeToolCall } from '../tools';
import { cleanupAllProcesses } from '../tools/shell';
import { log, setVerbose } from '../utils/logger';
+import { sweepLocalTraces } from '../utils/traceMaintenance';
const CONNECT_SERVICE_NAME = CLI_CONNECT_SERVICE_NAME;
@@ -423,6 +424,16 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
const startedAt = new Date();
updateStatus('connecting');
+ // Housekeeping for the local trace store: partials left behind by killed
+ // agent processes become `interrupted` snapshots (so `lh trace op list` shows
+ // the crashed runs), and aged-out snapshots are deleted. Fire-and-forget β€”
+ // it must never delay the gateway connection.
+ void sweepLocalTraces().then(({ deleted, reconciled }) => {
+ if (reconciled > 0 || deleted > 0) {
+ info(` Traces : ${reconciled} interrupted run(s) closed, ${deleted} expired removed`);
+ }
+ });
+
// Platform handlers for the shared `@lobechat/device-control` dispatcher.
// File preview / index use the package's portable defaults (no
// preview-protocol approval on the CLI). Deliberately mutable: the
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 9a92f15e87c..15ca346677c 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -31,8 +31,10 @@ import type { Command } from 'commander';
import { getTrpcClient } from '../api/client';
import { CoalescingBatchIngester } from '../utils/CoalescingBatchIngester';
+import { HeteroTraceRecorder } from '../utils/HeteroTraceRecorder';
import { log } from '../utils/logger';
import { createOperationHeartbeat } from '../utils/OperationHeartbeat';
+import { createLocalTraceStore } from '../utils/traceStore';
import { TrpcIngestSink } from '../utils/TrpcIngestSink';
export const SUPPORTED_AGENT_TYPES = new Set<string>(LOCAL_HETEROGENEOUS_AGENT_TYPES);
@@ -421,6 +423,18 @@ const exec = async (options: ExecOptions): Promise<void> => {
});
}
+ // Local execution trace. Recorded for EVERY run, not just server-ingest ones:
+ // a standalone `lh hetero exec` is exactly the case where nothing else keeps
+ // a record of what the agent did, and it is the same snapshot format a native
+ // agent run produces, so `lh trace op inspect` reads both.
+ const traceRecorder = new HeteroTraceRecorder({
+ agentType: options.type,
+ operationId,
+ onError: (message) => log.warn(`Trace: ${message}`),
+ store: createLocalTraceStore(),
+ topicId: options.topic,
+ });
+
// Determine JSONL output mode.
// Explicit --render flag always wins. Otherwise: emit JSONL in standalone
// mode; suppress in server-ingest mode (sink handles the data path).
@@ -666,6 +680,10 @@ const exec = async (options: ExecOptions): Promise<void> => {
? err.code
: undefined;
log.error('Failed to start agent:', message);
+ await traceRecorder.finalize({
+ error: buildFinishError(message, 'AgentRuntimeError', errnoCode),
+ result: 'error',
+ });
if (serverIngester && sink) {
try {
await serverIngester.drain();
@@ -738,7 +756,10 @@ const exec = async (options: ExecOptions): Promise<void> => {
resumeNotFound = true;
// Emit to JSONL for observability but do NOT push to ingester β€”
// we are about to retry; the server must not see a terminal error.
+ // The local trace still records it: "attempt 1 could not resume" is
+ // the whole reason someone reads the trace back.
if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
+ traceRecorder.observe(event);
continue;
}
}
@@ -759,6 +780,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
}
if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
operationHeartbeat?.observe(event);
+ traceRecorder.observe(event);
serverIngester?.push(event);
}
} catch (err) {
@@ -766,6 +788,14 @@ const exec = async (options: ExecOptions): Promise<void> => {
'Stream error from agent process:',
err instanceof Error ? err.message : String(err),
);
+ await traceRecorder.finalize({
+ error: buildFinishError(
+ String(err),
+ 'stream_error',
+ (err as NodeJS.ErrnoException | null)?.code,
+ ),
+ result: 'error',
+ });
if (serverIngester && sink) {
try {
await serverIngester.drain();
@@ -911,46 +941,56 @@ const exec = async (options: ExecOptions): Promise<void> => {
);
result = { ...result, ingestError: true };
}
+ }
+
+ // CC relays API/rate-limit errors as an in-stream terminal `error` event but
+ // still exits 0, so the exit code alone would report `success`. Treat any
+ // pushed terminal error as a failed run so the topic/task is marked failed.
+ const exitedClean =
+ !result.cancelled &&
+ !result.ingestError &&
+ !result.sawTerminalError &&
+ (code === 0 || signal === 'SIGTERM');
- // CC relays API/rate-limit errors as an in-stream terminal `error` event but
- // still exits 0, so the exit code alone would report `success`. Treat any
- // pushed terminal error as a failed run so the topic/task is marked failed.
- const exitedClean =
- !result.cancelled &&
- !result.ingestError &&
- !result.sawTerminalError &&
- (code === 0 || signal === 'SIGTERM');
-
- // When the run failed, pass an error detail so the server surfaces a useful
- // message instead of the generic "Agent execution failed" fallback. Prefer
- // the in-stream terminal error (CC relays API/rate-limit errors here while
- // exiting 0, so stderr is empty); otherwise fall back to the stderr tail.
- // Trim to the last 1 KB β€” the tail is most informative and keeps the tRPC
- // payload small.
- const stderrTail = result.stderrContent.trim();
- const errorDetail = result.terminalErrorMessage || stderrTail;
- // The adapter's in-stream classification (overloaded / rate_limit) already
- // carries the structured status-guide body β€” forward it verbatim instead of
- // re-deriving from the flattened message via the process-only classifier,
- // which would drop `agentType`/`code` and demote the client UI to the
- // generic error card.
- const finishError =
- result.cancelled || exitedClean
- ? undefined
- : result.terminalErrorData
- ? {
- body: { ...result.terminalErrorData },
- message: String(result.terminalErrorData.message ?? errorDetail ?? ''),
- type: 'AgentRuntimeError',
- }
- : errorDetail
- ? buildFinishError(errorDetail.slice(-1024), 'AgentRuntimeError')
- : undefined;
+ // When the run failed, pass an error detail so the server surfaces a useful
+ // message instead of the generic "Agent execution failed" fallback. Prefer
+ // the in-stream terminal error (CC relays API/rate-limit errors here while
+ // exiting 0, so stderr is empty); otherwise fall back to the stderr tail.
+ // Trim to the last 1 KB β€” the tail is most informative and keeps the tRPC
+ // payload small.
+ const stderrTail = result.stderrContent.trim();
+ const errorDetail = result.terminalErrorMessage || stderrTail;
+ // The adapter's in-stream classification (overloaded / rate_limit) already
+ // carries the structured status-guide body β€” forward it verbatim instead of
+ // re-deriving from the flattened message via the process-only classifier,
+ // which would drop `agentType`/`code` and demote the client UI to the
+ // generic error card.
+ const finishError =
+ result.cancelled || exitedClean
+ ? undefined
+ : result.terminalErrorData
+ ? {
+ body: { ...result.terminalErrorData },
+ message: String(result.terminalErrorData.message ?? errorDetail ?? ''),
+ type: 'AgentRuntimeError',
+ }
+ : errorDetail
+ ? buildFinishError(errorDetail.slice(-1024), 'AgentRuntimeError')
+ : undefined;
+
+ const runResult = result.cancelled ? 'cancelled' : exitedClean ? 'success' : 'error';
+ // Close the local trace for EVERY run β€” the outcome is derived above from the
+ // same signals the server finish uses, so a standalone run records the same
+ // completion reason a server-ingest one does. Runs before the sink so a
+ // failing server call still leaves a complete snapshot on disk.
+ await traceRecorder.finalize({ error: finishError, result: runResult });
+
+ if (serverIngester && sink) {
try {
await sink.finish({
error: finishError,
- result: result.cancelled ? 'cancelled' : exitedClean ? 'success' : 'error',
+ result: runResult,
sessionId,
});
} catch (err) {
diff --git a/apps/cli/src/commands/trace/op/list.ts b/apps/cli/src/commands/trace/op/list.ts
index c0ddd47ec78..e86cff371a9 100644
--- a/apps/cli/src/commands/trace/op/list.ts
+++ b/apps/cli/src/commands/trace/op/list.ts
@@ -1,4 +1,8 @@
-import { FileSnapshotStore, renderSummaryTable } from '@lobechat/agent-tracing';
+import {
+ FileSnapshotStore,
+ renderSummaryTable,
+ type SnapshotSummary,
+} from '@lobechat/agent-tracing';
import type { Command } from 'commander';
import { InvalidArgumentError } from 'commander';
import pc from 'picocolors';
@@ -6,6 +10,7 @@ import pc from 'picocolors';
import { getTrpcClient } from '../../../api/client';
import { printTable, timeAgo } from '../../../utils/format';
import { log } from '../../../utils/logger';
+import { createLocalTraceStore } from '../../../utils/traceStore';
const DEFAULT_LIMIT = 10;
@@ -58,6 +63,13 @@ const listByTopic = async (topicId: string, limit: number, json?: boolean) => {
);
};
+const dedupeByTraceId = (summaries: SnapshotSummary[]): SnapshotSummary[] => {
+ const seen = new Map<string, SnapshotSummary>();
+ for (const summary of summaries)
+ if (!seen.has(summary.traceId)) seen.set(summary.traceId, summary);
+ return [...seen.values()];
+};
+
export function registerOpListCommand(parent: Command) {
parent
.command('list')
@@ -78,7 +90,18 @@ export function registerOpListCommand(parent: Command) {
return;
}
- const summaries = await new FileSnapshotStore().list({ limit });
+ // Two local stores, because two different producers write them: a
+ // dev-mode server drops snapshots in `./.agent-tracing`, while locally
+ // executed agent runs record to the CLI home. Listing only one of them
+ // silently hides half the traces on a developer's machine.
+ const [cwdSnapshots, cliHomeSnapshots] = await Promise.all([
+ new FileSnapshotStore().list({ limit }),
+ createLocalTraceStore().list({ limit }),
+ ]);
+
+ const summaries = dedupeByTraceId([...cwdSnapshots, ...cliHomeSnapshots])
+ .sort((a, b) => b.createdAt - a.createdAt)
+ .slice(0, limit);
console.log(opts.json ? JSON.stringify(summaries, null, 2) : renderSummaryTable(summaries));
});
diff --git a/apps/cli/src/commands/trace/op/snapshot.test.ts b/apps/cli/src/commands/trace/op/snapshot.test.ts
new file mode 100644
index 00000000000..b2f14a0d214
--- /dev/null
+++ b/apps/cli/src/commands/trace/op/snapshot.test.ts
@@ -0,0 +1,84 @@
+import { type ExecutionSnapshot, FileSnapshotStore } from '@lobechat/agent-tracing';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { loadLocalSnapshot } from './snapshot';
+
+let root: string;
+let cliHome: { dirName: string; rootDir: string };
+let cwd: { dirName: string; rootDir: string };
+
+const snapshot = (traceId: string, startedAt: number): ExecutionSnapshot => ({
+ operationId: traceId,
+ startedAt,
+ steps: [],
+ totalCost: 0,
+ totalSteps: 0,
+ totalTokens: 0,
+ traceId,
+});
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'trace-resolve-'));
+ cliHome = { dirName: 'traces', rootDir: path.join(root, 'home') };
+ cwd = { dirName: '.agent-tracing', rootDir: path.join(root, 'repo') };
+});
+
+afterEach(async () => {
+ await fs.rm(root, { force: true, recursive: true });
+});
+
+const write = async (
+ store: { dirName: string; rootDir: string },
+ traceId: string,
+ startedAt: number,
+) => new FileSnapshotStore(store.rootDir, store.dirName).save(snapshot(traceId, startedAt));
+
+describe('loadLocalSnapshot', () => {
+ it('picks the newest run across both stores for the default target', async () => {
+ await write(cliHome, 'trace_hetero_old', 1_000);
+ await write(cwd, 'trace_server_new', 9_000);
+
+ // The dev-mode server's store holds the newer run β€” resolving `latest` from
+ // the CLI home alone would inspect the stale one while `lh trace op list`
+ // shows the newer one first.
+ const resolved = await loadLocalSnapshot(undefined, { cliHome, cwd });
+ expect(resolved?.traceId).toBe('trace_server_new');
+ });
+
+ it('picks the CLI-home run when it is the newer of the two', async () => {
+ await write(cliHome, 'trace_hetero_new', 9_000);
+ await write(cwd, 'trace_server_old', 1_000);
+
+ expect((await loadLocalSnapshot('latest', { cliHome, cwd }))?.traceId).toBe(
+ 'trace_hetero_new',
+ );
+ });
+
+ it('falls back to whichever store has anything at all', async () => {
+ await write(cwd, 'trace_only', 1_000);
+ expect((await loadLocalSnapshot(undefined, { cliHome, cwd }))?.traceId).toBe('trace_only');
+
+ await fs.rm(path.join(cwd.rootDir), { force: true, recursive: true });
+ await write(cliHome, 'trace_other', 2_000);
+ expect((await loadLocalSnapshot(undefined, { cliHome, cwd }))?.traceId).toBe('trace_other');
+ });
+
+ it('resolves an explicit id from either store', async () => {
+ await write(cliHome, 'trace_in_home', 1_000);
+ await write(cwd, 'trace_in_cwd', 9_000);
+
+ expect((await loadLocalSnapshot('trace_in_home', { cliHome, cwd }))?.traceId).toBe(
+ 'trace_in_home',
+ );
+ expect((await loadLocalSnapshot('trace_in_cwd', { cliHome, cwd }))?.traceId).toBe(
+ 'trace_in_cwd',
+ );
+ });
+
+ it('returns undefined when neither store has anything', async () => {
+ expect(await loadLocalSnapshot(undefined, { cliHome, cwd })).toBeUndefined();
+ });
+});
diff --git a/apps/cli/src/commands/trace/op/snapshot.ts b/apps/cli/src/commands/trace/op/snapshot.ts
index 1072f302206..8c7356c9a5a 100644
--- a/apps/cli/src/commands/trace/op/snapshot.ts
+++ b/apps/cli/src/commands/trace/op/snapshot.ts
@@ -2,12 +2,53 @@ import {
AmbiguousSnapshotIdError,
type ExecutionSnapshot,
loadSnapshot,
+ type LoadSnapshotOptions,
MissingTracingBaseUrlError,
} from '@lobechat/agent-tracing';
import { TRPCClientError } from '@trpc/client';
import { getTrpcClient } from '../../../api/client';
import { log } from '../../../utils/logger';
+import { localTraceStoreOptions } from '../../../utils/traceStore';
+
+/** Store locations `lh trace op` reads, in the order a tie is broken. */
+export interface LocalSnapshotStores {
+ /** `~/.lobehub/traces` β€” where locally executed agent runs record. */
+ cliHome?: LoadSnapshotOptions;
+ /** `.agent-tracing` under the cwd β€” where a dev-mode server writes. */
+ cwd?: LoadSnapshotOptions;
+}
+
+/**
+ * Load a snapshot from either local store.
+ *
+ * Two stores exist because two producers write them, and for the default
+ * target (`latest`) they have to be COMPARED rather than tried in order: each
+ * store answers `latest` with its own newest entry, so probing one first would
+ * inspect a stale run whenever the other store holds something newer β€” while
+ * `lh trace op list`, which merges and sorts both, correctly shows the newer
+ * one first. An explicit id needs no comparison: at most one store has it.
+ */
+export const loadLocalSnapshot = async (
+ target?: string,
+ stores: LocalSnapshotStores = {},
+): Promise<ExecutionSnapshot | undefined> => {
+ const cliHome = stores.cliHome ?? localTraceStoreOptions();
+ const cwd = stores.cwd ?? {};
+
+ const isLatest = !target || target === 'latest';
+ if (!isLatest) return (await loadSnapshot(target, cliHome)) ?? (await loadSnapshot(target, cwd));
+
+ const [fromCliHome, fromCwd] = await Promise.all([
+ loadSnapshot(target, cliHome),
+ loadSnapshot(target, cwd),
+ ]);
+
+ if (!fromCliHome) return fromCwd;
+ if (!fromCwd) return fromCliHome;
+
+ return fromCwd.startedAt > fromCliHome.startedAt ? fromCwd : fromCliHome;
+};
/**
* Resolve the snapshot a `lh trace op` subcommand was pointed at, or exit with
@@ -44,6 +85,13 @@ export const resolveSnapshotOrExit = async (target?: string): Promise<ExecutionS
};
try {
+ // Locally executed runs (`lh hetero exec`) record to the CLI home, so probe
+ // it before anything that can reach the network β€” otherwise inspecting a
+ // run this machine just performed would round-trip to the server for a
+ // snapshot that is already sitting on disk.
+ const localRun = await loadLocalSnapshot(target);
+ if (localRun) return localRun;
+
const snapshot = await loadSnapshot(target, { allowDownload: true, resolveDownloadUrl });
if (snapshot) return snapshot;
log.error(
diff --git a/apps/cli/src/utils/HeteroTraceRecorder.adapter.test.ts b/apps/cli/src/utils/HeteroTraceRecorder.adapter.test.ts
new file mode 100644
index 00000000000..587fe84ef4a
--- /dev/null
+++ b/apps/cli/src/utils/HeteroTraceRecorder.adapter.test.ts
@@ -0,0 +1,312 @@
+import { ClaudeCodeAdapter } from '@lobechat/heterogeneous-agents';
+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
+import { describe, expect, it } from 'vitest';
+
+import { HeteroTraceRecorder } from './HeteroTraceRecorder';
+import type { ExecutionSnapshot, ISnapshotStore, SnapshotSummary } from '@lobechat/agent-tracing';
+
+/**
+ * Drives the REAL Claude Code adapter, so the recorder is validated against the
+ * event stream the adapter actually emits rather than a hand-written imitation
+ * of it. A change to the adapter's event shapes should break this test.
+ */
+class MemoryStore implements ISnapshotStore {
+ partials = new Map<string, Partial<ExecutionSnapshot>>();
+ saved: ExecutionSnapshot[] = [];
+
+ async get() {
+ return null;
+ }
+ async getLatest() {
+ return null;
+ }
+ async list(): Promise<SnapshotSummary[]> {
+ return [];
+ }
+ async listPartials() {
+ return [];
+ }
+ async loadPartial(operationId: string) {
+ return this.partials.get(operationId) ?? null;
+ }
+ async removePartial(operationId: string) {
+ this.partials.delete(operationId);
+ }
+ async save(snapshot: ExecutionSnapshot) {
+ this.saved.push(snapshot);
+ }
+ async savePartial(operationId: string, partial: Partial<ExecutionSnapshot>) {
+ this.partials.set(operationId, partial);
+ }
+}
+
+/** A batch-mode Claude Code session: text, one tool call, an answer, a result. */
+const RAW_SESSION: unknown[] = [
+ { model: 'claude-opus-4-8', session_id: 'sess_1', subtype: 'init', type: 'system' },
+ {
+ message: {
+ content: [{ text: 'Let me read that file.', type: 'text' }],
+ id: 'msg_1',
+ model: 'claude-opus-4-8',
+ usage: { input_tokens: 100, output_tokens: 12 },
+ },
+ type: 'assistant',
+ },
+ {
+ message: {
+ content: [
+ { id: 'toolu_1', input: { file_path: '/tmp/a.ts' }, name: 'Read', type: 'tool_use' },
+ ],
+ id: 'msg_2',
+ model: 'claude-opus-4-8',
+ usage: { input_tokens: 150, output_tokens: 30 },
+ },
+ type: 'assistant',
+ },
+ {
+ message: {
+ content: [
+ { content: 'export const a = 1;', is_error: false, tool_use_id: 'toolu_1', type: 'tool_result' },
+ ],
+ },
+ type: 'user',
+ },
+ {
+ message: {
+ content: [{ text: 'The file exports `a`.', type: 'text' }],
+ id: 'msg_3',
+ model: 'claude-opus-4-8',
+ usage: { input_tokens: 200, output_tokens: 20 },
+ },
+ type: 'assistant',
+ },
+ {
+ result: 'done',
+ subtype: 'success',
+ total_cost_usd: 0.031,
+ type: 'result',
+ usage: { input_tokens: 450, output_tokens: 62 },
+ },
+];
+
+const runAdapter = (recorder: HeteroTraceRecorder) => {
+ const adapter = new ClaudeCodeAdapter();
+ let timestamp = 1_000;
+
+ for (const raw of RAW_SESSION) {
+ for (const event of adapter.adapt(raw as never)) {
+ recorder.observe({
+ ...event,
+ operationId: 'op_adapter',
+ timestamp: (timestamp += 100),
+ } as AgentStreamEvent);
+ }
+ }
+};
+
+/**
+ * A session where the main agent spawns a subagent via the Task tool. The
+ * subagent's own turns and tool calls carry `parent_tool_use_id`, and the
+ * adapter stamps them with a `subagent` peer field.
+ */
+const SUBAGENT_SESSION: unknown[] = [
+ { model: 'claude-opus-4-8', session_id: 'sess_2', subtype: 'init', type: 'system' },
+ {
+ message: {
+ content: [
+ { id: 'toolu_task', input: { prompt: 'go look' }, name: 'Task', type: 'tool_use' },
+ ],
+ id: 'msg_main_1',
+ model: 'claude-opus-4-8',
+ usage: { input_tokens: 100, output_tokens: 20 },
+ },
+ type: 'assistant',
+ },
+ // ── everything below is the SUBAGENT's own work ────────────────────────
+ {
+ message: {
+ content: [{ text: 'Subagent thinking out loud.', type: 'text' }],
+ id: 'msg_sub_1',
+ model: 'claude-opus-4-8',
+ usage: { input_tokens: 5000, output_tokens: 500 },
+ },
+ parent_tool_use_id: 'toolu_task',
+ type: 'assistant',
+ },
+ {
+ message: {
+ content: [
+ { id: 'toolu_sub', input: { file_path: '/tmp/inner.ts' }, name: 'Read', type: 'tool_use' },
+ ],
+ id: 'msg_sub_2',
+ model: 'claude-opus-4-8',
+ usage: { input_tokens: 5200, output_tokens: 40 },
+ },
+ parent_tool_use_id: 'toolu_task',
+ type: 'assistant',
+ },
+ {
+ message: {
+ content: [
+ { content: 'inner file body', is_error: false, tool_use_id: 'toolu_sub', type: 'tool_result' },
+ ],
+ },
+ parent_tool_use_id: 'toolu_task',
+ type: 'user',
+ },
+ // ── back to the MAIN agent: the Task tool returns ─────────────────────
+ {
+ message: {
+ content: [
+ { content: 'subagent report', is_error: false, tool_use_id: 'toolu_task', type: 'tool_result' },
+ ],
+ },
+ type: 'user',
+ },
+ {
+ message: {
+ content: [{ text: 'Done.', type: 'text' }],
+ id: 'msg_main_2',
+ model: 'claude-opus-4-8',
+ usage: { input_tokens: 300, output_tokens: 10 },
+ },
+ type: 'assistant',
+ },
+ {
+ result: 'ok',
+ subtype: 'success',
+ total_cost_usd: 0.5,
+ type: 'result',
+ usage: { input_tokens: 10600, output_tokens: 570 },
+ },
+];
+
+describe('HeteroTraceRecorder against the real ClaudeCodeAdapter', () => {
+ it('segments a session into per-turn LLM steps and per-call tool steps', async () => {
+ const store = new MemoryStore();
+ const recorder = new HeteroTraceRecorder({
+ agentType: 'claude-code',
+ operationId: 'op_adapter',
+ store,
+ topicId: 'tpc_adapter',
+ });
+
+ runAdapter(recorder);
+ await recorder.finalize({ result: 'success' });
+
+ const snapshot = store.saved[0];
+ expect(snapshot).toBeDefined();
+
+ // Three assistant turns β†’ three call_llm steps; one tool call β†’ one call_tool.
+ const llmSteps = snapshot.steps.filter((s) => s.stepType === 'call_llm');
+ const toolSteps = snapshot.steps.filter((s) => s.stepType === 'call_tool');
+ expect(llmSteps).toHaveLength(3);
+ expect(toolSteps).toHaveLength(1);
+
+ // Step indices are contiguous and chronological.
+ expect(snapshot.steps.map((s) => s.stepIndex)).toEqual([0, 1, 2, 3]);
+
+ // The turn that asked for the tool records the request. Note the adapter's
+ // convention: `identifier` is the wrapping CLI agent, `apiName` the tool it
+ // called β€” not the other way round.
+ expect(llmSteps[1].toolsCalling).toEqual([
+ {
+ apiName: 'Read',
+ arguments: JSON.stringify({ file_path: '/tmp/a.ts' }),
+ identifier: 'claude-code',
+ },
+ ]);
+ // …and the tool step records the outcome.
+ expect(toolSteps[0].toolsResult?.[0]).toMatchObject({
+ apiName: 'Read',
+ identifier: 'claude-code',
+ isSuccess: true,
+ output: 'export const a = 1;',
+ });
+
+ // Per-turn usage lands on the right step.
+ expect(llmSteps[0]).toMatchObject({ content: 'Let me read that file.', inputTokens: 100 });
+ expect(llmSteps[2]).toMatchObject({ content: 'The file exports `a`.', inputTokens: 200 });
+
+ // Session grand totals come from the result event, not the sum of turns.
+ expect(snapshot.totalCost).toBe(0.031);
+ expect(snapshot.totalTokens).toBe(512);
+ expect(snapshot.model).toBe('claude-opus-4-8');
+ expect(snapshot.completionReason).toBe('done');
+ });
+
+ it('keeps subagent work out of the main-agent spine', async () => {
+ const store = new MemoryStore();
+ const recorder = new HeteroTraceRecorder({
+ agentType: 'claude-code',
+ operationId: 'op_subagent',
+ store,
+ });
+
+ const adapter = new ClaudeCodeAdapter();
+ let timestamp = 1_000;
+ for (const raw of SUBAGENT_SESSION) {
+ for (const event of adapter.adapt(raw as never)) {
+ recorder.observe({
+ ...event,
+ operationId: 'op_subagent',
+ timestamp: (timestamp += 100),
+ } as AgentStreamEvent);
+ }
+ }
+ await recorder.finalize({ result: 'success' });
+
+ const snapshot = store.saved[0];
+ const llmSteps = snapshot.steps.filter((s) => s.stepType === 'call_llm');
+ const toolSteps = snapshot.steps.filter((s) => s.stepType === 'call_tool');
+
+ // The subagent's inner `Read` must NOT surface as a top-level tool step β€”
+ // only the main agent's `Task` call did.
+ expect(toolSteps).toHaveLength(1);
+ expect(toolSteps[0].toolsResult?.[0]).toMatchObject({
+ apiName: 'Task',
+ output: 'subagent report',
+ });
+
+ // The subagent's two turns must not become main-agent steps, and its text
+ // must not be appended to a main turn.
+ expect(llmSteps).toHaveLength(2);
+ const allContent = llmSteps.map((s) => s.content ?? '').join('');
+ expect(allContent).not.toContain('Subagent thinking out loud.');
+ expect(llmSteps[1].content).toBe('Done.');
+
+ // The subagent's usage must not be attributed to a main turn: the main
+ // agent spent 100 and 300 input tokens, never the subagent's 5000+.
+ expect(llmSteps.map((s) => s.inputTokens)).toEqual([100, 300]);
+ });
+
+ it('leaves a resumable partial behind when the process dies mid-session', async () => {
+ const store = new MemoryStore();
+ const recorder = new HeteroTraceRecorder({
+ agentType: 'claude-code',
+ operationId: 'op_killed',
+ store,
+ });
+
+ const adapter = new ClaudeCodeAdapter();
+ let timestamp = 1_000;
+ // Everything up to (but not including) the result event β€” i.e. the process
+ // was killed before it could finalize.
+ for (const raw of RAW_SESSION.slice(0, -1)) {
+ for (const event of adapter.adapt(raw as never)) {
+ recorder.observe({
+ ...event,
+ operationId: 'op_killed',
+ timestamp: (timestamp += 100),
+ } as AgentStreamEvent);
+ }
+ }
+ await new Promise((resolve) => setImmediate(resolve));
+
+ // No completed snapshot, but the work so far survives on disk.
+ expect(store.saved).toHaveLength(0);
+ const partial = store.partials.get('op_killed');
+ expect(partial?.steps?.length).toBeGreaterThan(0);
+ expect(partial?.operationId).toBe('op_killed');
+ });
+});
diff --git a/apps/cli/src/utils/HeteroTraceRecorder.test.ts b/apps/cli/src/utils/HeteroTraceRecorder.test.ts
new file mode 100644
index 00000000000..c2102788f8b
--- /dev/null
+++ b/apps/cli/src/utils/HeteroTraceRecorder.test.ts
@@ -0,0 +1,269 @@
+import type { ExecutionSnapshot, ISnapshotStore, SnapshotSummary } from '@lobechat/agent-tracing';
+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { HeteroTraceRecorder } from './HeteroTraceRecorder';
+
+/**
+ * Round-trip through JSON rather than `structuredClone`: the real store writes
+ * the partial to disk, so `undefined` fields must disappear here too. A
+ * structural clone would keep them and hide a serialization bug.
+ */
+// eslint-disable-next-line unicorn/prefer-structured-clone
+const serializeLikeDisk = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
+
+class MemoryStore implements ISnapshotStore {
+ partials = new Map<string, Partial<ExecutionSnapshot>>();
+ saved: ExecutionSnapshot[] = [];
+
+ async get(traceId: string) {
+ return this.saved.find((s) => s.traceId === traceId) ?? null;
+ }
+ async getLatest() {
+ return this.saved.at(-1) ?? null;
+ }
+ async list(): Promise<SnapshotSummary[]> {
+ return [];
+ }
+ async listPartials() {
+ return [...this.partials.keys()].map((id) => `${id}.json`);
+ }
+ async loadPartial(operationId: string) {
+ const partial = this.partials.get(operationId);
+ // Mirror the file store: callers get a copy, not the recorder's live object.
+ return partial ? serializeLikeDisk(partial) : null;
+ }
+ async removePartial(operationId: string) {
+ this.partials.delete(operationId);
+ }
+ async save(snapshot: ExecutionSnapshot) {
+ this.saved.push(snapshot);
+ }
+ async savePartial(operationId: string, partial: Partial<ExecutionSnapshot>) {
+ this.partials.set(operationId, serializeLikeDisk(partial));
+ }
+}
+
+const OPERATION_ID = 'op_test_1';
+
+let clock = 1_000;
+const event = (type: string, data: unknown = {}): AgentStreamEvent =>
+ ({
+ data,
+ operationId: OPERATION_ID,
+ stepIndex: 0,
+ timestamp: (clock += 100),
+ type,
+ }) as AgentStreamEvent;
+
+describe('HeteroTraceRecorder', () => {
+ let store: MemoryStore;
+ let recorder: HeteroTraceRecorder;
+
+ beforeEach(() => {
+ clock = 1000;
+ store = new MemoryStore();
+ recorder = new HeteroTraceRecorder({
+ agentType: 'claude-code',
+ operationId: OPERATION_ID,
+ store,
+ topicId: 'tpc_1',
+ });
+ });
+
+ it('records an assistant turn as a call_llm step with usage', async () => {
+ recorder.observe(event('stream_start', { model: 'claude-opus-4', provider: 'claude-code' }));
+ recorder.observe(event('stream_chunk', { chunkType: 'reasoning', content: 'thinking' }));
+ recorder.observe(event('stream_chunk', { chunkType: 'text', content: 'Hello' }));
+ recorder.observe(event('stream_chunk', { chunkType: 'text', content: ' world' }));
+ recorder.observe(
+ event('step_complete', {
+ model: 'claude-opus-4',
+ phase: 'turn_metadata',
+ usage: { totalInputTokens: 120, totalOutputTokens: 30, totalTokens: 150 },
+ }),
+ );
+ await recorder.finalize({ result: 'success' });
+
+ const snapshot = store.saved[0];
+ expect(snapshot.steps).toHaveLength(1);
+ expect(snapshot.steps[0]).toMatchObject({
+ content: 'Hello world',
+ inputTokens: 120,
+ outputTokens: 30,
+ reasoning: 'thinking',
+ stepIndex: 0,
+ stepType: 'call_llm',
+ totalTokens: 150,
+ });
+ expect(snapshot.completionReason).toBe('done');
+ expect(snapshot.model).toBe('claude-opus-4');
+ expect(snapshot.topicId).toBe('tpc_1');
+ });
+
+ it('records a tool call as its own call_tool step and attributes it to the turn', async () => {
+ recorder.observe(event('stream_start', { model: 'claude-opus-4' }));
+ recorder.observe(
+ event('tool_start', {
+ toolCalling: {
+ apiName: 'readFile',
+ arguments: '{"path":"a.ts"}',
+ id: 'call_1',
+ identifier: 'local-system',
+ },
+ }),
+ );
+ recorder.observe(
+ event('tool_result', { content: 'file body', isError: false, toolCallId: 'call_1' }),
+ );
+ recorder.observe(event('tool_end', { isSuccess: true, toolCallId: 'call_1' }));
+ recorder.observe(event('stream_end', {}));
+ await recorder.finalize({ result: 'success' });
+
+ const snapshot = store.saved[0];
+ const toolStep = snapshot.steps.find((s) => s.stepType === 'call_tool');
+ const llmStep = snapshot.steps.find((s) => s.stepType === 'call_llm');
+
+ expect(toolStep?.toolsResult).toEqual([
+ { apiName: 'readFile', identifier: 'local-system', isSuccess: true, output: 'file body' },
+ ]);
+ // The turn that asked for the tool keeps the request; the execution is its
+ // own step. Both halves have to be present to read the trace back.
+ expect(llmStep?.toolsCalling).toEqual([
+ { apiName: 'readFile', arguments: '{"path":"a.ts"}', identifier: 'local-system' },
+ ]);
+ });
+
+ it('takes session grand totals from result_usage', async () => {
+ recorder.observe(event('stream_start', {}));
+ recorder.observe(
+ event('step_complete', {
+ phase: 'turn_metadata',
+ usage: { totalInputTokens: 10, totalOutputTokens: 5, totalTokens: 15 },
+ }),
+ );
+ recorder.observe(
+ event('step_complete', {
+ costUsd: 0.42,
+ phase: 'result_usage',
+ usage: { totalTokens: 999 },
+ }),
+ );
+ await recorder.finalize({ result: 'success' });
+
+ expect(store.saved[0]).toMatchObject({ totalCost: 0.42, totalTokens: 999 });
+ });
+
+ it('falls back to per-turn tokens when the session total never arrives', async () => {
+ recorder.observe(event('stream_start', {}));
+ recorder.observe(
+ event('step_complete', { phase: 'turn_metadata', usage: { totalTokens: 150 } }),
+ );
+ recorder.observe(
+ event('step_complete', { phase: 'turn_metadata', usage: { totalTokens: 90 } }),
+ );
+ // Cancelled before `result_usage` β€” the only truthful number is the sum.
+ await recorder.finalize({ result: 'cancelled' });
+
+ expect(store.saved[0].totalTokens).toBe(240);
+ });
+
+ it('maps a cancelled run to interrupted and an error to error', async () => {
+ recorder.observe(event('stream_start', {}));
+ recorder.observe(event('stream_chunk', { chunkType: 'text', content: 'partial' }));
+ await recorder.finalize({ result: 'cancelled' });
+ expect(store.saved[0].completionReason).toBe('interrupted');
+
+ const second = new HeteroTraceRecorder({ agentType: 'codex', operationId: 'op_2', store });
+ second.observe(event('stream_start', {}));
+ second.observe(event('stream_chunk', { chunkType: 'text', content: 'x' }));
+ await second.finalize({
+ error: { message: 'boom', type: 'AgentRuntimeError' },
+ result: 'error',
+ });
+ expect(store.saved[1]).toMatchObject({
+ completionReason: 'error',
+ error: { message: 'boom', type: 'AgentRuntimeError' },
+ });
+ });
+
+ it('keeps a partial on disk while the run is in flight, and removes it on finalize', async () => {
+ recorder.observe(event('stream_start', {}));
+ recorder.observe(event('stream_chunk', { chunkType: 'text', content: 'hi' }));
+ recorder.observe(event('step_complete', { phase: 'turn_metadata', usage: { totalTokens: 5 } }));
+ // Let the coalescing writer settle.
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(store.partials.get(OPERATION_ID)?.steps).toHaveLength(1);
+
+ await recorder.finalize({ result: 'success' });
+ expect(store.partials.has(OPERATION_ID)).toBe(false);
+ });
+
+ it('retains notable events but not the chunk stream', async () => {
+ recorder.observe(event('stream_start', {}));
+ recorder.observe(event('stream_chunk', { chunkType: 'text', content: 'a' }));
+ recorder.observe(event('stream_retry', { attempt: 2 }));
+ await recorder.finalize({ result: 'success' });
+
+ const events = store.saved[0].steps[0].events ?? [];
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ attempt: 2, type: 'stream_retry' });
+ });
+
+ it('never throws when the store fails', async () => {
+ const failing = new MemoryStore();
+ failing.savePartial = async () => {
+ throw new Error('disk full');
+ };
+ const warnings: string[] = [];
+ const guarded = new HeteroTraceRecorder({
+ agentType: 'claude-code',
+ onError: (message) => warnings.push(message),
+ operationId: 'op_3',
+ store: failing,
+ });
+
+ guarded.observe(event('stream_start', {}));
+ guarded.observe(event('stream_chunk', { chunkType: 'text', content: 'x' }));
+ await expect(guarded.finalize({ result: 'success' })).resolves.toBeUndefined();
+ expect(warnings.join('\n')).toContain('disk full');
+ });
+});
+
+describe('HeteroTraceRecorder empty runs', () => {
+ it('writes no snapshot for a run that recorded nothing', async () => {
+ const store = new MemoryStore();
+ const quiet = new HeteroTraceRecorder({
+ agentType: 'claude-code',
+ operationId: 'op_empty',
+ store,
+ });
+
+ await quiet.finalize({ result: 'success' });
+
+ expect(store.saved).toHaveLength(0);
+ expect(store.partials.has('op_empty')).toBe(false);
+ });
+
+ it('still writes a snapshot for a run that failed before producing a step', async () => {
+ const store = new MemoryStore();
+ const failed = new HeteroTraceRecorder({
+ agentType: 'claude-code',
+ operationId: 'op_never_started',
+ store,
+ });
+
+ // "The CLI binary was not found" β€” no events at all, but the failure is
+ // exactly what makes the trace worth keeping.
+ await failed.finalize({
+ error: { message: 'claude: command not found', type: 'AgentRuntimeError' },
+ result: 'error',
+ });
+
+ expect(store.saved[0]).toMatchObject({
+ completionReason: 'error',
+ error: { message: 'claude: command not found' },
+ });
+ });
+});
diff --git a/apps/cli/src/utils/HeteroTraceRecorder.ts b/apps/cli/src/utils/HeteroTraceRecorder.ts
new file mode 100644
index 00000000000..46139592163
--- /dev/null
+++ b/apps/cli/src/utils/HeteroTraceRecorder.ts
@@ -0,0 +1,408 @@
+import {
+ type ExecutionSnapshot,
+ finalizeSnapshot,
+ type ISnapshotStore,
+ type StepSnapshot,
+} from '@lobechat/agent-tracing';
+import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';
+
+/**
+ * Assistant text / reasoning kept per step. Generous β€” this is the part a human
+ * actually reads back β€” but not unbounded: the partial snapshot is rewritten in
+ * full on every step, so an uncapped field turns a long run into quadratic I/O.
+ */
+const MAX_CONTENT_CHARS = 64 * 1024;
+
+/**
+ * Tool output kept per step. Much tighter than assistant text: a single `Read`
+ * of a large file would otherwise dominate the whole trace.
+ */
+const MAX_TOOL_OUTPUT_CHARS = 8 * 1024;
+
+/** Event types worth keeping verbatim β€” everything else is already structured. */
+const NOTABLE_EVENT_TYPES = new Set([
+ 'error',
+ 'stream_retry',
+ 'agent_intervention_request',
+ 'agent_intervention_response',
+]);
+
+const truncate = (value: string, max: number): string =>
+ value.length <= max ? value : `${value.slice(0, max)}\n…[truncated ${value.length - max} chars]`;
+
+const asRecord = (value: unknown): Record<string, any> =>
+ value && typeof value === 'object' ? (value as Record<string, any>) : {};
+
+/** Per-turn totals, used when the session grand total never arrived. */
+export const sumStepTokens = (steps?: Array<{ totalTokens?: number }>): number =>
+ (steps ?? []).reduce((total, step) => total + (step.totalTokens ?? 0), 0);
+
+interface OpenLlmStep {
+ content: string;
+ events: Array<{ [key: string]: unknown; type: string }>;
+ model?: string;
+ provider?: string;
+ reasoning: string;
+ startedAt: number;
+ toolsCalling: Array<{ apiName: string; arguments?: string; identifier: string }>;
+}
+
+interface OpenToolStep {
+ apiName: string;
+ arguments?: string;
+ identifier: string;
+ isSuccess?: boolean;
+ output?: string;
+ startedAt: number;
+}
+
+export interface HeteroTraceRecorderOptions {
+ agentType: string;
+ /** Best-effort warning sink. A trace failure must never fail the run. */
+ onError?: (message: string) => void;
+ operationId: string;
+ store: ISnapshotStore;
+ topicId?: string;
+}
+
+export type HeteroRunResult = 'cancelled' | 'error' | 'success';
+
+/**
+ * Records a heterogeneous agent run as an `ExecutionSnapshot` on local disk.
+ *
+ * The stream a CLI-wrapped agent emits (`stream_start` … `step_complete`,
+ * `tool_start` … `tool_end`) already carries everything a step needs, so this
+ * folds it into the SAME snapshot format the server writes for native agent
+ * runs β€” which is what lets `lh trace op inspect` read both without branching.
+ *
+ * Fields that only a native run can produce (`messagesBaseline`,
+ * `contextEngine`, `toolsetBaseline`) are simply absent; they are optional on
+ * `StepSnapshot` precisely so a partial producer stays valid.
+ *
+ * Every method is best-effort: a failed write is logged and swallowed. Losing a
+ * trace is an inconvenience, losing the run is not acceptable.
+ */
+export class HeteroTraceRecorder {
+ private llmStep: OpenLlmStep | null = null;
+ private nextStepIndex = 0;
+ private readonly partial: Partial<ExecutionSnapshot>;
+ private readonly toolSteps = new Map<string, OpenToolStep>();
+
+ /** Grand totals from `step_complete{phase:'result_usage'}`, if the CLI reports them. */
+ private totalCost = 0;
+ private totalTokens = 0;
+
+ // Serialized, coalescing writer: at most one write in flight, and a write
+ // that lands while another is running is folded into a single follow-up.
+ private dirty = false;
+ private writing: Promise<void> = Promise.resolve();
+
+ constructor(private readonly options: HeteroTraceRecorderOptions) {
+ this.partial = {
+ agentId: undefined,
+ operationId: options.operationId,
+ // The CLI-wrapped agent IS the provider here (`claude-code`, `codex`) β€”
+ // the wrapped model's vendor is reported separately per turn.
+ provider: options.agentType,
+ startedAt: Date.now(),
+ steps: [],
+ topicId: options.topicId,
+ traceId: options.operationId,
+ };
+ }
+
+ /** Feed one event. Never throws. */
+ observe(event: AgentStreamEvent): void {
+ try {
+ this.handle(event);
+ } catch (error) {
+ this.warn(`failed to record event ${event.type}: ${String(error)}`);
+ }
+ }
+
+ /**
+ * Close any open step and write the completed snapshot. Removes the partial,
+ * so a partial left on disk always means "this run never finished".
+ */
+ async finalize(completion: {
+ error?: { message: string; type: string };
+ result: HeteroRunResult;
+ }): Promise<void> {
+ try {
+ this.closeLlmStep();
+ for (const toolCallId of this.toolSteps.keys()) this.closeToolStep(toolCallId);
+
+ // A run that produced no step and no error has nothing worth a snapshot β€”
+ // writing one anyway fills the store with empty files to page past in
+ // `lh trace op list`. A failure with no steps IS worth keeping: "it never
+ // got off the ground" is exactly what someone reads a trace to find out.
+ const hasContent =
+ (this.partial.steps?.length ?? 0) > 0 || this.totalTokens > 0 || !!completion.error;
+ if (!hasContent) {
+ await this.options.store.removePartial(this.options.operationId);
+ return;
+ }
+
+ await this.flush();
+ await finalizeSnapshot(this.options.store, this.options.operationId, {
+ error: completion.error,
+ reason:
+ completion.result === 'success'
+ ? 'done'
+ : completion.result === 'cancelled'
+ ? 'interrupted'
+ : 'error',
+ totalCost: this.totalCost,
+ totalSteps: this.partial.steps?.length ?? 0,
+ // `result_usage` is the authoritative session total, but an interrupted
+ // or errored run never reaches it β€” sum the turns instead, so the trace
+ // reports what was actually spent rather than zero.
+ totalTokens: this.totalTokens || sumStepTokens(this.partial.steps),
+ });
+ } catch (error) {
+ this.warn(`failed to finalize trace: ${String(error)}`);
+ }
+ }
+
+ // ─── Event handling ───────────────────────────────────────────────────────
+
+ private handle(event: AgentStreamEvent): void {
+ const data = asRecord(event.data);
+
+ // Subagent-scoped events (Claude Code's Task tool) ride the SAME stream as
+ // the main agent's, tagged with a `subagent` peer field. Folding them into
+ // the main spine would append the child's text to the parent's turn, let
+ // the child's usage close that turn early, and surface the child's tools as
+ // top-level calls β€” corrupting the trace precisely for the runs that use
+ // Agent/Task. The parent's own `Task` tool step still records the result
+ // the child returned, which mirrors how the native runtime keeps a
+ // sub-agent's work in its own child operation rather than the parent's.
+ if (data.subagent) return;
+
+ switch (event.type) {
+ case 'stream_start': {
+ // Session opening for Claude Code (emitted once, on `system.init`);
+ // per-turn for some other adapters. Either way it starts a turn, and a
+ // turn still open at this point never reported its usage β€” close it so
+ // steps stay one-per-turn. Turns after the first are opened lazily by
+ // `ensureLlmStep`, which is what makes both conventions segment the
+ // same way.
+ this.closeLlmStep();
+ this.llmStep = {
+ content: '',
+ events: [],
+ model: typeof data.model === 'string' ? data.model : undefined,
+ provider: typeof data.provider === 'string' ? data.provider : undefined,
+ reasoning: '',
+ startedAt: event.timestamp,
+ toolsCalling: [],
+ };
+ return;
+ }
+
+ case 'stream_chunk': {
+ const step = this.ensureLlmStep(event.timestamp);
+ const content = typeof data.content === 'string' ? data.content : '';
+ if (!content) return;
+ if (data.chunkType === 'text') step.content += content;
+ else if (data.chunkType === 'reasoning') step.reasoning += content;
+ return;
+ }
+
+ case 'step_complete': {
+ if (data.phase === 'turn_metadata') {
+ const step = this.ensureLlmStep(event.timestamp);
+ if (typeof data.model === 'string') step.model = data.model;
+ if (typeof data.provider === 'string') step.provider = data.provider;
+ this.closeLlmStep(event.timestamp, asRecord(data.usage));
+ return;
+ }
+
+ if (data.phase === 'result_usage') {
+ // Authoritative session grand total β€” overwrite rather than add, it
+ // already covers every turn.
+ const usage = asRecord(data.usage);
+ if (typeof data.costUsd === 'number') this.totalCost = data.costUsd;
+ if (typeof usage.totalTokens === 'number') this.totalTokens = usage.totalTokens;
+ this.scheduleWrite();
+ }
+ return;
+ }
+
+ case 'stream_end': {
+ this.closeLlmStep(event.timestamp);
+ return;
+ }
+
+ case 'tool_start': {
+ const toolCalling = asRecord(data.toolCalling);
+ const toolCallId = typeof toolCalling.id === 'string' ? toolCalling.id : undefined;
+ if (!toolCallId) return;
+
+ const identifier = String(toolCalling.identifier ?? '');
+ const apiName = String(toolCalling.apiName ?? '');
+ // The call is attributed to the LLM turn that produced it, so the trace
+ // shows which turn asked for what β€” then it becomes its own tool step.
+ this.llmStep?.toolsCalling.push({
+ apiName,
+ arguments: typeof toolCalling.arguments === 'string' ? toolCalling.arguments : undefined,
+ identifier,
+ });
+ this.toolSteps.set(toolCallId, {
+ apiName,
+ arguments: typeof toolCalling.arguments === 'string' ? toolCalling.arguments : undefined,
+ identifier,
+ startedAt: event.timestamp,
+ });
+ return;
+ }
+
+ case 'tool_result': {
+ const toolCallId = typeof data.toolCallId === 'string' ? data.toolCallId : undefined;
+ const step = toolCallId ? this.toolSteps.get(toolCallId) : undefined;
+ if (!step) return;
+ if (typeof data.content === 'string') step.output = data.content;
+ if (typeof data.isError === 'boolean') step.isSuccess = !data.isError;
+ return;
+ }
+
+ case 'tool_end': {
+ const toolCallId = typeof data.toolCallId === 'string' ? data.toolCallId : undefined;
+ if (!toolCallId) return;
+ const step = this.toolSteps.get(toolCallId);
+ if (step && typeof data.isSuccess === 'boolean') step.isSuccess = data.isSuccess;
+ this.closeToolStep(toolCallId, event.timestamp);
+ return;
+ }
+
+ default: {
+ if (!NOTABLE_EVENT_TYPES.has(event.type)) return;
+ // Attach to the open turn when there is one; otherwise it would be lost
+ // between turns, which is exactly where a terminal error tends to land.
+ const step = this.ensureLlmStep(event.timestamp);
+ step.events.push({ ...data, timestamp: event.timestamp, type: event.type });
+ }
+ }
+ }
+
+ // ─── Step lifecycle ───────────────────────────────────────────────────────
+
+ private ensureLlmStep(startedAt: number): OpenLlmStep {
+ if (!this.llmStep) {
+ this.llmStep = {
+ content: '',
+ events: [],
+ reasoning: '',
+ startedAt,
+ toolsCalling: [],
+ };
+ }
+ return this.llmStep;
+ }
+
+ private closeLlmStep(completedAt = Date.now(), usage?: Record<string, any>): void {
+ const open = this.llmStep;
+ this.llmStep = null;
+ if (!open) return;
+
+ // An empty turn carries nothing worth a step row β€” it happens when a
+ // `stream_start` is immediately followed by another one on a retry.
+ const isEmpty =
+ !open.content &&
+ !open.reasoning &&
+ open.toolsCalling.length === 0 &&
+ open.events.length === 0 &&
+ !usage;
+ if (isEmpty) return;
+
+ const inputTokens =
+ typeof usage?.totalInputTokens === 'number' ? usage.totalInputTokens : undefined;
+ const outputTokens =
+ typeof usage?.totalOutputTokens === 'number' ? usage.totalOutputTokens : undefined;
+
+ this.pushStep(
+ {
+ completedAt,
+ content: open.content ? truncate(open.content, MAX_CONTENT_CHARS) : undefined,
+ events: open.events.length > 0 ? open.events : undefined,
+ executionTimeMs: Math.max(0, completedAt - open.startedAt),
+ inputTokens,
+ outputTokens,
+ reasoning: open.reasoning ? truncate(open.reasoning, MAX_CONTENT_CHARS) : undefined,
+ startedAt: open.startedAt,
+ stepIndex: this.nextStepIndex++,
+ stepType: 'call_llm',
+ toolsCalling: open.toolsCalling.length > 0 ? open.toolsCalling : undefined,
+ totalCost: 0,
+ totalTokens: typeof usage?.totalTokens === 'number' ? usage.totalTokens : 0,
+ },
+ { model: open.model, provider: open.provider },
+ );
+ }
+
+ private closeToolStep(toolCallId: string, completedAt = Date.now()): void {
+ const open = this.toolSteps.get(toolCallId);
+ if (!open) return;
+ this.toolSteps.delete(toolCallId);
+
+ this.pushStep({
+ completedAt,
+ executionTimeMs: Math.max(0, completedAt - open.startedAt),
+ startedAt: open.startedAt,
+ stepIndex: this.nextStepIndex++,
+ stepType: 'call_tool',
+ toolsResult: [
+ {
+ apiName: open.apiName,
+ identifier: open.identifier,
+ isSuccess: open.isSuccess,
+ output: open.output ? truncate(open.output, MAX_TOOL_OUTPUT_CHARS) : undefined,
+ },
+ ],
+ totalCost: 0,
+ totalTokens: 0,
+ });
+ }
+
+ private pushStep(step: StepSnapshot, metadata?: { model?: string; provider?: string }): void {
+ this.partial.steps ??= [];
+ this.partial.steps.push(step);
+ // The model id only becomes known once the first turn reports it.
+ if (!this.partial.model && metadata?.model) this.partial.model = metadata.model;
+ this.scheduleWrite();
+ }
+
+ // ─── Persistence ──────────────────────────────────────────────────────────
+
+ /**
+ * Write the partial without reading it back first.
+ *
+ * `appendStepToPartial` from the tracing package re-reads the file on every
+ * step, which is quadratic over a long CLI run; the recorder already holds
+ * the authoritative copy in memory, so it writes straight through. The
+ * on-disk format is identical.
+ */
+ private scheduleWrite(): void {
+ this.dirty = true;
+ this.writing = this.writing.then(() => this.drain());
+ }
+
+ private async drain(): Promise<void> {
+ if (!this.dirty) return;
+ this.dirty = false;
+ try {
+ await this.options.store.savePartial(this.options.operationId, this.partial);
+ } catch (error) {
+ this.warn(`failed to write partial trace: ${String(error)}`);
+ }
+ }
+
+ private async flush(): Promise<void> {
+ this.scheduleWrite();
+ await this.writing;
+ }
+
+ private warn(message: string): void {
+ this.options.onError?.(message);
+ }
+}
diff --git a/apps/cli/src/utils/traceMaintenance.test.ts b/apps/cli/src/utils/traceMaintenance.test.ts
new file mode 100644
index 00000000000..f15335a556d
--- /dev/null
+++ b/apps/cli/src/utils/traceMaintenance.test.ts
@@ -0,0 +1,140 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { ExecutionSnapshot, ISnapshotStore, SnapshotSummary } from '@lobechat/agent-tracing';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { pruneOldTraces, reconcileOrphanTraces } from './traceMaintenance';
+
+class MemoryStore implements ISnapshotStore {
+ partials = new Map<string, Partial<ExecutionSnapshot>>();
+ saved: ExecutionSnapshot[] = [];
+
+ async get() {
+ return null;
+ }
+ async getLatest() {
+ return null;
+ }
+ async list(): Promise<SnapshotSummary[]> {
+ return [];
+ }
+ async listPartials() {
+ return [...this.partials.keys()].map((id) => `${id}.json`);
+ }
+ async loadPartial(operationId: string) {
+ return this.partials.get(operationId) ?? null;
+ }
+ async removePartial(operationId: string) {
+ this.partials.delete(operationId);
+ }
+ async save(snapshot: ExecutionSnapshot) {
+ this.saved.push(snapshot);
+ }
+ async savePartial(operationId: string, partial: Partial<ExecutionSnapshot>) {
+ this.partials.set(operationId, partial);
+ }
+}
+
+const NOW = 10_000_000;
+const HOUR = 60 * 60 * 1000;
+
+describe('reconcileOrphanTraces', () => {
+ it('closes a partial whose last step is older than the idle window', async () => {
+ const store = new MemoryStore();
+ store.partials.set('op_dead', {
+ operationId: 'op_dead',
+ startedAt: NOW - 12 * HOUR,
+ steps: [{ completedAt: NOW - 10 * HOUR } as any],
+ });
+
+ const reconciled = await reconcileOrphanTraces(store, { now: NOW });
+
+ expect(reconciled).toBe(1);
+ expect(store.saved[0]).toMatchObject({
+ completionReason: 'interrupted',
+ operationId: 'op_dead',
+ });
+ // The partial is consumed, so it is never reconciled twice.
+ expect(store.partials.has('op_dead')).toBe(false);
+ });
+
+ it('reports the tokens the killed run did spend, not zero', async () => {
+ const store = new MemoryStore();
+ store.partials.set('op_dead', {
+ operationId: 'op_dead',
+ startedAt: NOW - 12 * HOUR,
+ steps: [
+ { completedAt: NOW - 11 * HOUR, totalTokens: 1200 } as any,
+ { completedAt: NOW - 10 * HOUR, totalTokens: 800 } as any,
+ ],
+ });
+
+ await reconcileOrphanTraces(store, { now: NOW });
+
+ // `result_usage` never arrived, so the session total is the sum of turns.
+ expect(store.saved[0].totalTokens).toBe(2000);
+ });
+
+ it('leaves a partial that is still being written alone', async () => {
+ const store = new MemoryStore();
+ store.partials.set('op_live', {
+ operationId: 'op_live',
+ startedAt: NOW - 12 * HOUR,
+ // A long-running agent: started hours ago, but stepped a minute ago.
+ steps: [{ completedAt: NOW - 60_000 } as any],
+ });
+
+ expect(await reconcileOrphanTraces(store, { now: NOW })).toBe(0);
+ expect(store.partials.has('op_live')).toBe(true);
+ expect(store.saved).toHaveLength(0);
+ });
+
+ it('falls back to startedAt for a partial that never recorded a step', async () => {
+ const store = new MemoryStore();
+ store.partials.set('op_stillborn', { operationId: 'op_stillborn', startedAt: NOW - 12 * HOUR });
+
+ expect(await reconcileOrphanTraces(store, { now: NOW })).toBe(1);
+ });
+});
+
+describe('pruneOldTraces', () => {
+ let dir: string;
+
+ beforeEach(async () => {
+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'trace-prune-'));
+ });
+
+ afterEach(async () => {
+ await fs.rm(dir, { force: true, recursive: true });
+ });
+
+ it('deletes snapshots past the retention window and keeps recent ones', async () => {
+ const old = path.join(dir, '2020-01-01_old.json');
+ const recent = path.join(dir, '2026-01-01_recent.json');
+ await fs.writeFile(old, '{}');
+ await fs.writeFile(recent, '{}');
+ const staleTime = new Date(Date.now() - 30 * 24 * HOUR);
+ await fs.utimes(old, staleTime, staleTime);
+
+ expect(await pruneOldTraces({ dir, maxAgeMs: 14 * 24 * HOUR })).toBe(1);
+ expect(await fs.readdir(dir)).toEqual(['2026-01-01_recent.json']);
+ });
+
+ it('ignores the latest symlink and non-snapshot files', async () => {
+ await fs.writeFile(path.join(dir, 'keep.json'), '{}');
+ await fs.symlink('keep.json', path.join(dir, 'latest.json'));
+ await fs.writeFile(path.join(dir, 'notes.txt'), 'x');
+
+ // `now` is pinned ahead of the writes: `mtimeMs` carries sub-millisecond
+ // precision, so a freshly written file can read as marginally newer than an
+ // integer `Date.now()` and survive a zero-length window.
+ expect(await pruneOldTraces({ dir, maxAgeMs: 0, now: Date.now() + 60_000 })).toBe(1);
+ expect((await fs.readdir(dir)).sort()).toEqual(['latest.json', 'notes.txt']);
+ });
+
+ it('returns 0 when the trace directory does not exist yet', async () => {
+ expect(await pruneOldTraces({ dir: path.join(dir, 'missing') })).toBe(0);
+ });
+});
diff --git a/apps/cli/src/utils/traceMaintenance.ts b/apps/cli/src/utils/traceMaintenance.ts
new file mode 100644
index 00000000000..bc10487fc6e
--- /dev/null
+++ b/apps/cli/src/utils/traceMaintenance.ts
@@ -0,0 +1,124 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+
+import { finalizeSnapshot, type ISnapshotStore } from '@lobechat/agent-tracing';
+
+import { sumStepTokens } from './HeteroTraceRecorder';
+import { createLocalTraceStore, resolveTraceDir } from './traceStore';
+
+/**
+ * How long a partial must go without a new step before it is treated as the
+ * remains of a killed process rather than a live run.
+ *
+ * Deliberately generous: a single LLM turn can legitimately run for many
+ * minutes, and finalizing a partial that is still being written would publish a
+ * bogus `interrupted` snapshot for a run that is about to succeed. No real run
+ * goes this long between steps.
+ */
+const ORPHAN_IDLE_MS = 6 * 60 * 60 * 1000;
+
+/** Completed snapshots older than this are deleted on the next sweep. */
+const RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
+
+const lastActivityAt = (partial: {
+ startedAt?: number;
+ steps?: Array<{ completedAt: number }>;
+}): number => {
+ const steps = partial.steps ?? [];
+ const lastStep = steps.at(-1);
+ return lastStep?.completedAt ?? partial.startedAt ?? 0;
+};
+
+/**
+ * Turn partials left behind by killed processes into completed `interrupted`
+ * snapshots.
+ *
+ * Without this a `kill -9` leaves the run visible only to `lh trace op inspect`
+ * (which falls back to partials) and invisible to `lh trace op list` (which
+ * lists completed snapshots) β€” the crashed runs, the ones most worth finding,
+ * would be the ones that never show up.
+ *
+ * @returns number of partials reconciled.
+ */
+export const reconcileOrphanTraces = async (
+ store: ISnapshotStore = createLocalTraceStore(),
+ options?: { idleMs?: number; now?: number },
+): Promise<number> => {
+ const idleMs = options?.idleMs ?? ORPHAN_IDLE_MS;
+ const now = options?.now ?? Date.now();
+
+ let reconciled = 0;
+ const partials = await store.listPartials().catch(() => []);
+
+ for (const filename of partials) {
+ const operationId = filename.replace(/\.json$/, '');
+ const partial = await store.loadPartial(operationId).catch(() => null);
+ if (!partial) continue;
+ if (now - lastActivityAt(partial) < idleMs) continue;
+
+ await finalizeSnapshot(store, operationId, {
+ error: { message: 'Run ended without recording a result', type: 'interrupted' },
+ reason: 'interrupted',
+ totalCost: partial.totalCost ?? 0,
+ totalSteps: partial.steps?.length ?? 0,
+ // A killed run never emitted its session total, so the only truthful
+ // number available is the sum of the turns it did record.
+ totalTokens: partial.totalTokens || sumStepTokens(partial.steps),
+ }).catch(() => {});
+ reconciled += 1;
+ }
+
+ return reconciled;
+};
+
+/**
+ * Delete completed snapshots older than the retention window.
+ *
+ * The store is a flat directory that only ever grows, and one long agent run
+ * can be a multi-megabyte JSON β€” left alone it becomes the largest thing in the
+ * CLI home. Partials are left to {@link reconcileOrphanTraces}, which turns
+ * them into completed snapshots that this sweep then ages out normally.
+ *
+ * @returns number of snapshots deleted.
+ */
+export const pruneOldTraces = async (options?: {
+ dir?: string;
+ maxAgeMs?: number;
+ now?: number;
+}): Promise<number> => {
+ const dir = options?.dir ?? resolveTraceDir();
+ const maxAgeMs = options?.maxAgeMs ?? RETENTION_MS;
+ const now = options?.now ?? Date.now();
+
+ const entries = await fs.readdir(dir).catch(() => [] as string[]);
+ let deleted = 0;
+
+ for (const entry of entries) {
+ if (!entry.endsWith('.json') || entry === 'latest.json') continue;
+ const filePath = path.join(dir, entry);
+ // `lstat`, not `stat`: `latest.json` is filtered above, but a stale symlink
+ // to a already-deleted snapshot would otherwise throw on stat.
+ const stat = await fs.lstat(filePath).catch(() => null);
+ if (!stat?.isFile()) continue;
+ if (now - stat.mtimeMs < maxAgeMs) continue;
+
+ await fs.unlink(filePath).catch(() => {});
+ deleted += 1;
+ }
+
+ return deleted;
+};
+
+/**
+ * Best-effort housekeeping for the local trace store. Safe to call on every
+ * daemon start; never throws.
+ */
+export const sweepLocalTraces = async (): Promise<{ deleted: number; reconciled: number }> => {
+ try {
+ const reconciled = await reconcileOrphanTraces();
+ const deleted = await pruneOldTraces();
+ return { deleted, reconciled };
+ } catch {
+ return { deleted: 0, reconciled: 0 };
+ }
+};
diff --git a/apps/cli/src/utils/traceStore.ts b/apps/cli/src/utils/traceStore.ts
new file mode 100644
index 00000000000..c79bd2de3cb
--- /dev/null
+++ b/apps/cli/src/utils/traceStore.ts
@@ -0,0 +1,42 @@
+import os from 'node:os';
+import path from 'node:path';
+
+import { FileSnapshotStore, type ISnapshotStore } from '@lobechat/agent-tracing';
+
+import { resolveCliDirName } from '../constants/identity';
+
+/**
+ * Leaf directory holding locally recorded execution traces. Sits next to
+ * `settings.json` / `credentials.json` under the CLI home rather than under the
+ * user's cwd: an agent run's trace belongs to the machine, not to whichever
+ * repository happened to be the working directory when it was spawned.
+ */
+const TRACES_DIR_NAME = 'traces';
+
+/**
+ * `~/.lobehub/traces` β€” or the `LOBEHUB_CLI_HOME` override, so a dev build
+ * (`LOBEHUB_CLI_HOME=.lobehub-dev`) keeps its traces out of the real ones.
+ */
+export const resolveTraceRoot = (): string => path.join(os.homedir(), resolveCliDirName());
+
+/** Absolute path of the directory the snapshots actually live in. */
+export const resolveTraceDir = (): string => path.join(resolveTraceRoot(), TRACES_DIR_NAME);
+
+/**
+ * Snapshot store for locally executed agent runs.
+ *
+ * Layout (owned by `FileSnapshotStore`):
+ *
+ * ~/.lobehub/traces/
+ * 2026-08-30T…_op_abc123def.json completed runs
+ * _partial/op_abc….json in-progress, or left behind by a crash
+ * latest.json symlink to the newest completed run
+ */
+export const createLocalTraceStore = (): ISnapshotStore =>
+ new FileSnapshotStore(resolveTraceRoot(), TRACES_DIR_NAME);
+
+/** Options that point `loadSnapshot` at the store above. */
+export const localTraceStoreOptions = () => ({
+ dirName: TRACES_DIR_NAME,
+ rootDir: resolveTraceRoot(),
+});
diff --git a/apps/cli/tests/setup.ts b/apps/cli/tests/setup.ts
index c354b0eae86..e3029eaa688 100644
--- a/apps/cli/tests/setup.ts
+++ b/apps/cli/tests/setup.ts
@@ -1,7 +1,23 @@
-import { vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterAll, vi } from 'vitest';
import type * as loggerModule from '../src/utils/logger';
+// Point the CLI home at a throwaway directory for the whole run. Anything the
+// CLI persists β€” settings, credentials, the connect daemon's state, execution
+// traces β€” resolves against `resolveCliDirName()` under `os.homedir()`, so
+// without this a suite that drives a command end to end writes into the
+// developer's real `~/.lobehub`.
+const testHomeDirName = `.lobehub-test-${process.pid}`;
+process.env.LOBEHUB_CLI_HOME = testHomeDirName;
+
+afterAll(() => {
+ fs.rmSync(path.join(os.homedir(), testHomeDirName), { force: true, recursive: true });
+});
+
// The real logger writes straight to stdout/stderr, so every suite stubbed it by
// hand. Suites asserting on log calls import `log` and read the spies below; a
// suite needing different behavior overrides this with its own `vi.mock`.
diff --git a/packages/agent-tracing/src/recorder/index.ts b/packages/agent-tracing/src/recorder/index.ts
index ba5748509f1..96a07d59b96 100644
--- a/packages/agent-tracing/src/recorder/index.ts
+++ b/packages/agent-tracing/src/recorder/index.ts
@@ -9,16 +9,22 @@ export async function appendStepToPartial(
store: ISnapshotStore,
operationId: string,
step: StepSnapshot,
- metadata?: { model?: string; provider?: string },
+ metadata?: { agentId?: string; model?: string; provider?: string; topicId?: string },
): Promise<void> {
const partial = (await store.loadPartial(operationId)) ?? { steps: [] };
if (!partial.startedAt) {
partial.startedAt = Date.now();
- partial.model = metadata?.model;
- partial.provider = metadata?.provider;
+ partial.agentId = metadata?.agentId;
+ partial.topicId = metadata?.topicId;
}
+ // Model / provider are only known once the first LLM turn reports them, which
+ // for a CLI-wrapped agent is several steps in β€” so they are filled on the
+ // first step that carries them, not only on the header-creating step.
+ if (!partial.model && metadata?.model) partial.model = metadata.model;
+ if (!partial.provider && metadata?.provider) partial.provider = metadata.provider;
+
if (!partial.steps) partial.steps = [];
partial.steps.push(step);
@@ -44,6 +50,7 @@ export async function finalizeSnapshot(
if (!partial) return;
const snapshot: ExecutionSnapshot = {
+ agentId: partial.agentId,
completedAt: Date.now(),
completionReason: completion.reason as ExecutionSnapshot['completionReason'],
error: completion.error,
@@ -52,10 +59,12 @@ export async function finalizeSnapshot(
provider: partial.provider,
startedAt: partial.startedAt ?? Date.now(),
steps: (partial.steps ?? []).sort((a, b) => a.stepIndex - b.stepIndex),
+ topicId: partial.topicId,
totalCost: completion.totalCost,
totalSteps: completion.totalSteps,
totalTokens: completion.totalTokens,
traceId: operationId,
+ userId: partial.userId,
};
await store.save(snapshot);
diff --git a/packages/agent-tracing/src/store/file-store.test.ts b/packages/agent-tracing/src/store/file-store.test.ts
new file mode 100644
index 00000000000..3ac72a44e1f
--- /dev/null
+++ b/packages/agent-tracing/src/store/file-store.test.ts
@@ -0,0 +1,70 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import type { ExecutionSnapshot } from '../types';
+import { FileSnapshotStore } from './file-store';
+
+let root: string;
+
+const snapshot = (traceId: string): ExecutionSnapshot => ({
+ operationId: traceId,
+ startedAt: Date.now(),
+ steps: [],
+ totalCost: 0,
+ totalSteps: 0,
+ totalTokens: 0,
+ traceId,
+});
+
+beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'file-store-'));
+});
+
+afterEach(async () => {
+ await fs.rm(root, { force: true, recursive: true });
+});
+
+describe('FileSnapshotStore', () => {
+ it('defaults to a .agent-tracing directory under the root', async () => {
+ await new FileSnapshotStore(root).save(snapshot('trace_default'));
+
+ const entries = await fs.readdir(path.join(root, '.agent-tracing'));
+ expect(entries.some((entry) => entry.includes('trace_defau'))).toBe(true);
+ });
+
+ it('honours a custom directory name so a host can own its own layout', async () => {
+ const store = new FileSnapshotStore(root, 'traces');
+ await store.save(snapshot('trace_custom'));
+
+ const entries = await fs.readdir(path.join(root, 'traces'));
+ expect(entries.some((entry) => entry.includes('trace_custo'))).toBe(true);
+ // And nothing leaked into the default location.
+ await expect(fs.readdir(path.join(root, '.agent-tracing'))).rejects.toThrow();
+ expect(await store.get('trace_custom')).toMatchObject({ traceId: 'trace_custom' });
+ });
+
+ it('writes partials atomically, leaving no temp file behind', async () => {
+ const store = new FileSnapshotStore(root, 'traces');
+ await store.savePartial('op_1', { operationId: 'op_1', steps: [] });
+
+ const entries = await fs.readdir(path.join(root, 'traces', '_partial'));
+ expect(entries).toEqual(['op_1.json']);
+ expect(await store.loadPartial('op_1')).toMatchObject({ operationId: 'op_1' });
+ });
+
+ it('still saves the snapshot when the latest symlink cannot be written', async () => {
+ const store = new FileSnapshotStore(root, 'traces');
+ await store.save(snapshot('trace_a'));
+
+ // A directory at `latest.json` makes both unlink and symlink fail β€” the
+ // stand-in for two runs racing on the pointer. The snapshot must survive.
+ await fs.rm(path.join(root, 'traces', 'latest.json'));
+ await fs.mkdir(path.join(root, 'traces', 'latest.json'));
+
+ await expect(store.save(snapshot('trace_b'))).resolves.toBeUndefined();
+ expect(await store.get('trace_b')).toMatchObject({ traceId: 'trace_b' });
+ });
+});
diff --git a/packages/agent-tracing/src/store/file-store.ts b/packages/agent-tracing/src/store/file-store.ts
index 11757208053..785d5f36cde 100644
--- a/packages/agent-tracing/src/store/file-store.ts
+++ b/packages/agent-tracing/src/store/file-store.ts
@@ -10,8 +10,14 @@ const PARTIAL_DIR = '_partial';
export class FileSnapshotStore implements ISnapshotStore {
private dir: string;
- constructor(rootDir?: string) {
- this.dir = path.resolve(rootDir ?? process.cwd(), DEFAULT_DIR);
+ /**
+ * @param rootDir Directory `dirName` resolves against. Defaults to the cwd.
+ * @param dirName Leaf directory holding the snapshots. Overridable so a host
+ * that owns its own layout (the CLI writes to `~/.lobehub/traces`) does not
+ * end up with a nested hidden `.agent-tracing/` inside it.
+ */
+ constructor(rootDir?: string, dirName: string = DEFAULT_DIR) {
+ this.dir = path.resolve(rootDir ?? process.cwd(), dirName);
}
// ==================== Completed snapshots ====================
@@ -26,14 +32,20 @@ export class FileSnapshotStore implements ISnapshotStore {
await fs.writeFile(filePath, JSON.stringify(snapshot, null, 2), 'utf8');
- // Update latest symlink
+ // Update latest symlink. Best-effort convenience pointer: two runs
+ // finishing at once race between the unlink and the symlink, and losing
+ // that race must not throw away an already-written snapshot.
const latestPath = path.join(this.dir, 'latest.json');
try {
await fs.unlink(latestPath);
} catch {
// ignore if doesn't exist
}
- await fs.symlink(filename, latestPath);
+ try {
+ await fs.symlink(filename, latestPath);
+ } catch {
+ // ignore β€” `getLatest` falls back to the newest file by name
+ }
}
async get(traceId: string): Promise<ExecutionSnapshot | null> {
@@ -140,9 +152,26 @@ export class FileSnapshotStore implements ISnapshotStore {
}
}
+ /**
+ * Write the in-progress snapshot atomically (temp file + rename).
+ *
+ * A partial exists precisely so a killed process can be recovered from it, so
+ * it must never be observed half-written β€” a plain `writeFile` interrupted by
+ * `SIGKILL` leaves truncated JSON, which fails to parse at exactly the moment
+ * the file is needed. `rename` within one directory is atomic.
+ */
async savePartial(operationId: string, partial: Partial<ExecutionSnapshot>): Promise<void> {
await fs.mkdir(this.partialDir(), { recursive: true });
- await fs.writeFile(this.partialPath(operationId), JSON.stringify(partial), 'utf8');
+ const target = this.partialPath(operationId);
+ const tmp = `${target}.${process.pid}.tmp`;
+
+ try {
+ await fs.writeFile(tmp, JSON.stringify(partial), 'utf8');
+ await fs.rename(tmp, target);
+ } catch (error) {
+ await fs.unlink(tmp).catch(() => {});
+ throw error;
+ }
}
async removePartial(operationId: string): Promise<void> {
diff --git a/packages/agent-tracing/src/store/loadSnapshot.ts b/packages/agent-tracing/src/store/loadSnapshot.ts
index 72c63612dcf..fc98736fab7 100644
--- a/packages/agent-tracing/src/store/loadSnapshot.ts
+++ b/packages/agent-tracing/src/store/loadSnapshot.ts
@@ -11,6 +11,11 @@ export interface LoadSnapshotOptions {
* `_remote/` cache. Off by default so read-only callers never hit network.
*/
allowDownload?: boolean;
+ /**
+ * Leaf directory holding the snapshots, resolved against `rootDir`. Defaults
+ * to `.agent-tracing`; the CLI passes its own (`~/.lobehub/traces`).
+ */
+ dirName?: string;
/**
* Resolve the download URL for an operation id, instead of building one from
* `TRACING_BASE_URL`. Lets an authenticated caller (`lh`) reach the object
@@ -20,7 +25,7 @@ export interface LoadSnapshotOptions {
* back to `TRACING_BASE_URL`.
*/
resolveDownloadUrl?: (operationId: string) => Promise<string | null>;
- /** Root that `.agent-tracing/` resolves against. Defaults to `process.cwd()`. */
+ /** Root that the snapshot directory resolves against. Defaults to `process.cwd()`. */
rootDir?: string;
}
@@ -64,7 +69,7 @@ export async function loadSnapshot(
target?: string,
options: LoadSnapshotOptions = {},
): Promise<ExecutionSnapshot | undefined> {
- const { allowDownload = false, resolveDownloadUrl, rootDir } = options;
+ const { allowDownload = false, dirName, resolveDownloadUrl, rootDir } = options;
if (target?.endsWith('.json') && !isUrl(target)) {
return JSON.parse(await readFile(target, 'utf8')) as ExecutionSnapshot;
@@ -80,7 +85,7 @@ export async function loadSnapshot(
return (await res.json()) as ExecutionSnapshot;
}
- const local = await new FileSnapshotStore(rootDir).get(target ?? 'latest');
+ const local = await new FileSnapshotStore(rootDir, dirName).get(target ?? 'latest');
if (local) return local;
if (!target) return undefined;