π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(cli): `lh trace op` β inspect and replay a recorded operation, single call or whole trajectory (#18797)
Arvin Xu77be8bb286e4
diff --git a/.agents/skills/agent-tracing/SKILL.md b/.agents/skills/agent-tracing/SKILL.mdindex 08bb8979626..8082d0bd012 100644--- a/.agents/skills/agent-tracing/SKILL.md+++ b/.agents/skills/agent-tracing/SKILL.md@@ -46,31 +46,34 @@ packages/agent-tracing/## Remote Traces (Production / Staging)-Server deployments also upload completed snapshots to object storage (zstd-compressed; the key is stored in `agent_operations.trace_s3_key`). `agent-tracing inspect <operationId>` transparently downloads, decompresses, and caches them β no manual S3 access needed.+Server deployments also upload completed snapshots to object storage (zstd-compressed; the key is stored in `agent_operations.trace_s3_key`).-1. **Find the operation id** from a business id (users usually hand you a topic id):+**Preferred: `lh trace op`.** The server resolves the key and signs the object for the caller's own scope, so a LobeHub login is the only requirement β no `TRACING_BASE_URL`, no bucket domain, and no SQL to turn a topic id into an operation id:- ```sql- SELECT id, trace_s3_key FROM agent_operations WHERE topic_id = 'tpc_xxx';- ```+```bash+lh trace op list --topic tpc_xxx # operations of a topic, newest first, with a TRACE column+lh trace op inspect op_xxx_agt_xxx_tpc_xxx_xxxx+lh trace op inspect op_xxx_agt_xxx_tpc_xxx_xxxx -T # tool injection (enabledToolIds, manifests)+```++`TRACE = β` in `list` means no snapshot was recorded for that run (it predates trace upload, or upload was off). A recorded snapshot can still 404 in storage after its retention window.- `trace_s3_key IS NULL` means no snapshot was recorded; a non-null key can still 404 in storage (retention/TTL).+Backend: the `agentTrace` lambda router (`getSnapshotUrl` / `listOperations`). Note it is `blocked` for restricted API keys, so these commands need a real session, not a scoped key.-2. **Configure the base URL** β the bucket's public domain plus the `/agent-traces` prefix β either way:+**Fallback: the standalone `agent-tracing` CLI.** It has no LobeHub session, so it builds the object URL itself and needs the bucket's public domain configured:- - env var: `TRACING_BASE_URL=https://<bucket-public-domain>/agent-traces`- - file: `.agent-tracing/.env` in the repo root containing the same `TRACING_BASE_URL=...` line+- env var: `TRACING_BASE_URL=https://<bucket-public-domain>/agent-traces`+- or `.agent-tracing/.env` in the repo root with the same `TRACING_BASE_URL=...` line- The deployment-specific value is private to each deployment and intentionally not recorded in this repo.+The deployment-specific value is private to each deployment and intentionally not recorded in this repo. Find the operation id by hand first:-3. **Inspect by operation id** β auto-detected by the `op_..._agt_..._tpc_...` shape; the snapshot is cached to `.agent-tracing/_remote/<opId>.json` and every `inspect` flag works the same as for local traces:+```sql+SELECT id, trace_s3_key FROM agent_operations WHERE topic_id = 'tpc_xxx';+```- ```bash- agent-tracing inspect op_xxx_agt_xxx_tpc_xxx_xxxx # step tree of a production run- agent-tracing inspect op_xxx_agt_xxx_tpc_xxx_xxxx -T # tool injection (enabledToolIds, manifests)- ```+Either way the snapshot is cached to `.agent-tracing/_remote/<opId>.json`, and every `inspect` flag works the same as for local traces.-Implementation: `packages/agent-tracing/src/store/remote-store.ts` (URL is built from the operation id as `{base}/{agentId}/{topicId}/{opId}.json.zst`).+Implementation: `packages/agent-tracing/src/store/loadSnapshot.ts` (resolution order: local store β `_remote/` cache β injected `resolveDownloadUrl` β `TRACING_BASE_URL`) and `store/remote-store.ts` (URL built as `{base}/{agentId}/{topicId}/{opId}.json.zst`). Reading a compressed snapshot needs Node >= 22.15.## CLI Commands@@ -138,8 +141,63 @@ agent-tracing ctx-mapagent-tracing ctx-map <operationId|traceId|path.json>agent-tracing ctx-map --html # standalone report under .agent-tracing/_reports/agent-tracing ctx-map --html out.html++# Re-issue a recorded LLM call against other models (see "replay" below)+agent-tracing replay <operationId|traceId|path.json>+agent-tracing replay <target> -s 4 -m openai/gpt-5,anthropic/claude-sonnet-5+agent-tracing replay <target> --all-steps+```++## replay β Re-issue a Frozen Call++A snapshot already freezes everything one LLM call saw: `steps[].contextEngine.output` is the+exact message array sent to the model, `context.payload.tools` the toolset it could reach.+`replay` sends that frozen payload back out with only the model swapped, so a difference in+output is attributable to the model rather than to context assembly. If every model fails the+same payload, the context is at fault; if some pass, it is model selection.++Available from both CLIs β `agent-tracing replay` (reads `LOBEHUB_JWT`) and `lh trace op replay`+(uses the `lh login` session). Both need credentials because the call goes out through the+LobeHub chat route.++```bash+# One call: defaults to the last call_llm step and the model the op ran on+lh trace op replay <operationId>+lh trace op replay <operationId> -s 4 -m openai/gpt-5,anthropic/claude-sonnet-5+lh trace op replay <operationId> --judge "answers with a concrete file path"++# Every call of the operation+lh trace op replay <operationId> --all-steps+lh trace op replay <operationId> --all-steps --concurrency 8```+`--all-steps` answers the question the whole feature exists for: **take a run that succeeded, put+another model on it, and see whether that model also gets the job done.** It ends in a PASS / FAIL+verdict from an llm-rubric judge comparing the replayed outcome against the recorded one; pass+`--judge "<criteria>"` to define success yourself instead of using the default rubric.++The judge scores the **outcome, not the route**. A model that solved the same problem by calling+different tools has passed. The per-call tool comparison (`toolSignature`) is reported underneath+as supporting evidence β where the run took another path β and never decides pass / fail. A final+call that never reached the model is a FAIL, not a missing verdict.++Each call is replayed independently, against the payload the harness actually built for it, so a+different answer at call 2 cannot contaminate call 4, a call that fails to reach the provider+costs only itself, and the calls go out concurrently (4 at a time by default).++Chaining the nodes β feeding each replayed output into the next β was built and then removed. A+trace cannot regenerate tool output, only hand back what was recorded, so the moment the model+deviates there is no ground truth left; the run then measures nothing while still looking like it+succeeded. Independent replay is the design, not a fallback.++Known limitation: **sampling parameters are not recorded.** The recorder stores the runtime step+context under `context.payload`, not the provider request body, so temperature, `top_p`,+`max_tokens`, penalties and reasoning config are absent from every trace written so far. Replays+use the server's current defaults for those. Model-to-model comparisons stay valid (every target+gets the same request); comparisons against the recorded output do not, for an operation that ran+with non-default settings. `--temperature` / `--max-tokens` override explicitly. The CLI prints a+`note` line whenever a replay is running without recorded parameters.+## ctx-map β Context Window Composition`ctx-map` renders one row per `call_llm` step: the messages that call sent to the model, splitdiff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 84d2608e7d5..0cc2b8589b9 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -32,10 +32,12 @@},"devDependencies": {"@lobechat/agent-gateway-client": "workspace:*",+ "@lobechat/agent-tracing": "workspace:*","@lobechat/const": "workspace:*","@lobechat/device-control": "workspace:*","@lobechat/device-gateway-client": "workspace:*","@lobechat/device-identity": "workspace:*",+ "@lobechat/eval-rubric": "workspace:*","@lobechat/heterogeneous-agents": "workspace:*","@lobechat/local-file-shell": "workspace:*","@lobechat/tool-runtime": "workspace:*",@@ -58,6 +60,9 @@"tsdown": "^0.21.10","typescript": "^6.0.3"},+ "engines": {+ "node": ">=22.15"+ },"publishConfig": {"access": "public","registry": "https://registry.npmjs.org"diff --git a/apps/cli/pnpm-workspace.yaml b/apps/cli/pnpm-workspace.yamlindex 3b888a29f2b..f23a2b34b8d 100644--- a/apps/cli/pnpm-workspace.yaml+++ b/apps/cli/pnpm-workspace.yaml@@ -1,5 +1,6 @@packages:- '../../packages/agent-gateway-client'+ - '../../packages/agent-tracing'- '../../packages/device-control'- '../../packages/device-sandbox'- '../../packages/device-gateway-client'@@ -9,6 +10,7 @@ packages:- '../../packages/tool-runtime'- '../../packages/prompts'- '../../packages/const'+ - '../../packages/eval-rubric'- '../../packages/types'- '../../packages/model-bank'- '../../packages/ssrf-safe-fetch'diff --git a/apps/cli/src/commands/trace/index.ts b/apps/cli/src/commands/trace/index.tsnew file mode 100644index 00000000000..94246adb627--- /dev/null+++ b/apps/cli/src/commands/trace/index.ts@@ -0,0 +1,11 @@+import type { Command } from 'commander';++import { registerOpCommand } from './op';++export function registerTraceCommand(program: Command) {+ const trace = program+ .command('trace')+ .description('Inspect and replay recorded agent execution traces');++ registerOpCommand(trace);+}diff --git a/apps/cli/src/commands/trace/op/index.ts b/apps/cli/src/commands/trace/op/index.tsnew file mode 100644index 00000000000..c9511c49e8b--- /dev/null+++ b/apps/cli/src/commands/trace/op/index.ts@@ -0,0 +1,17 @@+import type { Command } from 'commander';++import { registerOpInspectCommand } from './inspect';+import { registerOpListCommand } from './list';+import { registerOpReplayCommand } from './replay';++/**+ * `lh trace op` β traces of a single agent operation. Sibling scopes (goal,+ * task) get their own group under `lh trace` rather than more flags here.+ */+export function registerOpCommand(parent: Command) {+ const op = parent.command('op').description('Traces of a single agent operation');++ registerOpInspectCommand(op);+ registerOpListCommand(op);+ registerOpReplayCommand(op);+}diff --git a/apps/cli/src/commands/trace/op/inspect.ts b/apps/cli/src/commands/trace/op/inspect.tsnew file mode 100644index 00000000000..6e706b7cac3--- /dev/null+++ b/apps/cli/src/commands/trace/op/inspect.ts@@ -0,0 +1,41 @@+import { InspectError, type InspectOptions, inspectSnapshot } from '@lobechat/agent-tracing';+import type { Command } from 'commander';++import { log } from '../../../utils/logger';+import { resolveSnapshotOrExit } from './snapshot';++export function registerOpInspectCommand(parent: Command) {+ parent+ .command('inspect')+ .alias('i')+ .description('Inspect a recorded operation: steps, messages, tools, context engine input')+ .argument('[target]', 'Operation id, trace id, snapshot json path, URL, or "latest"')+ .option('-s, --step <n>', 'View specific step (default: 0 for -r/--env)')+ .option('-m, --messages', 'Show messages context')+ .option('-t, --tools', 'Show tool call details')+ .option('-e, --events', 'Show raw events (llm_start, llm_result, etc.)')+ .option('-c, --context', 'Show runtime context & payload')+ .option('--msg <n>', 'Show full content of message [N] from Final LLM Payload')+ .option('--msg-input <n>', 'Show full content of message [N] from Context Engine Input')+ .option('-r, --system-role', 'Show full system role content (default step 0)')+ .option('--env', 'Show environment context (default step 0)')+ .option('-d, --diff <n>', 'Diff against step N (use with -r or --env)')+ .option('-T, --payload-tools', 'List available tools registered in LLM payload')+ .option('-M, --memory', 'Show full user memory content (default step 0)')+ .option('-S, --agent-signal', 'Show local agent-signal chain analysis')+ .option('-p, --payload', 'Show context engine input overview')+ .option('-j, --json', 'Output as JSON')+ .action(async (target: string | undefined, opts: InspectOptions) => {+ const snapshot = await resolveSnapshotOrExit(target);++ try {+ console.log(inspectSnapshot(snapshot, opts));+ } catch (error) {+ if (error instanceof InspectError) {+ log.error(error.message);+ process.exit(1);+ }+ throw error;+ }+ });+}diff --git a/apps/cli/src/commands/trace/op/list.ts b/apps/cli/src/commands/trace/op/list.tsnew file mode 100644index 00000000000..c0ddd47ec78--- /dev/null+++ b/apps/cli/src/commands/trace/op/list.ts@@ -0,0 +1,85 @@+import { FileSnapshotStore, renderSummaryTable } from '@lobechat/agent-tracing';+import type { Command } from 'commander';+import { InvalidArgumentError } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../../api/client';+import { printTable, timeAgo } from '../../../utils/format';+import { log } from '../../../utils/logger';++const DEFAULT_LIMIT = 10;++/**+ * Shape of one `agentTrace.listOperations` row. Declared locally because the+ * CLI's standalone `tsc` run cannot resolve the `@/server/routers/lambda` path+ * alias, so TRPC results widen to `any` here (same reason `topic/view.ts`+ * declares its own row types).+ */+interface TopicOperation {+ createdAt: Date | string | null;+ hasTrace: boolean;+ id: string;+ model: string | null;+ status: string;+ stepCount: number | null;+}++/**+ * Server-side listing for `--topic`: turns the id a user actually has on hand+ * (a topic) into the operation ids their traces are keyed by, which previously+ * meant querying `agent_operations` by hand. `Trace` says whether a snapshot+ * exists to inspect at all β a run recorded before trace upload, or one whose+ * object has expired, has none.+ */+const listByTopic = async (topicId: string, limit: number, json?: boolean) => {+ const client = await getTrpcClient();+ const { data } = await client.agentTrace.listOperations.query({ limit, topicId });++ if (json) {+ console.log(JSON.stringify(data, null, 2));+ return;+ }++ if (data.length === 0) {+ log.info(`No operations recorded for topic ${topicId}.`);+ return;+ }++ printTable(+ (data as TopicOperation[]).map((operation) => [+ operation.id,+ operation.status,+ operation.hasTrace ? pc.green('yes') : pc.dim('β'),+ operation.model ?? '-',+ operation.stepCount == null ? '-' : String(operation.stepCount),+ operation.createdAt ? timeAgo(operation.createdAt) : '-',+ ]),+ ['OPERATION', 'STATUS', 'TRACE', 'MODEL', 'STEPS', 'AGE'],+ );+};++export function registerOpListCommand(parent: Command) {+ parent+ .command('list')+ .alias('ls')+ .description('List recorded operation snapshots (locally, or by topic from the server)')+ .option('--topic <topicId>', 'List the operations recorded for a topic instead of local files')+ .option('-l, --limit <n>', 'Number of snapshots to list', (value) => {+ const parsed = Number.parseInt(value, 10);+ if (!Number.isFinite(parsed)) throw new InvalidArgumentError('--limit must be an integer');+ return parsed;+ })+ .option('-j, --json', 'Output as JSON')+ .action(async (opts: { json?: boolean; limit?: number; topic?: string }) => {+ const limit = opts.limit ?? DEFAULT_LIMIT;++ if (opts.topic) {+ await listByTopic(opts.topic, limit, opts.json);+ return;+ }++ const summaries = await new FileSnapshotStore().list({ limit });++ console.log(opts.json ? JSON.stringify(summaries, null, 2) : renderSummaryTable(summaries));+ });+}diff --git a/apps/cli/src/commands/trace/op/replay.ts b/apps/cli/src/commands/trace/op/replay.tsnew file mode 100644index 00000000000..83dec395a62--- /dev/null+++ b/apps/cli/src/commands/trace/op/replay.ts@@ -0,0 +1,287 @@+import {+ type ExecutionSnapshot,+ type FrozenCall,+ judgeReplay,+ listFrozenCalls,+ listReplayableSteps,+ type ModelTarget,+ parseModelTargets,+ type ReplayAttempt,+ type ReplayConnection,+ replayFrozenCall,+ replayTrajectory,+ selectFrozenCall,+} from '@lobechat/agent-tracing';+import type { Command } from 'commander';+import { InvalidArgumentError } from 'commander';+import pc from 'picocolors';++import { getAuthInfo } from '../../../api/http';+import { log } from '../../../utils/logger';+import { resolveSnapshotOrExit } from './snapshot';+import { printTrajectorySummary, TrajectoryStrip } from './trajectoryView';++const DEFAULT_JUDGE_MODEL = 'openai/gpt-4o-mini';++const parseIntOption = (name: string) => (value: string) => {+ const parsed = Number.parseInt(value, 10);+ if (!Number.isFinite(parsed)) throw new InvalidArgumentError(`${name} must be an integer`);+ return parsed;+};++const parseFloatOption = (name: string) => (value: string) => {+ const parsed = Number.parseFloat(value);+ if (!Number.isFinite(parsed)) throw new InvalidArgumentError(`${name} must be a number`);+ return parsed;+};++export function registerOpReplayCommand(parent: Command) {+ parent+ .command('replay')+ .description('Re-issue a frozen LLM call from a recorded operation against one or more models')+ .argument('[target]', 'Operation id, trace id, snapshot json path, URL, or "latest"')+ .option(+ '-s, --step <n>',+ 'Snapshot step index to replay (default: the last call_llm step)',+ parseIntOption('--step'),+ )+ .option(+ '-m, --model <list>',+ 'Comma-separated provider/model targets (default: the model the operation ran on)',+ )+ .option(+ '--all-steps',+ 'Replay every call of the operation, each against its own recorded payload',+ )+ .option(+ '--concurrency <n>',+ 'How many calls to replay at once with --all-steps',+ parseIntOption('--concurrency'),+ )+ .option('--judge <criteria>', 'Score every replayed output with an llm-rubric criteria')+ .option('--judge-model <model>', 'Judge model as provider/model', DEFAULT_JUDGE_MODEL)+ .option('--no-tools', 'Drop tool definitions from the replayed payload')+ .option('--temperature <n>', 'Override temperature', parseFloatOption('--temperature'))+ .option('--max-tokens <n>', 'Override max output tokens', parseIntOption('--max-tokens'))+ .option('--json', 'Output JSON')+ .action(+ async (+ target: string | undefined,+ options: {+ allSteps?: boolean;+ concurrency?: number;+ json?: boolean;+ judge?: string;+ judgeModel: string;+ maxTokens?: number;+ model?: string;+ step?: number;+ temperature?: number;+ tools: boolean;+ },+ ) => {+ const snapshot = await resolveSnapshotOrExit(target);+ const allSteps = Boolean(options.allSteps);++ if (allSteps && options.step !== undefined) {+ log.error('--step replays a single call; drop it to replay every call.');+ process.exit(1);+ return;+ }++ const call = allSteps ? undefined : selectFrozenCall(snapshot, options.step);++ if (!allSteps && !call) {+ const steps = listReplayableSteps(snapshot);+ log.error(+ options.step === undefined+ ? 'Snapshot has no call_llm step with a recorded payload β nothing to replay.'+ : `Step ${options.step} is not a replayable call_llm step. Available: ${steps.join(', ') || '(none)'}`,+ );+ process.exit(1);+ return;+ }++ let targets: ModelTarget[];+ let judgeModel: ModelTarget | undefined;+ try {+ targets = options.model+ ? parseModelTargets(options.model, snapshot.provider)+ : originalTarget(snapshot);+ // Replaying every call always ends in a pass / fail verdict, so it+ // needs a judge even when no explicit criteria was given.+ judgeModel =+ options.judge || allSteps ? parseModelTargets(options.judgeModel)[0] : undefined;+ } catch (error) {+ log.error(error instanceof Error ? error.message : String(error));+ process.exit(1);+ return;+ }++ const { serverUrl, headers } = await getAuthInfo();+ const connection: ReplayConnection = { headers, serverUrl };++ if (allSteps) {+ if (targets.length > 1) {+ log.error('Replaying every call runs one model at a time β pass a single --model.');+ process.exit(1);+ return;+ }++ const strip = options.json+ ? undefined+ : new TrajectoryStrip(listReplayableSteps(snapshot).length);++ if (!options.json) {+ printTrajectoryHeader(snapshot, targets[0]);+ strip?.start();+ }++ const result = await replayTrajectory({+ concurrency: options.concurrency,+ connection,+ maxTokens: options.maxTokens,+ onNode: (node) => strip?.settle(node),+ verdictJudge: judgeModel ? { criteria: options.judge, judgeModel } : undefined,+ snapshot,+ target: targets[0],+ temperature: options.temperature,+ withTools: options.tools,+ });++ if (options.json) {+ console.log(JSON.stringify({ ...result, operationId: snapshot.operationId }, null, 2));+ } else {+ printTrajectorySummary(result);+ }+ return;+ }++ if (!call) return;++ if (!options.json) printHeader(snapshot, call, targets);++ const attempts: ReplayAttempt[] = [];+ for (const modelTarget of targets) {+ const attempt = await replayFrozenCall({+ call,+ connection,+ maxTokens: options.maxTokens,+ target: modelTarget,+ temperature: options.temperature,+ withTools: options.tools,+ });++ if (options.judge && judgeModel && !attempt.error) {+ attempt.judge = await judgeReplay({+ actual: attempt.content,+ connection,+ criteria: options.judge,+ judgeModel,+ });+ }++ attempts.push(attempt);+ if (!options.json) printAttempt(attempt);+ }++ if (options.json) {+ console.log(+ JSON.stringify(+ {+ attempts,+ operationId: snapshot.operationId,+ originalModel: snapshot.model,+ stepIndex: call.stepIndex,+ },+ null,+ 2,+ ),+ );+ }+ },+ );+}++const originalTarget = (snapshot: ExecutionSnapshot): ModelTarget[] => {+ if (!snapshot.model || !snapshot.provider) {+ throw new Error(+ 'Snapshot does not record a model/provider β pass targets explicitly with --model provider/model',+ );+ }+ return [+ {+ label: `${snapshot.provider}/${snapshot.model}`,+ model: snapshot.model,+ provider: snapshot.provider,+ },+ ];+};++/**+ * Traces do not record sampling parameters, so a replay runs at the server's+ * current defaults for them. Say so where the comparison is set up, rather than+ * letting a run that used non-default temperature or reasoning settings read as+ * a clean model-to-model comparison. Disappears once a trace carries them.+ */+const printParamsCaveat = (call?: FrozenCall) => {+ if (call?.params && Object.keys(call.params).length > 0) return;+ console.log(pc.dim(' note sampling params are not recorded; replay uses server defaults'));+};++const printTrajectoryHeader = (snapshot: ExecutionSnapshot, target: ModelTarget) => {+ console.log(pc.bold('Per-node replay'));+ console.log(` operation ${snapshot.operationId}`);+ console.log(` recorded ${snapshot.provider ?? '?'}/${snapshot.model ?? '?'}`);+ console.log(` target ${target.label}`);+ printParamsCaveat(listFrozenCalls(snapshot)[0]);+ console.log('');+};++const printHeader = (snapshot: ExecutionSnapshot, call: FrozenCall, targets: ModelTarget[]) => {+ console.log(pc.bold('Replaying frozen call'));+ console.log(` operation ${snapshot.operationId}`);+ console.log(` recorded ${snapshot.provider ?? '?'}/${snapshot.model ?? '?'}`);+ console.log(+ ` step ${call.stepIndex} β ${call.messages.length} messages, ${call.tools?.length ?? 0} tools`,+ );+ console.log(` targets ${targets.map((t) => t.label).join(', ')}`);+ printParamsCaveat(call);+ console.log('');+};++const printAttempt = (attempt: ReplayAttempt) => {+ console.log(pc.bold(pc.cyan(`ββ ${attempt.model}`)));++ if (attempt.error) {+ console.log(pc.red(` error: ${attempt.error}`));+ console.log('');+ return;+ }++ const meta = [+ `${attempt.durationMs}ms`,+ attempt.usage?.promptTokens === undefined ? undefined : `in ${attempt.usage.promptTokens}`,+ attempt.usage?.completionTokens === undefined+ ? undefined+ : `out ${attempt.usage.completionTokens}`,+ ]+ .filter(Boolean)+ .join(' ');+ console.log(pc.dim(` ${meta}`));++ if (attempt.judge) {+ const verdict = attempt.judge.passed ? pc.green('PASS') : pc.red('FAIL');+ console.log(+ ` ${verdict} ${attempt.judge.score.toFixed(2)} ${pc.dim(attempt.judge.reason ?? '')}`,+ );+ }++ for (const toolCall of attempt.toolCalls) {+ console.log(pc.yellow(` β ${toolCall.name}(${toolCall.arguments ?? ''})`));+ }++ console.log('');+ console.log(attempt.content || pc.dim('(empty response)'));+ console.log('');+};diff --git a/apps/cli/src/commands/trace/op/snapshot.ts b/apps/cli/src/commands/trace/op/snapshot.tsnew file mode 100644index 00000000000..1072f302206--- /dev/null+++ b/apps/cli/src/commands/trace/op/snapshot.ts@@ -0,0 +1,69 @@+import {+ AmbiguousSnapshotIdError,+ type ExecutionSnapshot,+ loadSnapshot,+ MissingTracingBaseUrlError,+} from '@lobechat/agent-tracing';+import { TRPCClientError } from '@trpc/client';++import { getTrpcClient } from '../../../api/client';+import { log } from '../../../utils/logger';++/**+ * Resolve the snapshot a `lh trace op` subcommand was pointed at, or exit with+ * a message that says what to do about it.+ *+ * The download path is what `lh` adds over the standalone `agent-tracing` CLI:+ * the object key lives on `agent_operations.trace_s3_key` and the server signs+ * it against the caller's own ownership scope, so inspecting a production run+ * needs a LobeHub login and nothing else β no `TRACING_BASE_URL`, no public+ * bucket domain, and no SQL to turn a topic id into an operation id first.+ */+export const resolveSnapshotOrExit = async (target?: string): Promise<ExecutionSnapshot> => {+ // Why the server declined to sign, kept so the final message can say+ // "no trace recorded" instead of blaming a missing env var.+ let serverReason: string | undefined;++ const resolveDownloadUrl = async (operationId: string): Promise<string | null> => {+ const client = await getTrpcClient();++ try {+ const { data } = await client.agentTrace.getSnapshotUrl.query({ operationId });+ return data.url;+ } catch (error) {+ // NOT_FOUND means the operation is absent, outside the caller's scope, or+ // recorded no trace β all "nothing to download", so fall through to any+ // locally configured TRACING_BASE_URL. Anything else (auth, network, a+ // signing failure) is a real problem and must not be silently swallowed.+ if (error instanceof TRPCClientError && error.data?.code === 'NOT_FOUND') {+ serverReason = error.message;+ return null;+ }+ throw error;+ }+ };++ try {+ const snapshot = await loadSnapshot(target, { allowDownload: true, resolveDownloadUrl });+ if (snapshot) return snapshot;+ log.error(+ target+ ? `No snapshot found for "${target}".`+ : 'No local snapshots found. Run an agent operation first, or pass an operation id.',+ );+ } catch (error) {+ if (error instanceof MissingTracingBaseUrlError) {+ log.error(+ serverReason+ ? `${serverReason}\n` ++ 'Run `lh trace op list --topic <topicId>` to see which operations still have a trace.'+ : error.message,+ );+ } else if (error instanceof AmbiguousSnapshotIdError) {+ log.error(error.message);+ } else {+ log.error(error instanceof Error ? error.message : String(error));+ }+ }+ process.exit(1);+};diff --git a/apps/cli/src/commands/trace/op/trajectoryView.ts b/apps/cli/src/commands/trace/op/trajectoryView.tsnew file mode 100644index 00000000000..a4f939d8f7c--- /dev/null+++ b/apps/cli/src/commands/trace/op/trajectoryView.ts@@ -0,0 +1,173 @@+import type { TrajectoryNode, TrajectoryResult } from '@lobechat/agent-tracing';+import pc from 'picocolors';++/**+ * One glyph per LLM call, left to right in call order.+ *+ * A different tool route is drawn neutral, not as a warning: the replay asks+ * whether another model gets the job done, and a model that solved the same+ * problem by calling different tools has not done anything wrong. Only a call+ * that never reached the model is red. The pass / fail answer comes from the+ * judge, above.+ */+const GLYPH = { diverged: 'β', error: 'β', matched: 'β', pending: 'Β·' } as const;++type NodeState = keyof typeof GLYPH;++const stateOf = (node: TrajectoryNode | undefined): NodeState => {+ if (!node) return 'pending';+ if (node.attempt.error) return 'error';+ return node.divergence ? 'diverged' : 'matched';+};++const paint = (state: NodeState): string => {+ const glyph = GLYPH[state];+ if (state === 'matched') return pc.green(glyph);+ if (state === 'diverged') return pc.cyan(glyph);+ if (state === 'error') return pc.red(glyph);+ return pc.dim(glyph);+};++const GROUP = 10;+const PER_ROW = 50;++/**+ * Render the strip as rows of `PER_ROW` glyphs, grouped in tens so a node can+ * be counted off by eye, each row labelled with the call number it starts at.+ */+const stripRows = (states: NodeState[]): string[] => {+ const rows: string[] = [];+ // The call-number gutter only earns its space once the strip wraps.+ const numbered = states.length > PER_ROW;++ for (let start = 0; start < states.length; start += PER_ROW) {+ const slice = states.slice(start, start + PER_ROW);+ const groups: string[] = [];+ for (let at = 0; at < slice.length; at += GROUP) {+ groups.push(+ slice+ .slice(at, at + GROUP)+ .map((state) => paint(state))+ .join(''),+ );+ }+ const gutter = numbered ? `${String(start + 1).padStart(4)} ` : '';+ rows.push(` ${gutter}${groups.join(' ')}`);+ }++ return rows;+};++/**+ * Live strip: nodes settle out of order under concurrency, so each one is+ * painted where it belongs and the whole strip is redrawn in place. Falls back+ * to printing nothing until the summary when stdout is not a terminal, so piped+ * or captured output stays free of cursor escapes.+ */+export class TrajectoryStrip {+ private readonly states: NodeState[];+ private readonly live: boolean;+ private drawnRows = 0;++ constructor(totalNodes: number) {+ this.states = Array.from({ length: totalNodes }, () => 'pending' as NodeState);+ this.live = Boolean(process.stdout.isTTY) && totalNodes > 0;+ }++ settle(node: TrajectoryNode) {+ this.states[node.nodeIndex] = stateOf(node);+ this.draw();+ }++ /** Paint the initial all-pending strip so the run's length is visible up front. */+ start() {+ this.draw();+ }++ private draw() {+ if (!this.live) return;++ if (this.drawnRows > 0) {+ process.stdout.write(`\u001B[${this.drawnRows}A\u001B[0J`);+ }++ const rows = stripRows(this.states);+ process.stdout.write(`${rows.join('\n')}\n`);+ this.drawnRows = rows.length;+ }+}++/** Supporting detail for the calls that took another route or never answered. */+const printNodeDetail = (node: TrajectoryNode) => {+ const at = `call ${String(node.nodeIndex + 1).padStart(3)} ${pc.dim(`step ${node.stepIndex}`)}`;++ if (node.attempt.error) {+ console.log(` ${pc.red(GLYPH.error)} ${at} ${pc.red(node.attempt.error)}`);+ return;+ }++ const divergence = node.divergence;+ if (!divergence) return;++ console.log(+ ` ${pc.cyan(GLYPH.diverged)} ${at} ${pc.dim('recorded')} ${divergence.recorded || pc.dim('(final answer)')}` ++ ` ${pc.dim('β replayed')} ${divergence.replayed || pc.dim('(final answer)')}`,+ );+};++const wrap = (text: string, width: number, indent: string): string[] => {+ const words = text.split(/\s+/).filter(Boolean);+ const lines: string[] = [];+ let line = '';++ for (const word of words) {+ if (line && line.length + word.length + 1 > width) {+ lines.push(indent + line);+ line = word;+ } else {+ line = line ? `${line} ${word}` : word;+ }+ }+ if (line) lines.push(indent + line);++ return lines;+};++export const printTrajectorySummary = (result: TrajectoryResult) => {+ const total = result.nodes.length;+ const rerouted = result.nodes.filter((node) => node.divergence);+ const failed = result.nodes.filter((node) => node.attempt.error);+ const elapsed = result.nodes.reduce((sum, node) => sum + (node.attempt.durationMs ?? 0), 0);++ console.log('');++ // The verdict is the answer the replay was run to get, so it leads.+ if (result.verdict) {+ const { passed, reason, score } = result.verdict;+ const badge = passed ? pc.bold(pc.green('β PASS')) : pc.bold(pc.red('β FAIL'));+ console.log(` ${badge} ${pc.bold(score.toFixed(2))}`);+ if (reason) {+ console.log('');+ for (const line of wrap(reason, 76, ' ')) console.log(pc.dim(line));+ }+ } else {+ console.log(` ${pc.dim('no verdict β run with a judge model to get pass / fail')}`);+ }++ console.log('');+ console.log(+ pc.dim(+ ` ${total} calls Β· ${(elapsed / 1000).toFixed(1)}s Β· ` ++ `${total - rerouted.length - failed.length}/${total} took the recorded tool route`,+ ),+ );++ for (const row of stripRows(result.nodes.map((node) => stateOf(node)))) console.log(row);++ if (rerouted.length > 0 || failed.length > 0) {+ console.log('');+ for (const node of result.nodes) {+ if (node.divergence || node.attempt.error) printNodeDetail(node);+ }+ }+};diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex 695c18e17f0..059971eb9bc 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -33,6 +33,7 @@ import { registerStatusCommand } from './commands/status';import { registerTaskCommand } from './commands/task';import { registerThreadCommand } from './commands/thread';import { registerTopicCommand } from './commands/topic';+import { registerTraceCommand } from './commands/trace';import { registerUpdateCommand } from './commands/update';import { registerUserCommand } from './commands/user';import { registerVerifyCommand } from './commands/verify';@@ -94,6 +95,7 @@ export function createProgram() {registerTaskCommand(program);registerThreadCommand(program);registerTopicCommand(program);+ registerTraceCommand(program);registerMessageCommand(program);registerModelCommand(program);registerNotifyCommand(program);diff --git a/apps/cli/tsdown.config.ts b/apps/cli/tsdown.config.tsindex 3a17b9f4c2d..d23a3acad7c 100644--- a/apps/cli/tsdown.config.ts+++ b/apps/cli/tsdown.config.ts@@ -18,5 +18,7 @@ export default defineConfig({codeSplitting: false,},platform: 'node',- target: 'node18',+ // Matches the `engines.node` floor: reading a compressed trace snapshot needs+ // `node:zlib` zstd, which lands in 22.15. Node 20 went EOL in April 2026.+ target: 'node22',});diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yamlindex 9a9c8cb4aea..f61c7c64785 100644--- a/apps/desktop/pnpm-workspace.yaml+++ b/apps/desktop/pnpm-workspace.yaml@@ -1,9 +1,11 @@packages:- '../cli'- '../../packages/agent-gateway-client'+ - '../../packages/agent-tracing'- '../../packages/chat-adapter-imessage'- '../../packages/heterogeneous-agents'- '../../packages/const'+ - '../../packages/eval-rubric'- '../../packages/electron-server-ipc'- '../../packages/electron-client-ipc'- '../../packages/electron-mac-notifications'diff --git a/packages/agent-tracing/package.json b/packages/agent-tracing/package.jsonindex 8b0b8280921..a11c5bd0475 100644--- a/packages/agent-tracing/package.json+++ b/packages/agent-tracing/package.json@@ -5,7 +5,8 @@"exports": {".": "./src/index.ts","./store": "./src/store/types.ts",- "./recorder": "./src/recorder/index.ts"+ "./recorder": "./src/recorder/index.ts",+ "./replay": "./src/replay/index.ts"},"main": "./src/index.ts","bin": {@@ -16,6 +17,7 @@"test": "vitest run"},"dependencies": {+ "@lobechat/eval-rubric": "workspace:*","commander": "^13.1.0","gpt-tokenizer": "^3.4.0","model-bank": "workspace:*"diff --git a/packages/agent-tracing/src/cli/index.ts b/packages/agent-tracing/src/cli/index.tsindex 96c9f01a04e..dc846256b5f 100755--- a/packages/agent-tracing/src/cli/index.ts+++ b/packages/agent-tracing/src/cli/index.ts@@ -7,6 +7,7 @@ import { registerCtxMapCommand } from './ctx-map';import { registerInspectCommand } from './inspect';import { registerListCommand } from './list';import { registerPartialCommand } from './partial';+import { registerReplayCommand } from './replay';import { registerToolQualityCommand } from './tool-quality';const program = new Command();@@ -16,6 +17,7 @@ program.name('agent-tracing').description('Local agent execution snapshot viewerregisterInspectCommand(program);registerListCommand(program);registerPartialCommand(program);+registerReplayCommand(program);registerToolQualityCommand(program);registerCtxLintCommand(program);registerCtxMapCommand(program);diff --git a/packages/agent-tracing/src/cli/inspect.ts b/packages/agent-tracing/src/cli/inspect.tsindex f564ab490f0..98bc7b60b23 100644--- a/packages/agent-tracing/src/cli/inspect.ts+++ b/packages/agent-tracing/src/cli/inspect.ts@@ -1,71 +1,7 @@import type { Command } from 'commander';-import { FileSnapshotStore } from '../store/file-store';-import {- buildRemoteUrl,- isOperationId,- loadBaseUrl,- RemoteSnapshotStore,-} from '../store/remote-store';-import type { ExecutionSnapshot, StepSnapshot } from '../types';-import {- renderAgentSignal,- renderDiff,- renderEnvContext,- renderMemory,- renderMessageDetail,- renderPayload,- renderPayloadTools,- renderSnapshot,- renderStepDetail,- renderSystemRole,- resolveCeSnapshot,-} from '../viewer';--async function fetchSnapshotFromUrl(url: string): Promise<ExecutionSnapshot> {- const res = await fetch(url);- if (!res.ok) {- throw new Error(`Failed to fetch snapshot: ${res.status} ${res.statusText}`);- }- return (await res.json()) as ExecutionSnapshot;-}--function isUrl(input: string): boolean {- return input.startsWith('http://') || input.startsWith('https://');-}--function findStep(snapshot: ExecutionSnapshot, stepIndex: number): StepSnapshot {- const step = snapshot.steps.find((s) => s.stepIndex === stepIndex);- if (!step) {- console.error(- `Step ${stepIndex} not found. Available: ${snapshot.steps.map((s) => s.stepIndex).join(', ')}`,- );- process.exit(1);- }- return step;-}--function getSystemRole(step: StepSnapshot, allSteps?: StepSnapshot[]): string | undefined {- const ceEvent = resolveCeSnapshot(step, allSteps) as any;- const inputRole = ceEvent?.input?.systemRole;- if (inputRole) return inputRole;- const outputMsgs = ceEvent?.output as any[] | undefined;- const systemMsg = outputMsgs?.find((m: any) => m.role === 'system');- if (!systemMsg) return undefined;- return typeof systemMsg.content === 'string'- ? systemMsg.content- : JSON.stringify(systemMsg.content, null, 2);-}--function getEnvContent(step: StepSnapshot, allSteps?: StepSnapshot[]): string | undefined {- const ceEvent = resolveCeSnapshot(step, allSteps) as any;- const outputMsgs = ceEvent?.output as any[] | undefined;- const envMsg = outputMsgs?.find((m: any) => m.role === 'user');- if (!envMsg) return undefined;- return typeof envMsg.content === 'string'- ? envMsg.content- : JSON.stringify(envMsg.content, null, 2);-}+import { InspectError, type InspectOptions, inspectSnapshot } from '../inspect/inspectSnapshot';+import { loadSnapshot } from '../store/loadSnapshot';export function registerInspectCommand(program: Command) {program@@ -97,242 +33,32 @@ export function registerInspectCommand(program: Command) {'Show context engine input overview (knowledge, memory, capabilities, etc.)',).option('-j, --json', 'Output as JSON')- .action(- async (- traceId: string | undefined,- opts: {- agentSignal?: boolean;- context?: boolean;- diff?: string;- env?: boolean;- events?: boolean;- json?: boolean;- messages?: boolean;- msg?: string;- msgInput?: string;- memory?: boolean;- payload?: boolean;- payloadTools?: boolean;- step?: string;- systemRole?: boolean;- tools?: boolean;- },- ) => {- let snapshot: ExecutionSnapshot | null;-- if (traceId && isUrl(traceId)) {- snapshot = await fetchSnapshotFromUrl(traceId);- } else if (traceId && isOperationId(traceId)) {- // Try local store first, then fetch from remote- const fileStore = new FileSnapshotStore();- snapshot = await fileStore.get(traceId);- if (!snapshot) {- const remoteStore = new RemoteSnapshotStore();- const cached = await remoteStore.getCached(traceId);- if (cached) {- snapshot = cached;- console.error(`β Loaded from cache: _remote/${traceId}.json`);- } else {- const baseUrl = await loadBaseUrl();- if (!baseUrl) {- console.error(- 'Remote fetch requires TRACING_BASE_URL.\n' +- 'Set it via:\n' +- ' 1. Environment variable: export TRACING_BASE_URL=https://...\n' +- ' 2. File: .agent-tracing/.env with TRACING_BASE_URL=https://...',- );- process.exit(1);- }- const url = buildRemoteUrl(baseUrl, traceId);- if (!url) {- console.error(`Failed to parse operation ID: ${traceId}`);- process.exit(1);- }- snapshot = await remoteStore.fetch(url, traceId);- }- }- } else if (traceId && traceId.startsWith('op_')) {- // Partial op id (e.g. `op_<timestamp>`): first check the local- // FileSnapshotStore (which also covers `_partial/` in-progress- // snapshots via substring match), then fall back to a prefix scan- // of the `_remote/` cache so users don't have to paste the full- // `op_<ts>_agt_..._tpc_..._<suffix>` string.- const fileStore = new FileSnapshotStore();- snapshot = await fileStore.get(traceId);- if (!snapshot) {- const remoteStore = new RemoteSnapshotStore();- const matches = await remoteStore.findCachedByPrefix(traceId);- if (matches.length === 1) {- const fullId = matches[0];- snapshot = await remoteStore.getCached(fullId);- console.error(`β Resolved "${traceId}" β ${fullId}`);- } else if (matches.length > 1) {- console.error(`Ambiguous id prefix "${traceId}" β multiple cached snapshots match:`);- for (const m of matches) console.error(` ${m}`);- console.error('Re-run with the full operation id.');- process.exit(1);- }- }- } else {- const store = new FileSnapshotStore();- snapshot = traceId ? await store.get(traceId) : await store.getLatest();- }-- if (!snapshot) {- console.error(- traceId- ? `Snapshot not found: ${traceId}`- : 'No snapshots found. Run an agent operation first.',- );- process.exit(1);- }-- if (opts.agentSignal) {- if (opts.json) {- const { analyzeAgentSignal } = await import('../viewer/agentSignal');- console.log(JSON.stringify(analyzeAgentSignal(snapshot), null, 2));- } else {- console.log(renderAgentSignal(snapshot));- }- return;- }-- const stepIndex = opts.step !== undefined ? Number.parseInt(opts.step, 10) : undefined;-- // -r / --env / -T / -p default to step 0- const effectiveStepIndex =- stepIndex ??- (opts.systemRole || opts.env || opts.payloadTools || opts.payload || opts.memory- ? 0- : undefined);-- // --diff requires -r or --env- if (opts.diff !== undefined && !opts.systemRole && !opts.env) {- console.error('--diff requires -r or --env.');+ .action(async (traceId: string | undefined, opts: InspectOptions) => {+ let snapshot;+ try {+ snapshot = await loadSnapshot(traceId, { allowDownload: true });+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error));+ process.exit(1);+ }++ if (!snapshot) {+ console.error(+ traceId+ ? `Snapshot not found: ${traceId}`+ : 'No snapshots found. Run an agent operation first.',+ );+ process.exit(1);+ }++ try {+ console.log(inspectSnapshot(snapshot, opts));+ } catch (error) {+ if (error instanceof InspectError) {+ console.error(error.message);process.exit(1);}-- // --diff mode- if (opts.diff !== undefined && effectiveStepIndex !== undefined) {- const diffStepIndex = Number.parseInt(opts.diff, 10);- const stepA = findStep(snapshot, effectiveStepIndex);- const stepB = findStep(snapshot, diffStepIndex);- const label = opts.systemRole ? 'System Role' : 'Environment Context';- const contentA = opts.systemRole- ? getSystemRole(stepA, snapshot.steps)- : getEnvContent(stepA, snapshot.steps);- const contentB = opts.systemRole- ? getSystemRole(stepB, snapshot.steps)- : getEnvContent(stepB, snapshot.steps);- console.log(- renderDiff(contentA ?? '', contentB ?? '', {- labelA: `Step ${effectiveStepIndex}`,- labelB: `Step ${diffStepIndex}`,- title: label,- }),- );- return;- }-- // -r / --env view- if ((opts.systemRole || opts.env) && effectiveStepIndex !== undefined) {- const step = findStep(snapshot, effectiveStepIndex);- if (opts.json) {- if (opts.systemRole) {- console.log(JSON.stringify(getSystemRole(step, snapshot.steps) ?? null, null, 2));- } else {- const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;- const envMsg = (ceEvent?.output as any[])?.find((m: any) => m.role === 'user');- console.log(JSON.stringify(envMsg ?? null, null, 2));- }- } else {- console.log(- opts.systemRole- ? renderSystemRole(step, snapshot.steps)- : renderEnvContext(step, snapshot.steps),- );- }- return;- }-- // -T / --payload-tools view- if (opts.payloadTools && effectiveStepIndex !== undefined) {- const step = findStep(snapshot, effectiveStepIndex);- if (opts.json) {- const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;- const toolsConfig = ceEvent?.input?.toolsConfig;- const payloadTools = (step.context?.payload as any)?.tools;- console.log(JSON.stringify({ payloadTools, toolsConfig }, null, 2));- } else {- console.log(renderPayloadTools(step, snapshot.steps));- }- return;- }-- // -p / --payload view- if (opts.payload && effectiveStepIndex !== undefined) {- const step = findStep(snapshot, effectiveStepIndex);- if (opts.json) {- const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;- console.log(JSON.stringify(ceEvent?.input ?? null, null, 2));- } else {- console.log(renderPayload(step, snapshot.steps));- }- return;- }-- // -M / --memory view- if (opts.memory && effectiveStepIndex !== undefined) {- const step = findStep(snapshot, effectiveStepIndex);- if (opts.json) {- const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;- console.log(JSON.stringify(ceEvent?.input?.userMemory ?? null, null, 2));- } else {- console.log(renderMemory(step, snapshot.steps));- }- return;- }-- if (opts.json) {- if (stepIndex !== undefined) {- const step = findStep(snapshot, stepIndex);- console.log(JSON.stringify(step, null, 2));- } else {- console.log(JSON.stringify(snapshot, null, 2));- }- return;- }-- // --msg or --msg-input: show full message detail- const msgIndex =- opts.msg !== undefined- ? Number.parseInt(opts.msg, 10)- : opts.msgInput !== undefined- ? Number.parseInt(opts.msgInput, 10)- : undefined;- const msgSource: 'input' | 'output' = opts.msgInput !== undefined ? 'input' : 'output';-- if (stepIndex !== undefined) {- const step = findStep(snapshot, stepIndex);-- if (msgIndex !== undefined) {- console.log(renderMessageDetail(step, msgIndex, msgSource, snapshot.steps));- return;- }-- console.log(- renderStepDetail(step, {- allSteps: snapshot.steps,- context: opts.context,- events: opts.events,- messages: opts.messages,- tools: opts.tools,- }),- );- return;- }-- console.log(renderSnapshot(snapshot));- },- );+ throw error;+ }+ });}diff --git a/packages/agent-tracing/src/cli/replay.ts b/packages/agent-tracing/src/cli/replay.tsnew file mode 100644index 00000000000..17774aba63f--- /dev/null+++ b/packages/agent-tracing/src/cli/replay.ts@@ -0,0 +1,232 @@+import type { Command } from 'commander';++import {+ judgeReplay,+ listReplayableSteps,+ type ModelTarget,+ parseModelTargets,+ type ReplayAttempt,+ type ReplayConnection,+ replayFrozenCall,+ replayTrajectory,+ selectFrozenCall,+} from '../replay';+import { loadSnapshot } from '../store/loadSnapshot';+import type { ExecutionSnapshot } from '../types';++const DEFAULT_JUDGE_MODEL = 'openai/gpt-4o-mini';+const DEFAULT_SERVER_URL = 'https://app.lobehub.com';++/**+ * Replay reaches a model through the LobeHub chat route, which needs a token.+ * The `lh` CLI has a credential store; this dev-tool CLI does not, so it reads+ * the same env vars `lh` honours and says so when they are missing.+ */+const resolveConnection = (): ReplayConnection => {+ const token = process.env.LOBEHUB_JWT;+ if (!token) {+ throw new Error(+ 'Replay needs a LobeHub token. Either set LOBEHUB_JWT (and optionally ' ++ 'LOBEHUB_SERVER_URL), or use `lh trace op replay`, which uses your ' ++ '`lh login` session.',+ );+ }++ return {+ headers: { 'Content-Type': 'application/json', 'Oidc-Auth': token },+ serverUrl: process.env.LOBEHUB_SERVER_URL || DEFAULT_SERVER_URL,+ };+};++const originalTarget = (snapshot: ExecutionSnapshot): ModelTarget[] => {+ if (!snapshot.model || !snapshot.provider) {+ throw new Error(+ 'Snapshot does not record a model/provider β pass targets explicitly with --model provider/model',+ );+ }+ return [+ {+ label: `${snapshot.provider}/${snapshot.model}`,+ model: snapshot.model,+ provider: snapshot.provider,+ },+ ];+};++export function registerReplayCommand(program: Command) {+ program+ .command('replay')+ .description('Re-issue a frozen LLM call from a snapshot against one or more models')+ .argument('[target]', 'Operation id, trace id, snapshot json path, URL, or "latest"')+ .option('-s, --step <n>', 'Snapshot step index to replay (default: the last call_llm step)')+ .option('-m, --model <list>', 'Comma-separated provider/model targets')+ .option('--all-steps', 'Replay every call of the operation against its own recorded payload')+ .option('--concurrency <n>', 'How many calls to replay at once with --all-steps')+ .option('--judge <criteria>', 'Score every replayed output with an llm-rubric criteria')+ .option('--judge-model <model>', 'Judge model as provider/model', DEFAULT_JUDGE_MODEL)+ .option('--no-tools', 'Drop tool definitions from the replayed payload')+ .option('--temperature <n>', 'Override temperature')+ .option('--max-tokens <n>', 'Override max output tokens')+ .option('-j, --json', 'Output as JSON')+ .action(+ async (+ target: string | undefined,+ opts: {+ allSteps?: boolean;+ concurrency?: string;+ json?: boolean;+ judge?: string;+ judgeModel: string;+ maxTokens?: string;+ model?: string;+ step?: string;+ temperature?: string;+ tools: boolean;+ },+ ) => {+ const snapshot = await loadSnapshot(target, { allowDownload: true }).catch(+ (error: unknown) => {+ console.error(error instanceof Error ? error.message : String(error));+ process.exit(1);+ },+ );++ if (!snapshot) {+ console.error(`Snapshot not found: ${target ?? 'latest'}`);+ process.exit(1);+ }++ const allSteps = Boolean(opts.allSteps);+ const stepIndex = opts.step === undefined ? undefined : Number.parseInt(opts.step, 10);+ const call = allSteps ? undefined : selectFrozenCall(snapshot, stepIndex);++ if (!allSteps && !call) {+ console.error(+ stepIndex === undefined+ ? 'Snapshot has no call_llm step with a recorded payload β nothing to replay.'+ : `Step ${stepIndex} is not a replayable call_llm step. Available: ${listReplayableSteps(snapshot).join(', ') || '(none)'}`,+ );+ process.exit(1);+ }++ let targets: ModelTarget[];+ let judgeModel: ModelTarget | undefined;+ let connection: ReplayConnection;+ try {+ targets = opts.model+ ? parseModelTargets(opts.model, snapshot.provider)+ : originalTarget(snapshot);+ judgeModel = opts.judge || allSteps ? parseModelTargets(opts.judgeModel)[0] : undefined;+ connection = resolveConnection();+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error));+ process.exit(1);+ }++ if (allSteps) {+ const result = await replayTrajectory({+ concurrency:+ opts.concurrency === undefined ? undefined : Number.parseInt(opts.concurrency, 10),+ connection,+ maxTokens:+ opts.maxTokens === undefined ? undefined : Number.parseInt(opts.maxTokens, 10),+ onNode: opts.json+ ? undefined+ : (node) =>+ console.log(+ `${node.divergence ? 'β ' : 'β'} node ${node.nodeIndex + 1} (step ${node.stepIndex})` ++ (node.divergence+ ? ` ${node.divergence.field}: recorded ${node.divergence.recorded || '(final answer)'} / replayed ${node.divergence.replayed || '(final answer)'}`+ : ''),+ ),+ verdictJudge: judgeModel ? { criteria: opts.judge, judgeModel } : undefined,+ snapshot,+ target: targets[0],+ temperature:+ opts.temperature === undefined ? undefined : Number.parseFloat(opts.temperature),+ withTools: opts.tools,+ });++ console.log(+ opts.json+ ? JSON.stringify({ ...result, operationId: snapshot.operationId }, null, 2)+ : (result.verdict+ ? `\n${result.verdict.passed ? 'PASS' : 'FAIL'} ${result.verdict.score.toFixed(2)} ${result.verdict.reason ?? ''}`+ : '\nno verdict β pass a judge model to get pass / fail') ++ `\n${result.totalNodes} calls, ` ++ `${result.nodes.filter((node) => !node.divergence && !node.attempt.error).length}` ++ ` took the recorded tool route`,+ );+ return;+ }++ if (!call) return;++ if (!opts.json) {+ console.error(+ `Replaying ${snapshot.operationId} step ${call.stepIndex} ` ++ `(${call.messages.length} messages, ${call.tools?.length ?? 0} tools) ` ++ `on ${targets.map((t) => t.label).join(', ')}`,+ );+ }++ const attempts: ReplayAttempt[] = [];+ for (const modelTarget of targets) {+ const attempt = await replayFrozenCall({+ call,+ connection,+ maxTokens:+ opts.maxTokens === undefined ? undefined : Number.parseInt(opts.maxTokens, 10),+ target: modelTarget,+ temperature:+ opts.temperature === undefined ? undefined : Number.parseFloat(opts.temperature),+ withTools: opts.tools,+ });++ if (opts.judge && judgeModel && !attempt.error) {+ attempt.judge = await judgeReplay({+ actual: attempt.content,+ connection,+ criteria: opts.judge,+ judgeModel,+ });+ }++ attempts.push(attempt);++ if (!opts.json) {+ console.log(`\nββ ${attempt.model}`);+ if (attempt.error) {+ console.log(` error: ${attempt.error}`);+ continue;+ }+ console.log(` ${attempt.durationMs}ms`);+ if (attempt.judge) {+ console.log(+ ` ${attempt.judge.passed ? 'PASS' : 'FAIL'} ${attempt.judge.score.toFixed(2)} ${attempt.judge.reason ?? ''}`,+ );+ }+ for (const toolCall of attempt.toolCalls) {+ console.log(` β ${toolCall.name}(${toolCall.arguments ?? ''})`);+ }+ console.log(`\n${attempt.content || '(empty response)'}`);+ }+ }++ if (opts.json) {+ console.log(+ JSON.stringify(+ {+ attempts,+ operationId: snapshot.operationId,+ originalModel: snapshot.model,+ stepIndex: call.stepIndex,+ },+ null,+ 2,+ ),+ );+ }+ },+ );+}diff --git a/packages/agent-tracing/src/cli/resolve.ts b/packages/agent-tracing/src/cli/resolve.tsindex f3056740771..828a0d53c5b 100644--- a/packages/agent-tracing/src/cli/resolve.ts+++ b/packages/agent-tracing/src/cli/resolve.ts@@ -1,21 +1,13 @@-import { readFile } from 'node:fs/promises';--import { FileSnapshotStore } from '../store/file-store';-import { isOperationId, RemoteSnapshotStore } from '../store/remote-store';+import { loadSnapshot } from '../store/loadSnapshot';import type { ExecutionSnapshot } from '../types';/*** Resolve a single snapshot from a CLI target: a snapshot json path, an operation id- * (local first, then the `_remote` download cache), `latest`, or nothing (latest local).+ * (local first, then the `_remote/` download cache), `latest`, or nothing (latest local).+ *+ * Thin wrapper over {@link loadSnapshot} kept for the read-only CLI commands, which+ * never download.*/export async function resolveSnapshot(target?: string): Promise<ExecutionSnapshot | undefined> {- if (target?.endsWith('.json')) return JSON.parse(await readFile(target, 'utf8'));-- const local = await new FileSnapshotStore().get(target ?? 'latest');- if (local) return local;-- if (target && isOperationId(target)) {- return (await new RemoteSnapshotStore().getCached(target)) ?? undefined;- }- return undefined;+ return loadSnapshot(target);}diff --git a/packages/agent-tracing/src/index.ts b/packages/agent-tracing/src/index.tsindex 1f210bedb4d..a1321ca4730 100644--- a/packages/agent-tracing/src/index.ts+++ b/packages/agent-tracing/src/index.ts@@ -12,9 +12,23 @@ export {type ContextSegment,type SegmentKind,} from './analysis/contextMap';+export { InspectError, type InspectOptions, inspectSnapshot } from './inspect/inspectSnapshot';export { appendStepToPartial, finalizeSnapshot } from './recorder';+export * from './replay';export { FileSnapshotStore } from './store/file-store';-export { isOperationId, parseOperationId } from './store/remote-store';+export {+ AmbiguousSnapshotIdError,+ loadSnapshot,+ type LoadSnapshotOptions,+ MissingTracingBaseUrlError,+} from './store/loadSnapshot';+export {+ buildRemoteUrl,+ isOperationId,+ loadBaseUrl,+ parseOperationId,+ RemoteSnapshotStore,+} from './store/remote-store';export type { ISnapshotStore } from './store/types';export type { ExecutionSnapshot, SnapshotSummary, StepSnapshot } from './types';export {diff --git a/packages/agent-tracing/src/inspect/inspectSnapshot.test.ts b/packages/agent-tracing/src/inspect/inspectSnapshot.test.tsnew file mode 100644index 00000000000..8c7bc7e5679--- /dev/null+++ b/packages/agent-tracing/src/inspect/inspectSnapshot.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from 'vitest';++import type { ExecutionSnapshot } from '../types';+import { InspectError, inspectSnapshot } from './inspectSnapshot';++const snapshot = (steps: Partial<ExecutionSnapshot['steps'][number]>[]): ExecutionSnapshot =>+ ({+ completedAt: 2,+ model: 'deepseek-v4-flash',+ operationId: 'op_1_agt_a_tpc_b_c',+ provider: 'lobehub',+ startedAt: 1,+ steps: steps.map((step, index) => ({+ completedAt: 2,+ executionTimeMs: 1,+ startedAt: 1,+ stepIndex: index,+ stepType: 'call_llm',+ totalCost: 0,+ totalTokens: 0,+ ...step,+ })),+ totalCost: 0,+ totalSteps: steps.length,+ totalTokens: 0,+ traceId: 'trace-1',+ }) as ExecutionSnapshot;++const withSystemRole = (role: string) => ({+ contextEngine: {+ output: [+ { content: role, role: 'system' },+ { content: 'env block', role: 'user' },+ ],+ },+});++describe('inspectSnapshot', () => {+ it('renders the whole snapshot as JSON when no step is targeted', () => {+ const snap = snapshot([{}]);+ expect(JSON.parse(inspectSnapshot(snap, { json: true })).operationId).toBe(snap.operationId);+ });++ it('renders a single step as JSON when a step is targeted', () => {+ const snap = snapshot([{}, {}]);+ expect(JSON.parse(inspectSnapshot(snap, { json: true, step: '1' })).stepIndex).toBe(1);+ });++ it('defaults the step-scoped views to step 0', () => {+ const snap = snapshot([withSystemRole('first'), withSystemRole('second')]);+ expect(JSON.parse(inspectSnapshot(snap, { json: true, systemRole: true }))).toBe('first');+ });++ it('honours an explicit step for the step-scoped views', () => {+ const snap = snapshot([withSystemRole('first'), withSystemRole('second')]);+ expect(JSON.parse(inspectSnapshot(snap, { json: true, step: '1', systemRole: true }))).toBe(+ 'second',+ );+ });++ it('reads the env view off the first user message', () => {+ const snap = snapshot([withSystemRole('role')]);+ expect(JSON.parse(inspectSnapshot(snap, { env: true, json: true }))).toEqual({+ content: 'env block',+ role: 'user',+ });+ });++ it('surfaces the payload tools recorded on the step', () => {+ const tools = [{ function: { name: 'search' }, type: 'function' }];+ const snap = snapshot([{ context: { payload: { tools }, phase: 'x' } }]);++ // `toolsConfig` is absent rather than null: an undefined value is dropped by+ // JSON.stringify, which is what the original inspect command emitted too.+ expect(JSON.parse(inspectSnapshot(snap, { json: true, payloadTools: true }))).toEqual({+ payloadTools: tools,+ });+ });++ it('rejects --diff without a content view to diff', () => {+ expect(() => inspectSnapshot(snapshot([{}]), { diff: '1' })).toThrow(InspectError);+ });++ it('reports which steps exist when the requested one does not', () => {+ expect(() => inspectSnapshot(snapshot([{}, {}]), { json: true, step: '7' })).toThrow(+ /Step 7 not found. Available: 0, 1/,+ );+ });++ it('lets --agent-signal win over the step views', () => {+ const snap = snapshot([withSystemRole('role')]);+ const result = inspectSnapshot(snap, { agentSignal: true, json: true, systemRole: true });+ expect(() => JSON.parse(result)).not.toThrow();+ });+});diff --git a/packages/agent-tracing/src/inspect/inspectSnapshot.ts b/packages/agent-tracing/src/inspect/inspectSnapshot.tsnew file mode 100644index 00000000000..34cf7d64c30--- /dev/null+++ b/packages/agent-tracing/src/inspect/inspectSnapshot.ts@@ -0,0 +1,179 @@+import type { ExecutionSnapshot, StepSnapshot } from '../types';+import {+ analyzeAgentSignal,+ renderAgentSignal,+ renderDiff,+ renderEnvContext,+ renderMemory,+ renderMessageDetail,+ renderPayload,+ renderPayloadTools,+ renderSnapshot,+ renderStepDetail,+ renderSystemRole,+ resolveCeSnapshot,+} from '../viewer';++export interface InspectOptions {+ agentSignal?: boolean;+ context?: boolean;+ diff?: string;+ env?: boolean;+ events?: boolean;+ json?: boolean;+ memory?: boolean;+ messages?: boolean;+ msg?: string;+ msgInput?: string;+ payload?: boolean;+ payloadTools?: boolean;+ step?: string;+ systemRole?: boolean;+ tools?: boolean;+}++/** A bad flag combination or an out-of-range step β the caller decides how to report it. */+export class InspectError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'InspectError';+ }+}++const findStep = (snapshot: ExecutionSnapshot, stepIndex: number): StepSnapshot => {+ const step = snapshot.steps.find((s) => s.stepIndex === stepIndex);+ if (!step) {+ throw new InspectError(+ `Step ${stepIndex} not found. Available: ${snapshot.steps.map((s) => s.stepIndex).join(', ')}`,+ );+ }+ return step;+};++const getSystemRole = (step: StepSnapshot, allSteps?: StepSnapshot[]): string | undefined => {+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;+ const inputRole = ceEvent?.input?.systemRole;+ if (inputRole) return inputRole;+ const outputMsgs = ceEvent?.output as any[] | undefined;+ const systemMsg = outputMsgs?.find((m: any) => m.role === 'system');+ if (!systemMsg) return undefined;+ return typeof systemMsg.content === 'string'+ ? systemMsg.content+ : JSON.stringify(systemMsg.content, null, 2);+};++const getEnvContent = (step: StepSnapshot, allSteps?: StepSnapshot[]): string | undefined => {+ const ceEvent = resolveCeSnapshot(step, allSteps) as any;+ const outputMsgs = ceEvent?.output as any[] | undefined;+ const envMsg = outputMsgs?.find((m: any) => m.role === 'user');+ if (!envMsg) return undefined;+ return typeof envMsg.content === 'string'+ ? envMsg.content+ : JSON.stringify(envMsg.content, null, 2);+};++const json = (value: unknown) => JSON.stringify(value ?? null, null, 2);++/**+ * Render one view of a snapshot. Resolution (local store / remote cache /+ * download / server) belongs to the caller, so `agent-tracing inspect` and+ * `lh trace op inspect` render identically off whatever they managed to load.+ */+export function inspectSnapshot(snapshot: ExecutionSnapshot, opts: InspectOptions = {}): string {+ if (opts.agentSignal) {+ return opts.json ? json(analyzeAgentSignal(snapshot)) : renderAgentSignal(snapshot);+ }++ const stepIndex = opts.step === undefined ? undefined : Number.parseInt(opts.step, 10);++ // -r / --env / -T / -p / -M address a single step and default to the first one.+ const effectiveStepIndex =+ stepIndex ??+ (opts.systemRole || opts.env || opts.payloadTools || opts.payload || opts.memory+ ? 0+ : undefined);++ if (opts.diff !== undefined && !opts.systemRole && !opts.env) {+ throw new InspectError('--diff requires -r or --env.');+ }++ if (opts.diff !== undefined && effectiveStepIndex !== undefined) {+ const diffStepIndex = Number.parseInt(opts.diff, 10);+ const stepA = findStep(snapshot, effectiveStepIndex);+ const stepB = findStep(snapshot, diffStepIndex);+ const read = (step: StepSnapshot) =>+ opts.systemRole ? getSystemRole(step, snapshot.steps) : getEnvContent(step, snapshot.steps);++ return renderDiff(read(stepA) ?? '', read(stepB) ?? '', {+ labelA: `Step ${effectiveStepIndex}`,+ labelB: `Step ${diffStepIndex}`,+ title: opts.systemRole ? 'System Role' : 'Environment Context',+ });+ }++ if ((opts.systemRole || opts.env) && effectiveStepIndex !== undefined) {+ const step = findStep(snapshot, effectiveStepIndex);+ if (opts.json) {+ if (opts.systemRole) return json(getSystemRole(step, snapshot.steps));+ const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;+ return json((ceEvent?.output as any[])?.find((m: any) => m.role === 'user'));+ }+ return opts.systemRole+ ? renderSystemRole(step, snapshot.steps)+ : renderEnvContext(step, snapshot.steps);+ }++ if (opts.payloadTools && effectiveStepIndex !== undefined) {+ const step = findStep(snapshot, effectiveStepIndex);+ if (opts.json) {+ const ceEvent = resolveCeSnapshot(step, snapshot.steps) as any;+ return json({+ payloadTools: (step.context?.payload as any)?.tools,+ toolsConfig: ceEvent?.input?.toolsConfig,+ });+ }+ return renderPayloadTools(step, snapshot.steps);+ }++ if (opts.payload && effectiveStepIndex !== undefined) {+ const step = findStep(snapshot, effectiveStepIndex);+ if (opts.json) return json((resolveCeSnapshot(step, snapshot.steps) as any)?.input);+ return renderPayload(step, snapshot.steps);+ }++ if (opts.memory && effectiveStepIndex !== undefined) {+ const step = findStep(snapshot, effectiveStepIndex);+ if (opts.json) {+ return json((resolveCeSnapshot(step, snapshot.steps) as any)?.input?.userMemory);+ }+ return renderMemory(step, snapshot.steps);+ }++ if (opts.json) {+ return stepIndex === undefined ? json(snapshot) : json(findStep(snapshot, stepIndex));+ }++ if (stepIndex === undefined) return renderSnapshot(snapshot);++ const step = findStep(snapshot, stepIndex);++ const msgIndex =+ opts.msg === undefined+ ? opts.msgInput === undefined+ ? undefined+ : Number.parseInt(opts.msgInput, 10)+ : Number.parseInt(opts.msg, 10);++ if (msgIndex !== undefined) {+ const source: 'input' | 'output' = opts.msgInput === undefined ? 'output' : 'input';+ return renderMessageDetail(step, msgIndex, source, snapshot.steps);+ }++ return renderStepDetail(step, {+ allSteps: snapshot.steps,+ context: opts.context,+ events: opts.events,+ messages: opts.messages,+ tools: opts.tools,+ });+}diff --git a/packages/agent-tracing/src/replay/index.ts b/packages/agent-tracing/src/replay/index.tsnew file mode 100644index 00000000000..dda3c8aa9f2--- /dev/null+++ b/packages/agent-tracing/src/replay/index.ts@@ -0,0 +1,36 @@+export { createJudgeContext, parseJudgeResponse } from './judge';+export {+ buildReplayRequest,+ type BuildReplayRequestParams,+ extractCompletionText,+ extractToolCalls,+ type FrozenCall,+ listReplayableSteps,+ type ModelTarget,+ parseModelTargets,+ resolveStepParams,+ resolveStepTools,+ selectFrozenCall,+} from './payload';+export {+ judgeReplay,+ type JudgeReplayParams,+ type ReplayAttempt,+ type ReplayConnection,+ replayFrozenCall,+ type ReplayFrozenCallParams,+} from './replayFrozenCall';+export {+ replayTrajectory,+ type ReplayTrajectoryParams,+ type TrajectoryDivergence,+ type TrajectoryNode,+ type TrajectoryResult,+} from './replayTrajectory';+export {+ listFrozenCalls,+ type RecordedOutcome,+ recordedOutcome,+ type RecordedToolCall,+ toolSignature,+} from './trajectory';diff --git a/packages/agent-tracing/src/replay/judge.test.ts b/packages/agent-tracing/src/replay/judge.test.tsnew file mode 100644index 00000000000..f8de15371c6--- /dev/null+++ b/packages/agent-tracing/src/replay/judge.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { parseJudgeResponse } from './judge';++describe('parseJudgeResponse', () => {+ it('parses a clean JSON object', () => {+ expect(parseJudgeResponse('{"score":0.8,"reason":"good"}')).toEqual({+ reason: 'good',+ score: 0.8,+ });+ });++ it('recovers the object from a fenced block', () => {+ const raw = 'Here you go:\n```json\n{"score": 0, "reason": "wrong persona"}\n```\n';+ expect(parseJudgeResponse(raw)).toEqual({ reason: 'wrong persona', score: 0 });+ });++ it('keeps a score of 0 rather than treating it as missing', () => {+ expect(parseJudgeResponse('{"score":0,"reason":"fails"}').score).toBe(0);+ });++ it('skips braces inside strings when scanning for the object', () => {+ expect(parseJudgeResponse('note {"reason":"used {curly} braces","score":1} end')).toEqual({+ reason: 'used {curly} braces',+ score: 1,+ });+ });++ it('defaults the reason when the judge omits it', () => {+ expect(parseJudgeResponse('{"score":0.5}')).toEqual({ reason: '', score: 0.5 });+ });++ it('throws when there is no usable score', () => {+ expect(() => parseJudgeResponse('I think it was fine')).toThrow(/parseable score/);+ expect(() => parseJudgeResponse('{"score":"high"}')).toThrow(/parseable score/);+ });+});diff --git a/packages/agent-tracing/src/replay/judge.ts b/packages/agent-tracing/src/replay/judge.tsnew file mode 100644index 00000000000..9b36f5eb8c0--- /dev/null+++ b/packages/agent-tracing/src/replay/judge.ts@@ -0,0 +1,111 @@+import { type MatchContext } from '@lobechat/eval-rubric';++const JUDGE_SCHEMA_NAME = 'eval_judge_score';++/**+ * Back `eval-rubric`'s LLM judge with the authenticated `/webapi/chat` route so+ * replay scoring runs the exact same matcher the eval pipeline uses β only the+ * transport is local.+ */+export const createJudgeContext = ({+ headers,+ judgeModel,+ serverUrl,+}: {+ headers: Record<string, string>;+ judgeModel: { model: string; provider: string };+ serverUrl: string;+}): MatchContext => ({+ generateObject: async ({ messages, schema }) => {+ const res = await fetch(`${serverUrl}/webapi/chat/${judgeModel.provider}`, {+ body: JSON.stringify({+ messages,+ model: judgeModel.model,+ response_format: {+ json_schema: { name: JUDGE_SCHEMA_NAME, schema, strict: true },+ type: 'json_schema',+ },+ responseMode: 'json',+ stream: false,+ }),+ headers,+ method: 'POST',+ });++ if (!res.ok) throw new Error(`Judge request failed: ${res.status} ${await res.text()}`);++ const body = (await res.json()) as {+ choices?: Array<{ message?: { content?: unknown } }>;+ content?: Array<{ text?: unknown }>;+ };+ const raw =+ (typeof body?.choices?.[0]?.message?.content === 'string'+ ? (body.choices[0].message.content as string)+ : undefined) ??+ body?.content?.map((part) => (typeof part?.text === 'string' ? part.text : '')).join('') ??+ '';++ return parseJudgeResponse(raw);+ },+ judgeModel: judgeModel.model,+});++/**+ * Providers that ignore `response_format` still tend to emit the object inside+ * prose or a fenced block, so fall back to the first balanced `{...}` span+ * rather than failing the whole replay on a formatting quirk.+ */+export const parseJudgeResponse = (raw: string): { reason: string; score: number } => {+ const candidates = [raw, extractJsonSpan(raw)].filter((value): value is string => !!value);++ for (const candidate of candidates) {+ try {+ const parsed = JSON.parse(candidate) as { reason?: unknown; score?: unknown };+ if (typeof parsed?.score === 'number' && Number.isFinite(parsed.score)) {+ return {+ reason: typeof parsed.reason === 'string' ? parsed.reason : '',+ score: parsed.score,+ };+ }+ } catch {+ // try the next candidate+ }+ }++ throw new Error(`Judge did not return a parseable score. Raw response: ${raw.slice(0, 200)}`);+};++const extractJsonSpan = (raw: string): string | undefined => {+ const start = raw.indexOf('{');+ if (start < 0) return undefined;++ let depth = 0;+ let inString = false;+ let escaped = false;++ for (let index = start; index < raw.length; index++) {+ const char = raw[index];++ if (escaped) {+ escaped = false;+ continue;+ }+ if (char === '\\') {+ escaped = true;+ continue;+ }+ if (char === '"') {+ inString = !inString;+ continue;+ }+ if (inString) continue;++ if (char === '{') depth++;+ if (char === '}') {+ depth--;+ if (depth === 0) return raw.slice(start, index + 1);+ }+ }++ return undefined;+};diff --git a/packages/agent-tracing/src/replay/payload.test.ts b/packages/agent-tracing/src/replay/payload.test.tsnew file mode 100644index 00000000000..c8c7c5ea33a--- /dev/null+++ b/packages/agent-tracing/src/replay/payload.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it } from 'vitest';++import type { ExecutionSnapshot } from '../types';+import {+ buildReplayRequest,+ extractCompletionText,+ extractToolCalls,+ listReplayableSteps,+ parseModelTargets,+ resolveStepTools,+ selectFrozenCall,+} from './payload';++const snapshot = (steps: Partial<ExecutionSnapshot['steps'][number]>[]): ExecutionSnapshot =>+ ({+ completedAt: 2,+ model: 'deepseek-v4-flash',+ operationId: 'op_1_agt_a_tpc_b_c',+ provider: 'lobehub',+ startedAt: 1,+ steps: steps.map((step, index) => ({+ completedAt: 2,+ executionTimeMs: 1,+ startedAt: 1,+ stepIndex: index,+ stepType: 'call_llm',+ totalCost: 0,+ totalTokens: 0,+ ...step,+ })),+ totalCost: 0,+ totalSteps: steps.length,+ totalTokens: 0,+ traceId: 'trace-1',+ }) as ExecutionSnapshot;++describe('selectFrozenCall', () => {+ it('defaults to the last call_llm step', () => {+ const snap = snapshot([+ { contextEngine: { output: [{ content: 'first', role: 'user' }] } },+ { contextEngine: { output: [{ content: 'second', role: 'user' }] } },+ ]);++ expect(selectFrozenCall(snap)?.stepIndex).toBe(1);+ expect(selectFrozenCall(snap)?.messages).toEqual([{ content: 'second', role: 'user' }]);+ });++ it('carries the CE delta forward for steps that omit output', () => {+ const snap = snapshot([+ { contextEngine: { output: [{ content: 'frozen', role: 'user' }] } },+ { contextEngine: {} },+ ]);++ expect(selectFrozenCall(snap, 1)?.messages).toEqual([{ content: 'frozen', role: 'user' }]);+ });++ it('addresses steps by snapshot step index, not call_llm position', () => {+ const snap = snapshot([+ { contextEngine: { output: [{ content: 'a', role: 'user' }] } },+ { stepType: 'call_tool' },+ { contextEngine: { output: [{ content: 'b', role: 'user' }] } },+ ]);++ expect(selectFrozenCall(snap, 2)?.messages).toEqual([{ content: 'b', role: 'user' }]);+ expect(selectFrozenCall(snap, 1)).toBeUndefined();+ expect(listReplayableSteps(snap)).toEqual([0, 2]);+ });++ it('returns undefined when nothing was recorded', () => {+ expect(selectFrozenCall(snapshot([{ stepType: 'call_tool' }]))).toBeUndefined();+ });+});++describe('resolveStepTools', () => {+ it('walks back to the nearest step that recorded a toolset', () => {+ const tools = [{ function: { name: 'search' }, type: 'function' }];+ const snap = snapshot([+ { context: { payload: { tools }, phase: 'x' } },+ { contextEngine: {} },+ { contextEngine: {} },+ ]);++ expect(resolveStepTools(snap, 2)).toEqual(tools);+ });++ it('ignores toolsets recorded after the target step', () => {+ const snap = snapshot([+ { contextEngine: {} },+ { context: { payload: { tools: [{ type: 'function' }] }, phase: 'x' } },+ ]);++ expect(resolveStepTools(snap, 0)).toBeUndefined();+ });+});++describe('parseModelTargets', () => {+ it('parses a comma-separated provider/model list', () => {+ expect(parseModelTargets('openai/gpt-5, anthropic/claude-opus-5')).toEqual([+ { label: 'openai/gpt-5', model: 'gpt-5', provider: 'openai' },+ { label: 'anthropic/claude-opus-5', model: 'claude-opus-5', provider: 'anthropic' },+ ]);+ });++ it('keeps slashes inside the model id', () => {+ expect(parseModelTargets('openrouter/meta/llama-4')).toEqual([+ { label: 'openrouter/meta/llama-4', model: 'meta/llama-4', provider: 'openrouter' },+ ]);+ });++ it('falls back to the snapshot provider for a bare model name', () => {+ expect(parseModelTargets('gpt-5', 'lobehub')).toEqual([+ { label: 'lobehub/gpt-5', model: 'gpt-5', provider: 'lobehub' },+ ]);+ });++ it('rejects a bare model name with no fallback provider', () => {+ expect(() => parseModelTargets('gpt-5')).toThrow(/Cannot resolve a provider/);+ });++ it('rejects an empty list', () => {+ expect(() => parseModelTargets(' , ')).toThrow(/No model targets/);+ });+});++describe('buildReplayRequest', () => {+ const call = { messages: [{ content: 'hi', role: 'user' }], stepIndex: 0, tools: [{ a: 1 }] };+ const target = { label: 'openai/gpt-5', model: 'gpt-5', provider: 'openai' };++ it('carries the frozen messages and tools over verbatim, swapping only the model', () => {+ expect(buildReplayRequest({ call, target })).toEqual({+ messages: call.messages,+ model: 'gpt-5',+ responseMode: 'json',+ stream: false,+ tools: call.tools,+ });+ });++ it('drops tools when replaying without them', () => {+ expect(buildReplayRequest({ call, target, withTools: false })).not.toHaveProperty('tools');+ });++ it('omits sampling overrides that were not requested', () => {+ const request = buildReplayRequest({ call, target });+ expect(request).not.toHaveProperty('temperature');+ expect(request).not.toHaveProperty('max_tokens');+ });++ it('applies sampling overrides when given', () => {+ expect(buildReplayRequest({ call, maxTokens: 128, target, temperature: 0 })).toMatchObject({+ max_tokens: 128,+ temperature: 0,+ });+ });+});++describe('extractCompletionText', () => {+ it('reads the OpenAI shape', () => {+ expect(extractCompletionText({ choices: [{ message: { content: 'hello' } }] })).toBe('hello');+ });++ it('reads the Anthropic shape', () => {+ expect(extractCompletionText({ content: [{ text: 'a' }, { text: 'b' }] })).toBe('ab');+ });++ it('returns an empty string for a tool-only completion', () => {+ expect(extractCompletionText({ choices: [{ message: { content: null } }] })).toBe('');+ });+});++describe('extractToolCalls', () => {+ it('normalizes tool calls and drops unnamed entries', () => {+ const body = {+ choices: [+ {+ message: {+ tool_calls: [+ { function: { arguments: '{"q":1}', name: 'search' } },+ { function: { arguments: '{}' } },+ ],+ },+ },+ ],+ };++ expect(extractToolCalls(body)).toEqual([{ arguments: '{"q":1}', name: 'search' }]);+ });++ it('returns an empty list when there are none', () => {+ expect(extractToolCalls({ choices: [{ message: { content: 'x' } }] })).toEqual([]);+ });+});diff --git a/packages/agent-tracing/src/replay/payload.ts b/packages/agent-tracing/src/replay/payload.tsnew file mode 100644index 00000000000..6b6800bb085--- /dev/null+++ b/packages/agent-tracing/src/replay/payload.ts@@ -0,0 +1,225 @@+import { resolvePayloads } from '../analysis/contextLint';+import type { ExecutionSnapshot } from '../types';++/** One `call_llm` step frozen out of a snapshot, ready to be re-issued. */+export interface FrozenCall {+ messages: unknown[];+ /**+ * Sampling / reasoning parameters the recorded call ran with.+ *+ * Undefined for every trace written so far: the recorder stores the runtime+ * step context under `context.payload`, not the provider request body, so+ * temperature, top_p, max_tokens, penalties and reasoning config are simply+ * not in the file. Replays therefore run at the server's current defaults for+ * those, and a difference in output is attributable to the model ONLY to the+ * extent the original also ran at defaults. Populated automatically once the+ * recorder starts writing them.+ */+ params?: Record<string, unknown>;+ stepIndex: number;+ /** LLM function definitions visible to the model at this step, if recorded. */+ tools?: unknown[];+}++/**+ * Generation parameters a replay must reproduce for the model to be the only+ * variable. Kept as an explicit allow-list so unrelated runtime-context keys+ * under `context.payload` can never leak into a provider request.+ */+const GENERATION_PARAM_KEYS = [+ 'frequency_penalty',+ 'max_tokens',+ 'presence_penalty',+ 'reasoning',+ 'reasoning_effort',+ 'stop',+ 'temperature',+ 'top_k',+ 'top_p',+] as const;++export interface ModelTarget {+ /** `provider/model` as the user typed it, used for display. */+ label: string;+ model: string;+ provider: string;+}++/**+ * Pick the `call_llm` step to replay. Defaults to the LAST one: a bad answer is+ * almost always the final assistant turn, and earlier steps are usually tool+ * plumbing. `stepIndex` addresses the snapshot's own step numbering, not the+ * position within the `call_llm` subset, so it lines up with `agent-tracing+ * inspect -s <n>`.+ */+export const selectFrozenCall = (+ snapshot: ExecutionSnapshot,+ stepIndex?: number,+): FrozenCall | undefined => {+ const { payloads } = resolvePayloads(snapshot);+ if (payloads.length === 0) return undefined;++ const picked =+ stepIndex === undefined+ ? payloads.at(-1)+ : payloads.find((payload) => payload.stepIndex === stepIndex);+ if (!picked) return undefined;++ return {+ messages: picked.messages,+ params: resolveStepParams(snapshot, picked.stepIndex),+ stepIndex: picked.stepIndex,+ tools: resolveStepTools(snapshot, picked.stepIndex),+ };+};++/**+ * Recover the recorded generation parameters for a step, if the trace carries+ * any. Returns undefined when none were recorded, which is what every trace+ * written before the recorder learned to store them looks like.+ */+export const resolveStepParams = (+ snapshot: ExecutionSnapshot,+ stepIndex: number,+): Record<string, unknown> | undefined => {+ const step = snapshot.steps.find((s) => s.stepIndex === stepIndex);+ const payload = step?.context?.payload as Record<string, unknown> | undefined;+ if (!payload) return undefined;++ const params: Record<string, unknown> = {};+ for (const key of GENERATION_PARAM_KEYS) {+ if (payload[key] !== undefined) params[key] = payload[key];+ }++ return Object.keys(params).length > 0 ? params : undefined;+};++/**+ * Tool definitions are recorded on `context.payload.tools`, but only on the+ * steps where the runtime rebuilt them (typically step 0). Walk backwards to+ * the nearest step that carries them so a later step replays with the same+ * toolset the model actually saw.+ */+export const resolveStepTools = (+ snapshot: ExecutionSnapshot,+ stepIndex: number,+): unknown[] | undefined => {+ let tools: unknown[] | undefined;+ for (const step of snapshot.steps) {+ if (step.stepIndex > stepIndex) break;+ const candidate = (step.context?.payload as { tools?: unknown } | undefined)?.tools;+ if (Array.isArray(candidate)) tools = candidate;+ }+ return tools;+};++/** List the `call_llm` step indexes a snapshot can replay, for error messages. */+export const listReplayableSteps = (snapshot: ExecutionSnapshot): number[] =>+ resolvePayloads(snapshot).payloads.map((payload) => payload.stepIndex);++/**+ * Parse `--model a/b,c/d` into provider/model pairs. A bare model name inherits+ * the provider the snapshot ran on, so `--model gpt-5` works when replaying an+ * op that already targeted a provider.+ */+export const parseModelTargets = (spec: string, fallbackProvider?: string): ModelTarget[] => {+ const targets: ModelTarget[] = [];++ for (const raw of spec.split(',')) {+ const entry = raw.trim();+ if (!entry) continue;++ const slash = entry.indexOf('/');+ const provider = slash > 0 ? entry.slice(0, slash) : fallbackProvider;+ const model = slash > 0 ? entry.slice(slash + 1) : entry;++ if (!provider) {+ throw new Error(+ `Cannot resolve a provider for "${entry}" β pass it as "provider/model" ` ++ `(the snapshot does not record one).`,+ );+ }+ if (!model) throw new Error(`Invalid model target: "${entry}"`);++ targets.push({ label: `${provider}/${model}`, model, provider });+ }++ if (targets.length === 0) throw new Error('No model targets provided');+ return targets;+};++export interface BuildReplayRequestParams {+ call: FrozenCall;+ maxTokens?: number;+ target: ModelTarget;+ temperature?: number;+ withTools?: boolean;+}++/**+ * Rebuild the chat request from a frozen call: messages, tools and whatever+ * generation parameters the trace recorded are carried over, then explicit+ * overrides are applied on top, so the model is the only variable.+ *+ * The caveat is `call.params` β see {@link FrozenCall.params}. Traces do not+ * record sampling parameters yet, so for an operation that ran with non-default+ * temperature or reasoning settings, a replay silently uses today's defaults+ * instead. Comparisons across models stay valid (every target gets the same+ * request); comparisons against the recorded output do not.+ */+export const buildReplayRequest = ({+ call,+ maxTokens,+ target,+ temperature,+ withTools = true,+}: BuildReplayRequestParams): Record<string, unknown> => {+ const request: Record<string, unknown> = {+ ...call.params,+ messages: call.messages,+ model: target.model,+ responseMode: 'json',+ stream: false,+ };++ if (withTools && call.tools?.length) request.tools = call.tools;+ if (temperature !== undefined) request.temperature = temperature;+ if (maxTokens !== undefined) request.max_tokens = maxTokens;++ return request;+};++/** Assistant text out of an OpenAI- or Anthropic-shaped completion body. */+export const extractCompletionText = (body: unknown): string => {+ const shaped = body as {+ choices?: Array<{ message?: { content?: unknown } }>;+ content?: Array<{ text?: unknown }>;+ };++ const openai = shaped?.choices?.[0]?.message?.content;+ if (typeof openai === 'string') return openai;++ const anthropic = shaped?.content+ ?.map((part) => (typeof part?.text === 'string' ? part.text : ''))+ .join('');+ if (anthropic) return anthropic;++ return '';+};++/** Tool calls requested by the replayed completion, normalized for display. */+export const extractToolCalls = (body: unknown): Array<{ arguments?: string; name: string }> => {+ const calls = (+ body as {+ choices?: Array<{+ message?: { tool_calls?: Array<{ function?: { arguments?: string; name?: string } }> };+ }>;+ }+ )?.choices?.[0]?.message?.tool_calls;++ if (!Array.isArray(calls)) return [];++ return calls+ .map((call) => ({ arguments: call.function?.arguments, name: call.function?.name ?? '' }))+ .filter((call) => call.name);+};diff --git a/packages/agent-tracing/src/replay/replayFrozenCall.ts b/packages/agent-tracing/src/replay/replayFrozenCall.tsnew file mode 100644index 00000000000..3772d79a826--- /dev/null+++ b/packages/agent-tracing/src/replay/replayFrozenCall.ts@@ -0,0 +1,136 @@+import { match } from '@lobechat/eval-rubric';++import { createJudgeContext } from './judge';+import {+ buildReplayRequest,+ extractCompletionText,+ extractToolCalls,+ type FrozenCall,+ type ModelTarget,+} from './payload';++const JUDGE_THRESHOLD = 0.6;++export interface ReplayAttempt {+ content: string;+ durationMs: number;+ error?: string;+ judge?: { passed: boolean; reason?: string; score: number };+ model: string;+ toolCalls: Array<{ arguments?: string; name: string }>;+ usage?: { completionTokens?: number; promptTokens?: number };+}++/** How a caller reaches `/webapi/chat/<provider>` β CLIs differ only in auth. */+export interface ReplayConnection {+ headers: Record<string, string>;+ serverUrl: string;+}++export interface ReplayFrozenCallParams {+ call: FrozenCall;+ connection: ReplayConnection;+ maxTokens?: number;+ target: ModelTarget;+ temperature?: number;+ withTools?: boolean;+}++/**+ * Re-issue one frozen call against one model. Transport errors are returned on+ * the attempt rather than thrown so a failing model in a multi-model sweep does+ * not abort the models after it.+ */+export const replayFrozenCall = async ({+ call,+ connection,+ maxTokens,+ target,+ temperature,+ withTools = true,+}: ReplayFrozenCallParams): Promise<ReplayAttempt> => {+ const request = buildReplayRequest({ call, maxTokens, target, temperature, withTools });+ const startedAt = Date.now();++ try {+ const res = await fetch(`${connection.serverUrl}/webapi/chat/${target.provider}`, {+ body: JSON.stringify(request),+ headers: connection.headers,+ method: 'POST',+ });++ if (!res.ok) {+ return {+ content: '',+ durationMs: Date.now() - startedAt,+ error: `${res.status} ${await res.text()}`,+ model: target.label,+ toolCalls: [],+ };+ }++ const body = (await res.json()) as {+ usage?: { completion_tokens?: number; prompt_tokens?: number };+ };++ return {+ content: extractCompletionText(body),+ durationMs: Date.now() - startedAt,+ model: target.label,+ toolCalls: extractToolCalls(body),+ usage: {+ completionTokens: body?.usage?.completion_tokens,+ promptTokens: body?.usage?.prompt_tokens,+ },+ };+ } catch (error) {+ return {+ content: '',+ durationMs: Date.now() - startedAt,+ error: error instanceof Error ? error.message : String(error),+ model: target.label,+ toolCalls: [],+ };+ }+};++export interface JudgeReplayParams {+ actual: string;+ connection: ReplayConnection;+ criteria: string;+ /** Reference output, shown to the judge as `[Expected]`. */+ expected?: string;+ judgeModel: ModelTarget;+}++/**+ * Score a replayed output through `eval-rubric`'s `llm-rubric` matcher, so a+ * score printed here means what the same score means in an eval run β only the+ * transport is local.+ */+export const judgeReplay = async ({+ actual,+ connection,+ criteria,+ expected,+ judgeModel,+}: JudgeReplayParams): Promise<ReplayAttempt['judge']> => {+ const result = await match(+ {+ actual,+ expected,+ input: '',+ rubric: {+ config: { criteria },+ id: 'replay-judge',+ name: 'replay-judge',+ threshold: JUDGE_THRESHOLD,+ type: 'llm-rubric',+ weight: 1,+ },+ },+ createJudgeContext({ ...connection, judgeModel }),+ );++ return { passed: result.passed, reason: result.reason, score: result.score };+};diff --git a/packages/agent-tracing/src/replay/replayTrajectory.test.ts b/packages/agent-tracing/src/replay/replayTrajectory.test.tsnew file mode 100644index 00000000000..159cfef8dfd--- /dev/null+++ b/packages/agent-tracing/src/replay/replayTrajectory.test.ts@@ -0,0 +1,224 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { ExecutionSnapshot } from '../types';+import { replayTrajectory } from './replayTrajectory';++const connection = { headers: {}, serverUrl: 'https://example.test' };+const target = { label: 'p/m', model: 'm', provider: 'p' };++/** Two call_llm nodes: the first calls a tool, the second answers. */+const twoNodeSnapshot = (): ExecutionSnapshot =>+ ({+ completedAt: 2,+ operationId: 'op_1_agt_a_tpc_b_c',+ startedAt: 1,+ steps: [+ {+ completedAt: 2,+ content: 'looking it up',+ contextEngine: {+ output: [+ { content: 'system', role: 'system' },+ { content: 'question', role: 'user' },+ ],+ },+ executionTimeMs: 1,+ messagesDelta: [{ content: 'looking it up', role: 'assistant' }],+ startedAt: 1,+ stepIndex: 0,+ stepType: 'call_llm',+ toolsCalling: [{ apiName: 'readFile', identifier: 'fs' }],+ totalCost: 0,+ totalTokens: 0,+ },+ {+ completedAt: 2,+ executionTimeMs: 1,+ startedAt: 1,+ stepIndex: 1,+ stepType: 'call_tool',+ toolsResult: [{ apiName: 'readFile', identifier: 'fs', output: 'FILE BODY' }],+ totalCost: 0,+ totalTokens: 0,+ },+ {+ completedAt: 2,+ content: 'the answer is 42',+ contextEngine: {+ output: [+ { content: 'system', role: 'system' },+ { content: 'injected block', role: 'user' },+ { content: 'question', role: 'user' },+ { content: 'looking it up', role: 'assistant' },+ { content: 'FILE BODY', role: 'tool' },+ ],+ },+ executionTimeMs: 1,+ messagesDelta: [{ content: 'the answer is 42', role: 'assistant' }],+ startedAt: 1,+ stepIndex: 2,+ stepType: 'call_llm',+ totalCost: 0,+ totalTokens: 0,+ },+ ],+ totalCost: 0,+ totalSteps: 3,+ totalTokens: 0,+ traceId: 't',+ }) as unknown as ExecutionSnapshot;++type StubToolCall = string | { arguments?: string; name: string };++/** Stub the chat route, returning one scripted completion per call. */+const stubModel = (completions: Array<{ content?: string; toolCalls?: StubToolCall[] }>) => {+ const sent: any[] = [];+ let call = 0;++ vi.stubGlobal('fetch', async (_url: string, init: { body: string }) => {+ sent.push(JSON.parse(init.body));+ const next = completions[Math.min(call++, completions.length - 1)];+ return {+ json: async () => ({+ choices: [+ {+ message: {+ content: next.content ?? '',+ tool_calls: next.toolCalls?.map((toolCall, index) => {+ const shaped = typeof toolCall === 'string' ? { name: toolCall } : toolCall;+ return {+ function: { arguments: shaped.arguments ?? '{}', name: shaped.name },+ id: `orig_${index}`,+ };+ }),+ },+ },+ ],+ }),+ ok: true,+ };+ });++ return sent;+};++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('replayTrajectory', () => {+ it('replays every node and reports a matching trajectory as no divergence', async () => {+ stubModel([{ content: 'looking it up', toolCalls: ['fs____readFile'] }, { content: '42' }]);++ const result = await replayTrajectory({ connection, snapshot: twoNodeSnapshot(), target });++ expect(result.totalNodes).toBe(2);+ expect(result.nodes).toHaveLength(2);+ expect(result.divergedAtNode).toBeUndefined();+ expect(result.nodes.every((node) => node.divergence === undefined)).toBe(true);+ });++ it('replays each node against its own recorded payload', async () => {+ const sent = stubModel([+ { content: 'guessing', toolCalls: ['fs____writeFile'] },+ { content: '43' },+ ]);++ const result = await replayTrajectory({+ concurrency: 1,+ connection,+ snapshot: twoNodeSnapshot(),+ target,+ });++ // Node 0 diverged, but node 1 still gets the payload the harness built for+ // it β including the ORIGINAL assistant turn and tool result, not the+ // replayed ones. That independence is the point of the mode.+ expect(result.divergedAtNode).toBe(0);+ expect(result.nodes).toHaveLength(2);+ expect(sent[1].messages.map((m: any) => m.content)).toEqual([+ 'system',+ 'injected block',+ 'question',+ 'looking it up',+ 'FILE BODY',+ ]);+ });++ it('a divergence never stops the nodes after it', async () => {+ stubModel([{ content: 'guessing', toolCalls: ['fs____writeFile'] }, { content: '43' }]);++ const result = await replayTrajectory({ connection, snapshot: twoNodeSnapshot(), target });++ expect(result.divergedAtNode).toBe(0);+ expect(result.nodes).toHaveLength(2);+ });++ it('a node that cannot reach the model costs only itself', async () => {+ let call = 0;+ vi.stubGlobal('fetch', async () => {+ // Only the first node fails; the second must still be replayed.+ if (call++ === 0) return { ok: false, status: 500, text: async () => 'boom' };+ return {+ json: async () => ({ choices: [{ message: { content: '42' } }] }),+ ok: true,+ };+ });++ const result = await replayTrajectory({+ concurrency: 1,+ connection,+ snapshot: twoNodeSnapshot(),+ target,+ });++ expect(result.nodes).toHaveLength(2);+ expect(result.nodes[0].attempt.error).toContain('500');+ expect(result.nodes[1].attempt.error).toBeUndefined();+ expect(result.nodes[1].attempt.content).toBe('42');+ });++ it('fails the verdict when the final call never reached the model', async () => {+ // A pass/fail tool that returns neither is useless: the run did not get the+ // job done, so it is a FAIL, not an absent verdict.+ vi.stubGlobal('fetch', async () => ({ ok: false, status: 503, text: async () => 'down' }));++ const result = await replayTrajectory({+ connection,+ snapshot: twoNodeSnapshot(),+ target,+ verdictJudge: { judgeModel: target },+ });++ expect(result.verdict?.passed).toBe(false);+ expect(result.verdict?.score).toBe(0);+ expect(result.verdict?.reason).toContain('503');+ });++ it('settles nodes as they finish but returns them in order', async () => {+ const seen: number[] = [];+ let call = 0;+ vi.stubGlobal('fetch', async () => {+ // The first node resolves last.+ const index = call++;+ await new Promise((resolve) => setTimeout(resolve, index === 0 ? 20 : 0));+ return {+ json: async () => ({ choices: [{ message: { content: `answer ${index}` } }] }),+ ok: true,+ };+ });++ const result = await replayTrajectory({+ concurrency: 4,+ connection,+ onNode: (node) => seen.push(node.nodeIndex),+ snapshot: twoNodeSnapshot(),+ target,+ });++ // Progress arrives out of order β each node carries its own index, so a+ // renderer places it rather than appending it.+ expect(seen).toEqual([1, 0]);+ expect(result.nodes.map((node) => node.nodeIndex)).toEqual([0, 1]);+ });+});diff --git a/packages/agent-tracing/src/replay/replayTrajectory.ts b/packages/agent-tracing/src/replay/replayTrajectory.tsnew file mode 100644index 00000000000..70d7c100854--- /dev/null+++ b/packages/agent-tracing/src/replay/replayTrajectory.ts@@ -0,0 +1,201 @@+import type { ExecutionSnapshot } from '../types';+import type { ModelTarget } from './payload';+import {+ judgeReplay,+ type ReplayAttempt,+ type ReplayConnection,+ replayFrozenCall,+} from './replayFrozenCall';+import { listFrozenCalls, recordedOutcome, toolSignature } from './trajectory';++/**+ * One field of a node that came out differently from the recording.+ *+ * `field` is what keeps the shape shared with the goal-coordinator layer, which+ * reports its own divergences the same way: a reader decides per field whether+ * it is scored or merely informational. Content, for instance, is expected to+ * differ and is judged rather than failed.+ */+export interface TrajectoryDivergence {+ field: 'toolSignature';+ recorded: string;+ replayed: string;+}++export interface TrajectoryNode {+ attempt: ReplayAttempt;+ /** Present only when the node's tool calls differ from the recorded run. */+ divergence?: TrajectoryDivergence;+ nodeIndex: number;+ recorded: { content: string; toolSignature: string };+ stepIndex: number;+}++export interface TrajectoryResult {+ divergedAtNode?: number;+ nodes: TrajectoryNode[];+ totalNodes: number;+ /**+ * Did this model get the job done β the question the whole replay exists to+ * answer. Judged semantically against the recorded outcome, because a+ * different model may reach the same result by a different route, and+ * demanding an identical tool sequence would fail it for succeeding+ * differently.+ */+ verdict?: { passed: boolean; reason?: string; score: number };+}++export interface ReplayTrajectoryParams {+ /** How many nodes to have in flight at once. */+ concurrency?: number;+ connection: ReplayConnection;+ maxTokens?: number;+ /**+ * Called as each node settles, which under concurrency is not node order β+ * every node carries its own `nodeIndex`, so a caller renders by position+ * rather than by arrival. `nodes` in the result is always ordered.+ */+ onNode?: (node: TrajectoryNode) => void;+ snapshot: ExecutionSnapshot;+ target: ModelTarget;+ temperature?: number;+ /** Judge that decides pass / fail. `criteria` overrides the default rubric. */+ verdictJudge?: { criteria?: string; judgeModel: ModelTarget };+ withTools?: boolean;+}++const DEFAULT_CONCURRENCY = 4;++/**+ * Judges the outcome, not the route. A replacement model that solved the same+ * problem by calling different tools has passed; one that answered differently+ * has not.+ */+const DEFAULT_VERDICT_CRITERIA = [+ 'The [Output] is another model replaying a recorded agent run and is compared',+ 'against what the original run produced in [Expected]. Score 1.0 when it gets',+ 'the job done: same decision, same substantive claims, same answer to the user',+ 'β allowing for differences in wording, ordering, formatting, verbosity, and',+ 'in which tools were used to get there. Score 0.0 when it reaches a different',+ 'conclusion, omits something the original established, or asserts something the',+ 'original did not.',+].join(' ');++/**+ * Run `tasks` with at most `limit` in flight, resolving to their results in+ * input order.+ */+const mapWithConcurrency = async <T>(+ tasks: Array<() => Promise<T>>,+ limit: number,+): Promise<T[]> => {+ const results = Array.from({ length: tasks.length }) as T[];+ let next = 0;++ const worker = async () => {+ while (next < tasks.length) {+ const index = next++;+ results[index] = await tasks[index]();+ }+ };++ await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, () => worker()));++ return results;+};++/**+ * Replay every `call_llm` node of a recorded operation, each against the+ * payload the harness actually built for it.+ *+ * The nodes are independent by construction, and that is the point: node 4 is+ * asked "given exactly this context, do you make the same decision?", so a+ * different answer at node 2 cannot contaminate it. Chaining the nodes instead+ * β feeding each replayed output into the next β was tried and removed: a trace+ * cannot regenerate tool output, only replay what was recorded, so the moment+ * the model deviates there is no ground truth left and the run silently+ * measures nothing.+ *+ * Independence also means the nodes can go out concurrently, and that a node+ * that fails to reach the provider costs only itself.+ */+export const replayTrajectory = async ({+ concurrency = DEFAULT_CONCURRENCY,+ connection,+ maxTokens,+ onNode,+ snapshot,+ target,+ temperature,+ verdictJudge,+ withTools = true,+}: ReplayTrajectoryParams): Promise<TrajectoryResult> => {+ const calls = listFrozenCalls(snapshot);++ const nodes = await mapWithConcurrency(+ calls.map((call, nodeIndex) => async (): Promise<TrajectoryNode> => {+ const attempt = await replayFrozenCall({+ call,+ connection,+ maxTokens,+ target,+ temperature,+ withTools,+ });++ const recorded = recordedOutcome(snapshot, call.stepIndex);+ const recordedSignature = toolSignature(recorded.toolCalls);++ const node: TrajectoryNode = {+ attempt,+ nodeIndex,+ recorded: { content: recorded.content, toolSignature: recordedSignature },+ stepIndex: call.stepIndex,+ };++ const actualSignature = toolSignature(attempt.toolCalls);+ if (!attempt.error && actualSignature !== recordedSignature) {+ node.divergence = {+ field: 'toolSignature',+ recorded: recordedSignature,+ replayed: actualSignature,+ };+ }++ onNode?.(node);++ return node;+ }),+ Math.max(1, concurrency),+ );++ const result: TrajectoryResult = {+ divergedAtNode: nodes.find((node) => node.divergence)?.nodeIndex,+ nodes,+ totalNodes: calls.length,+ };++ const lastNode = nodes.at(-1);+ if (!verdictJudge || !lastNode) return result;++ // A final call that never reached the model is a failed run, not an absent+ // verdict β a pass/fail tool that silently returns neither is useless.+ if (lastNode.attempt.error) {+ result.verdict = {+ passed: false,+ reason: `The final call did not reach the model: ${lastNode.attempt.error}`,+ score: 0,+ };+ return result;+ }++ result.verdict = await judgeReplay({+ actual: lastNode.attempt.content,+ connection,+ criteria: verdictJudge.criteria ?? DEFAULT_VERDICT_CRITERIA,+ expected: lastNode.recorded.content,+ judgeModel: verdictJudge.judgeModel,+ });++ return result;+};diff --git a/packages/agent-tracing/src/replay/trajectory.test.ts b/packages/agent-tracing/src/replay/trajectory.test.tsnew file mode 100644index 00000000000..32ef58d9610--- /dev/null+++ b/packages/agent-tracing/src/replay/trajectory.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';++import type { ExecutionSnapshot } from '../types';+import { listFrozenCalls, recordedOutcome, toolSignature } from './trajectory';++const snapshot = (steps: Partial<ExecutionSnapshot['steps'][number]>[]): ExecutionSnapshot =>+ ({+ completedAt: 2,+ operationId: 'op_1_agt_a_tpc_b_c',+ startedAt: 1,+ steps: steps.map((step, index) => ({+ completedAt: 2,+ executionTimeMs: 1,+ startedAt: 1,+ stepIndex: index,+ stepType: 'call_llm',+ totalCost: 0,+ totalTokens: 0,+ ...step,+ })),+ totalCost: 0,+ totalSteps: steps.length,+ totalTokens: 0,+ traceId: 't',+ }) as ExecutionSnapshot;++describe('listFrozenCalls', () => {+ it('returns one node per call_llm step, skipping tool steps', () => {+ const snap = snapshot([+ { contextEngine: { output: [{ content: 'a', role: 'user' }] } },+ { stepType: 'call_tool' },+ { contextEngine: { output: [{ content: 'b', role: 'user' }] } },+ ]);++ expect(listFrozenCalls(snap).map((call) => call.stepIndex)).toEqual([0, 2]);+ });+});++describe('recordedOutcome', () => {+ it('composes tool names as identifier____apiName', () => {+ const snap = snapshot([+ {+ content: 'let me look',+ toolsCalling: [{ apiName: 'globFiles', identifier: 'lobe-local-system' }],+ },+ ]);++ expect(recordedOutcome(snap, 0)).toEqual({+ content: 'let me look',+ toolCalls: [{ arguments: undefined, name: 'lobe-local-system____globFiles' }],+ });+ });++ it('reports an empty outcome for a step with no output', () => {+ expect(recordedOutcome(snapshot([{}]), 0)).toEqual({ content: '', toolCalls: [] });+ });+});++describe('toolSignature', () => {+ it('compares the sequence of tools, not their arguments', () => {+ expect(toolSignature([{ name: 'a' }, { name: 'b' }])).toBe('a β b');+ expect(toolSignature([{ name: 'b' }, { name: 'a' }])).not.toBe(+ toolSignature([{ name: 'a' }, { name: 'b' }]),+ );+ });++ it('treats a terminal answer as an empty signature', () => {+ expect(toolSignature([])).toBe('');+ });+});diff --git a/packages/agent-tracing/src/replay/trajectory.ts b/packages/agent-tracing/src/replay/trajectory.tsnew file mode 100644index 00000000000..b6c75c8c0c7--- /dev/null+++ b/packages/agent-tracing/src/replay/trajectory.ts@@ -0,0 +1,49 @@+import { resolvePayloads } from '../analysis/contextLint';+import type { ExecutionSnapshot } from '../types';+import { type FrozenCall, resolveStepParams, resolveStepTools } from './payload';++/** Tool identifiers are exposed to the model as `identifier____apiName`. */+const TOOL_NAME_SEPARATOR = '____';++export interface RecordedToolCall {+ arguments?: string;+ name: string;+}++/** What the recorded run actually produced at one `call_llm` node. */+export interface RecordedOutcome {+ content: string;+ toolCalls: RecordedToolCall[];+}++/** Every `call_llm` step of a snapshot, in order, with the payload it saw. */+export const listFrozenCalls = (snapshot: ExecutionSnapshot): FrozenCall[] =>+ resolvePayloads(snapshot).payloads.map(({ messages, stepIndex }) => ({+ messages,+ params: resolveStepParams(snapshot, stepIndex),+ stepIndex,+ tools: resolveStepTools(snapshot, stepIndex),+ }));++export const recordedOutcome = (+ snapshot: ExecutionSnapshot,+ stepIndex: number,+): RecordedOutcome => {+ const step = snapshot.steps.find((s) => s.stepIndex === stepIndex);++ return {+ content: step?.content ?? '',+ toolCalls: (step?.toolsCalling ?? []).map((call) => ({+ arguments: call.arguments,+ name: `${call.identifier}${TOOL_NAME_SEPARATOR}${call.apiName}`,+ })),+ };+};++/**+ * Comparable shape of a node's tool calls. Arguments are excluded: two models+ * can reach the same step of a trajectory with differently-phrased arguments,+ * and treating that as divergence would report noise as failure.+ */+export const toolSignature = (calls: Array<{ name: string }>): string =>+ calls.map((call) => call.name).join(' β ');diff --git a/packages/agent-tracing/src/store/loadSnapshot.test.ts b/packages/agent-tracing/src/store/loadSnapshot.test.tsnew file mode 100644index 00000000000..fc607ff010c--- /dev/null+++ b/packages/agent-tracing/src/store/loadSnapshot.test.ts@@ -0,0 +1,148 @@+import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import type { ExecutionSnapshot } from '../types';+import { AmbiguousSnapshotIdError, loadSnapshot, MissingTracingBaseUrlError } from './loadSnapshot';++const OP_ID = 'op_1_agt_aaa_tpc_bbb_ccc';++const snapshot = (traceId: string): ExecutionSnapshot =>+ ({+ completedAt: 2,+ operationId: OP_ID,+ startedAt: 1,+ steps: [],+ totalCost: 0,+ totalSteps: 0,+ totalTokens: 0,+ traceId,+ }) as ExecutionSnapshot;++const makeRoot = async () => mkdtemp(path.join(tmpdir(), 'load-snapshot-'));++const writeRemoteCache = async (root: string, operationId: string, traceId = 'trace-remote') => {+ const dir = path.join(root, '.agent-tracing', '_remote');+ await mkdir(dir, { recursive: true });+ await writeFile(path.join(dir, `${operationId}.json`), JSON.stringify(snapshot(traceId)), 'utf8');+};++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('loadSnapshot', () => {+ it('reads a snapshot json path directly', async () => {+ const root = await makeRoot();+ const file = path.join(root, 'snap.json');+ await writeFile(file, JSON.stringify(snapshot('trace-file')), 'utf8');++ expect((await loadSnapshot(file))?.traceId).toBe('trace-file');+ });++ it('serves an operation id from the _remote cache without network', async () => {+ const root = await makeRoot();+ await writeRemoteCache(root, OP_ID);++ expect((await loadSnapshot(OP_ID, { rootDir: root }))?.traceId).toBe('trace-remote');+ });++ it('resolves an op id prefix against the cache', async () => {+ const root = await makeRoot();+ await writeRemoteCache(root, OP_ID);++ expect((await loadSnapshot('op_1', { rootDir: root }))?.traceId).toBe('trace-remote');+ });++ it('refuses to guess between multiple prefix matches', async () => {+ const root = await makeRoot();+ await writeRemoteCache(root, 'op_1_agt_aaa_tpc_bbb_one');+ await writeRemoteCache(root, 'op_1_agt_aaa_tpc_bbb_two');++ await expect(loadSnapshot('op_1', { rootDir: root })).rejects.toThrow(AmbiguousSnapshotIdError);+ });++ it('does not download unless explicitly allowed', async () => {+ const root = await makeRoot();+ const fetchSpy = vi.spyOn(globalThis, 'fetch');++ expect(await loadSnapshot(OP_ID, { rootDir: root })).toBeUndefined();+ expect(fetchSpy).not.toHaveBeenCalled();++ fetchSpy.mockRestore();+ });++ it('explains how to configure the base URL when a download is requested without one', async () => {+ const root = await makeRoot();+ vi.stubEnv('TRACING_BASE_URL', '');++ await expect(loadSnapshot(OP_ID, { allowDownload: true, rootDir: root })).rejects.toThrow(+ MissingTracingBaseUrlError,+ );+ });++ it('returns undefined for an unknown target rather than throwing', async () => {+ const root = await makeRoot();+ expect(await loadSnapshot('nope', { rootDir: root })).toBeUndefined();+ });++ describe('resolveDownloadUrl', () => {+ it('downloads from the resolved URL instead of TRACING_BASE_URL', async () => {+ const root = await makeRoot();+ vi.stubEnv('TRACING_BASE_URL', 'https://public.example.com/agent-traces');+ const fetchSpy = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(+ new Response(Buffer.from(JSON.stringify(snapshot('trace-signed'))), { status: 200 }),+ );++ const result = await loadSnapshot(OP_ID, {+ allowDownload: true,+ resolveDownloadUrl: async () => 'https://signed.example.com/obj?sig=abc',+ rootDir: root,+ });++ expect(result?.traceId).toBe('trace-signed');+ expect(fetchSpy).toHaveBeenCalledWith('https://signed.example.com/obj?sig=abc');++ fetchSpy.mockRestore();+ });++ it('is not consulted when the snapshot is already cached locally', async () => {+ const root = await makeRoot();+ await writeRemoteCache(root, OP_ID);+ const resolveDownloadUrl = vi.fn();++ expect(+ (await loadSnapshot(OP_ID, { allowDownload: true, resolveDownloadUrl, rootDir: root }))+ ?.traceId,+ ).toBe('trace-remote');+ expect(resolveDownloadUrl).not.toHaveBeenCalled();+ });++ it('falls back to TRACING_BASE_URL when the resolver has nothing to offer', async () => {+ const root = await makeRoot();+ vi.stubEnv('TRACING_BASE_URL', 'https://public.example.com/agent-traces');+ const fetchSpy = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(+ new Response(Buffer.from(JSON.stringify(snapshot('trace-public'))), { status: 200 }),+ );++ const result = await loadSnapshot(OP_ID, {+ allowDownload: true,+ resolveDownloadUrl: async () => null,+ rootDir: root,+ });++ expect(result?.traceId).toBe('trace-public');+ expect(fetchSpy).toHaveBeenCalledWith(+ 'https://public.example.com/agent-traces/agt_aaa/tpc_bbb/op_1_agt_aaa_tpc_bbb_ccc.json.zst',+ );++ fetchSpy.mockRestore();+ });+ });+});diff --git a/packages/agent-tracing/src/store/loadSnapshot.ts b/packages/agent-tracing/src/store/loadSnapshot.tsnew file mode 100644index 00000000000..72c63612dcf--- /dev/null+++ b/packages/agent-tracing/src/store/loadSnapshot.ts@@ -0,0 +1,117 @@+import { readFile } from 'node:fs/promises';++import type { ExecutionSnapshot } from '../types';+import { FileSnapshotStore } from './file-store';+import { buildRemoteUrl, isOperationId, loadBaseUrl, RemoteSnapshotStore } from './remote-store';++export interface LoadSnapshotOptions {+ /**+ * Download the snapshot from `TRACING_BASE_URL` when the target is an+ * operation id that is neither recorded locally nor already in the+ * `_remote/` cache. Off by default so read-only callers never hit network.+ */+ allowDownload?: boolean;+ /**+ * Resolve the download URL for an operation id, instead of building one from+ * `TRACING_BASE_URL`. Lets an authenticated caller (`lh`) reach the object+ * through the LobeHub server β which knows the key from+ * `agent_operations.trace_s3_key` and signs it for the caller's own scope β+ * so no public bucket domain has to be configured. Returning `null` falls+ * back to `TRACING_BASE_URL`.+ */+ resolveDownloadUrl?: (operationId: string) => Promise<string | null>;+ /** Root that `.agent-tracing/` resolves against. Defaults to `process.cwd()`. */+ rootDir?: string;+}++export class AmbiguousSnapshotIdError extends Error {+ constructor(+ readonly prefix: string,+ readonly matches: string[],+ ) {+ super(+ `Ambiguous id prefix "${prefix}" β ${matches.length} cached snapshots match. ` ++ `Re-run with the full operation id.`,+ );+ this.name = 'AmbiguousSnapshotIdError';+ }+}++export class MissingTracingBaseUrlError extends Error {+ constructor(readonly operationId: string) {+ super(+ `Snapshot ${operationId} is not available locally and TRACING_BASE_URL is not configured.\n` ++ 'Set it via:\n' ++ ' 1. Environment variable: export TRACING_BASE_URL=https://<bucket-domain>/agent-traces\n' ++ ' 2. File: .agent-tracing/.env with TRACING_BASE_URL=https://...',+ );+ this.name = 'MissingTracingBaseUrlError';+ }+}++const isUrl = (target: string) => target.startsWith('http://') || target.startsWith('https://');++/**+ * Resolve one snapshot from a CLI-style target, in the order callers expect:+ * a `.json` path, an http(s) URL, a full operation id (local store β `_remote/`+ * cache β optional download), an `op_` prefix matched against the cache, a+ * traceId, `latest`, or nothing (latest local).+ *+ * Shared by the `agent-tracing` CLI and by `lh trace`, which needs the same+ * resolution but reaches the model through the authenticated LobeHub server.+ */+export async function loadSnapshot(+ target?: string,+ options: LoadSnapshotOptions = {},+): Promise<ExecutionSnapshot | undefined> {+ const { allowDownload = false, resolveDownloadUrl, rootDir } = options;++ if (target?.endsWith('.json') && !isUrl(target)) {+ return JSON.parse(await readFile(target, 'utf8')) as ExecutionSnapshot;+ }++ if (target && isUrl(target)) {+ const res = await fetch(target);+ if (!res.ok) {+ throw new Error(+ `Failed to fetch snapshot: ${res.status} ${res.statusText}\n URL: ${target}`,+ );+ }+ return (await res.json()) as ExecutionSnapshot;+ }++ const local = await new FileSnapshotStore(rootDir).get(target ?? 'latest');+ if (local) return local;++ if (!target) return undefined;++ const remote = new RemoteSnapshotStore(rootDir);++ if (isOperationId(target)) {+ const cached = await remote.getCached(target);+ if (cached) return cached;++ if (!allowDownload) return undefined;++ const signedUrl = await resolveDownloadUrl?.(target);+ if (signedUrl) return remote.fetch(signedUrl, target);++ const baseUrl = await loadBaseUrl(rootDir);+ if (!baseUrl) throw new MissingTracingBaseUrlError(target);++ const url = buildRemoteUrl(baseUrl, target);+ if (!url) throw new Error(`Failed to parse operation ID: ${target}`);++ return remote.fetch(url, target);+ }++ // Partial op id (e.g. `op_<timestamp>`): resolve against the `_remote/` cache+ // so callers don't have to paste the full `op_..._agt_..._tpc_..._<suffix>`.+ if (target.startsWith('op_')) {+ const matches = await remote.findCachedByPrefix(target);+ if (matches.length === 1) return (await remote.getCached(matches[0])) ?? undefined;+ if (matches.length > 1) throw new AmbiguousSnapshotIdError(target, matches);+ }++ return undefined;+}diff --git a/packages/agent-tracing/src/store/remote-store.ts b/packages/agent-tracing/src/store/remote-store.tsindex a005c2d8879..440c2856873 100644--- a/packages/agent-tracing/src/store/remote-store.ts+++ b/packages/agent-tracing/src/store/remote-store.ts@@ -1,11 +1,25 @@import fs from 'node:fs/promises';import path from 'node:path';import { promisify } from 'node:util';-import { zstdDecompress } from 'node:zlib';+import zlib from 'node:zlib';import type { ExecutionSnapshot } from '../types';-const decompressZstd = promisify(zstdDecompress);+/**+ * `zlib.zstdDecompress` only exists from Node 22.15. Resolved lazily rather+ * than promisified at module scope so that importing this file β which the+ * `lh` command tree does at startup β cannot crash the whole CLI on an older+ * runtime, and so the failure names the actual requirement.+ */+const decompressZstd = async (buf: Buffer): Promise<Buffer> => {+ if (typeof zlib.zstdDecompress !== 'function') {+ throw new Error(+ 'Reading a compressed trace snapshot requires Node >= 22.15 (node:zlib zstd support). ' ++ `Current runtime: ${process.version}.`,+ );+ }+ return promisify(zlib.zstdDecompress)(buf);+};const REMOTE_DIR = '_remote';const ENV_FILE = '.env';