{"data":{"slug":"github-lobehub-lobehub-agents-skills-agent-tracing-6e3d1a455fdb","title":"Inspect Agent Execution Traces","summary":"Use this tool to inspect agent execution traces for debugging and analysis, including detailed step-by-step information, tool calls, arguments, results, and execution context.","url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-agent-tracing-6e3d1a455fdb","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-lobehub-lobehub-agents-skills-agent-tracing-6e3d1a455fdb","markdown_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-agent-tracing-6e3d1a455fdb.md","download_url":"https:\/\/skillshunter.net\/skills\/github-lobehub-lobehub-agents-skills-agent-tracing-6e3d1a455fdb\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"To use this tool, run the CLI from the repo root where `.agent-tracing\/` is generated. Completed snapshots are stored as `.agent-tracing\/{ISO-timestamp}_{traceId-short}.json`, and the latest snapshot is available via `.agent-tracing\/latest.json`.","instructions":"---\nname: agent-tracing\ndescription: 'Use for agent traces by operation ID (\u62c9\u7ebf\u4e0a tracing): failed tools, arguments\/results, available tools, execution location, LLM calls and context.'\nuser-invocable: false\n---\n\n# Agent Tracing CLI Guide\n\n`@lobechat\/agent-tracing` is a zero-config local dev tool that records agent execution snapshots to disk and provides a CLI to inspect them.\n\n## How It Works\n\nIn `NODE_ENV=development`, `AgentRuntimeService.executeStep()` automatically records each step to `.agent-tracing\/` as partial snapshots. When the operation completes, the partial is finalized into a complete `ExecutionSnapshot` JSON file.\n\n**Data flow**: executeStep loop -> build `StepPresentationData` -> write partial snapshot to disk -> on completion, finalize to `.agent-tracing\/{timestamp}_{traceId}.json`\n\n**Context engine capture**: In `RuntimeExecutors.ts`, the `call_llm` executor calls `ctx.tracingContextEngine(input, output, metadata)` after `serverMessagesEngine()` processes messages. `AgentRuntimeService.executeStep` buffers the call per step and forwards it to `OperationTraceRecorder.appendStep` as the typed `contextEngine` field. CE flows through this side channel rather than the `events` array so its heavy payload (agentDocuments, systemRole, \u2026) never enters the Redis state pipeline (LOBE-9110). `metadata` carries the pipeline's per-request decision records (trim stats, cache-warmth gates, truncation counts).\n\n## Package Location\n\n```\npackages\/agent-tracing\/\n  src\/\n    types.ts          # ExecutionSnapshot, StepSnapshot, SnapshotSummary\n    store\/\n      types.ts        # ISnapshotStore interface\n      file-store.ts   # FileSnapshotStore (.agent-tracing\/*.json)\n    recorder\/\n      index.ts        # appendStepToPartial(), finalizeSnapshot()\n    viewer\/\n      index.ts        # Terminal rendering: renderSnapshot, renderStepDetail, renderMessageDetail, renderSummaryTable, renderPayload, renderPayloadTools, renderMemory\n    cli\/\n      index.ts        # CLI entry point (#!\/usr\/bin\/env bun)\n      inspect.ts      # Inspect command (default)\n      partial.ts      # Partial snapshot commands (list, inspect, clean)\n    index.ts          # Barrel exports\n```\n\n## Data Storage\n\n- Completed snapshots: `.agent-tracing\/{ISO-timestamp}_{traceId-short}.json`\n- Latest symlink: `.agent-tracing\/latest.json`\n- In-progress partials: `.agent-tracing\/_partial\/{operationId}.json`\n- Downloaded remote snapshots: `.agent-tracing\/_remote\/{operationId}.json`\n- `FileSnapshotStore` resolves from `process.cwd()` \u2014 **run CLI from the repo root**\n\n## Remote Traces (Production \/ Staging)\n\nServer deployments also upload completed snapshots to object storage (zstd-compressed; the key is stored in `agent_operations.trace_s3_key`).\n\n**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 \u2014 no `TRACING_BASE_URL`, no bucket domain, and no SQL to turn a topic id into an operation id:\n\n```bash\nlh trace op list --topic tpc_xxx # operations of a topic, newest first, with a TRACE column\nlh trace op inspect op_xxx_agt_xxx_tpc_xxx_xxxx\nlh trace op inspect op_xxx_agt_xxx_tpc_xxx_xxxx -T # tool injection (enabledToolIds, manifests)\n```\n\n`TRACE = \u2014` 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.\n\nBackend: 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.\n\n**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:\n\n- env var: `TRACING_BASE_URL=https:\/\/<bucket-public-domain>\/agent-traces`\n- or `.agent-tracing\/.env` in the repo root with the same `TRACING_BASE_URL=...` line\n\nThe deployment-specific value is private to each deployment and intentionally not recorded in this repo. Find the operation id by hand first:\n\n```sql\nSELECT id, trace_s3_key FROM agent_operations WHERE topic_id = 'tpc_xxx';\n```\n\nEither way the snapshot is cached to `.agent-tracing\/_remote\/<opId>.json`, and every `inspect` flag works the same as for local traces.\n\nImplementation: `packages\/agent-tracing\/src\/store\/loadSnapshot.ts` (resolution order: local store \u2192 `_remote\/` cache \u2192 injected `resolveDownloadUrl` \u2192 `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.\n\n## Goal Trajectories\n\nA goal is one complete _goal_ execution the way an operation is one complete agent execution, so it gets the same trace format one level up: `GoalTrajectory : AdvanceSnapshot` mirrors `ExecutionSnapshot : StepSnapshot`. There is no table of advances, exactly as there is no `agent_steps` table \u2014 `goal_traces` holds one rollup row per goal plus the object key, and the detail lives in the object.\n\nThe leaves join back down: an advance records the `operationId`s it put in flight (on `tick.effects[].operationId`), so `lh trace op inspect <opId>` continues from where the goal trace stops.\n\n```bash\nagent-tracing goal               # list local goal trajectories\nagent-tracing goal goal_xxx      # the run: triggers, outcomes, graph, gates, ops\nagent-tracing goal goal_xxx -a 3 # one advance in full, with the frontier it ranked\nagent-tracing goal goal_xxx -j   # raw JSON\n```\n\nWhat each tick records is the **decision input**, not just the result: the graph it read (as a delta against the previous tick), the budget it evaluated, the responsible task's state, and every eligible work node **including the ones it passed over**. Without the losers a trace cannot answer \"why not that node\".\n\n**Storage** follows the operation switch, so a deployment that keeps one keeps the other:\n\n- Completed: `goal-traces\/{goalId}.json.zst`\n- In progress: `goal-traces\/_partial\/{goalId}.json.zst` (an unfinished long-horizon goal is the normal thing to inspect)\n- Dev: `.goal-tracing\/{goalId}.json`\n\n**Replay.** `replayGoalAgainstCurrentCoordinator(trajectory)` re-runs the real `decideNextMove` over the recorded inputs and reports `{advanceSeq, tickIndex, field, recorded, replayed}` wherever the current coordinator would now choose differently. This reproduces the coordinator's _decisions_ exactly; it says nothing about whether the dispatched work would have gone the same way.\n\nImplementation: `packages\/agent-tracing\/src\/goal\/`, recorded through `apps\/server\/src\/services\/goal\/advanceGoal.ts` (the single funnel every advance passes through) via the `onDecision` side channel on `GoalService.tick`.\n\n## CLI Commands\n\nAll commands run from the **repo root**:\n\n```bash\n# View latest trace (tree overview, `inspect` is the default command)\nagent-tracing\nagent-tracing inspect\nagent-tracing inspect <traceId>\nagent-tracing inspect latest\n\n# List recent snapshots\nagent-tracing list\nagent-tracing list -l 20\n\n# Inspect specific step (-s is short for --step)\nagent-tracing inspect <traceId> -s 0\n\n# View messages (-m is short for --messages)\nagent-tracing inspect <traceId> -s 0 -m\n\n# View full content of a specific message (by index shown in -m output)\nagent-tracing inspect <traceId> -s 0 --msg 2\nagent-tracing inspect <traceId> -s 0 --msg-input 1\n\n# View tool call\/result details (-t is short for --tools)\nagent-tracing inspect <traceId> -s 1 -t\n\n# View raw events (-e is short for --events)\nagent-tracing inspect <traceId> -s 0 -e\n\n# View runtime context (-c is short for --context)\nagent-tracing inspect <traceId> -s 0 -c\n\n# View context engine input overview (-p is short for --payload)\nagent-tracing inspect <traceId> -p\nagent-tracing inspect <traceId> -s 0 -p\n\n# View available tools in payload (-T is short for --payload-tools)\nagent-tracing inspect <traceId> -T\nagent-tracing inspect <traceId> -s 0 -T\n\n# View user memory (-M is short for --memory)\nagent-tracing inspect <traceId> -M\nagent-tracing inspect <traceId> -s 0 -M\n\n# Raw JSON output (-j is short for --json)\nagent-tracing inspect <traceId> -j\nagent-tracing inspect <traceId> -s 0 -j\n\n# List in-progress partial snapshots\nagent-tracing partial list\n\n# Inspect a partial (use `inspect` directly \u2014 all flags work with partial IDs)\nagent-tracing inspect <partialOperationId>\nagent-tracing inspect <partialOperationId> -T\nagent-tracing inspect <partialOperationId> -p\n\n# Clean up stale partial snapshots\nagent-tracing partial clean\n\n# Map the context window composition of every LLM call (cm \/ map are aliases)\nagent-tracing ctx-map\nagent-tracing ctx-map <operationId|traceId|path.json>\nagent-tracing ctx-map --html            # standalone report under .agent-tracing\/_reports\/\nagent-tracing ctx-map --html out.html\n\n# Re-issue a recorded LLM call against other models (see \"replay\" below)\nagent-tracing replay <operationId|traceId|path.json>\nagent-tracing replay <target> -s 4 -m openai\/gpt-5,anthropic\/claude-sonnet-5\nagent-tracing replay <target> --all-steps\n```\n\n## replay \u2014 Re-issue a Frozen Call\n\nA snapshot already freezes everything one LLM call saw: `steps[].contextEngine.output` is the\nexact message array sent to the model, `context.payload.tools` the toolset it could reach.\n`replay` sends that frozen payload back out with only the model swapped, so a difference in\noutput is attributable to the model rather than to context assembly. If every model fails the\nsame payload, the context is at fault; if some pass, it is model selection.\n\nAvailable from both CLIs \u2014 `agent-tracing replay` (reads `LOBEHUB_JWT`) and `lh trace op replay`\n(uses the `lh login` session). Both need credentials because the call goes out through the\nLobeHub chat route.\n\n```bash\n# One call: defaults to the last call_llm step and the model the op ran on\nlh trace op replay <operationId>\nlh trace op replay <operationId> -s 4 -m openai\/gpt-5,anthropic\/claude-sonnet-5\nlh trace op replay <operationId> --judge \"answers with a concrete file path\"\n\n# Every call of the operation\nlh trace op replay <operationId> --all-steps\nlh trace op replay <operationId> --all-steps --concurrency 8\n```\n\n`--all-steps` answers the question the whole feature exists for: **take a run that succeeded, put\nanother model on it, and see whether that model also gets the job done.** It ends in a PASS \/ FAIL\nverdict from an llm-rubric judge comparing the replayed outcome against the recorded one; pass\n`--judge \"<criteria>\"` to define success yourself instead of using the default rubric.\n\nThe judge scores the **outcome, not the route**. A model that solved the same problem by calling\ndifferent tools has passed. The per-call tool comparison (`toolSignature`) is reported underneath\nas supporting evidence \u2014 where the run took another path \u2014 and never decides pass \/ fail. A final\ncall that never reached the model is a FAIL, not a missing verdict.\n\nEach call is replayed independently, against the payload the harness actually built for it, so a\ndifferent answer at call 2 cannot contaminate call 4, a call that fails to reach the provider\ncosts only itself, and the calls go out concurrently (4 at a time by default).\n\nChaining the nodes \u2014 feeding each replayed output into the next \u2014 was built and then removed. A\ntrace cannot regenerate tool output, only hand back what was recorded, so the moment the model\ndeviates there is no ground truth left; the run then measures nothing while still looking like it\nsucceeded. Independent replay is the design, not a fallback.\n\nKnown limitation: **sampling parameters are not recorded.** The recorder stores the runtime step\ncontext under `context.payload`, not the provider request body, so temperature, `top_p`,\n`max_tokens`, penalties and reasoning config are absent from every trace written so far. Replays\nuse the server's current defaults for those. Model-to-model comparisons stay valid (every target\ngets the same request); comparisons against the recorded output do not, for an operation that ran\nwith non-default settings. `--temperature` \/ `--max-tokens` override explicitly. The CLI prints a\n`note` line whenever a replay is running without recorded parameters.\n\n## ctx-map \u2014 Context Window Composition\n\n`ctx-map` renders one row per `call_llm` step: the messages that call sent to the model, split\ninto typed segments (system \/ injected block \/ user \/ reasoning \/ tool call \/ tool result) with\nwidth proportional to tokens, laid against the model's context window.\n\nThe second axis is what `ctx-lint` cannot show: each row is diffed against the previous call, so\nthe longest identical **message prefix** \u2014 the part a provider's prefix cache can reuse \u2014 is\nmarked, along with the first message that mutated and the tokens re-processed behind it. A small\ninjected block carrying a relative timestamp (`1m ago` \u2192 `now`) invalidates every token after it,\nwhich shows up as a break marker early in the row.\n\nReading a row:\n\n- **Block colors** encode role directly: orange system, green user, blue assistant, gray tool.\n  Assistant reasoning, content, and tool calls use different steps of the same blue scale;\n  framework-injected blocks use a lighter orange than the system prompt. Every value is a step\n  index into a LobeHub scale vendored in `viewer\/contextMapScales.ts`, with assignments in\n  `viewer\/contextMapPalette.ts`. The HTML report ships both themes and follows the system theme.\n- **Neutral message frames** group segments that belong to the same payload message. Every role\n  uses the same frame color: the outline communicates structure only, while the block fill carries\n  role and subtype semantics. The original framed layout uses padding inside each message and a\n  small track gap between messages, keeping each payload message visually distinct.\n- **Fill** says whether the provider reused it: shaded `\u2593` (HTML: 60%-opaque hatch) was served\n  from the prefix cache; solid `\u2588` (HTML: flat) was re-processed by the model.\n- **The line under the track** is the cache ledger \u2014 a bracket \/ green band spanning exactly the\n  cached prefix, then the break marker (`\u25b2` in the terminal, a red rule through the track in\n  HTML) at the column where reuse stopped, with the reason and the re-processed tokens.\n\n| Flag            | Short | Description                                                |\n| --------------- | ----- | ---------------------------------------------------------- |\n| `--html [path]` |       | Standalone HTML report (hover a segment for its content)   |\n| `--width <n>`   | `-w`  | Track width in terminal columns                            |\n| `--window <n>`  |       | Override the model context window used as the track        |\n| `--full-window` |       | Always scale to the full window, never to the largest call |\n| `--json`        | `-j`  | Per-call segments + cache stats                            |\n\nThe track scales to the context window; when the window dwarfs the payloads (a 50k payload on a\n1M window) it falls back to the largest call so the composition stays readable, and the header\nsays which basis is in use. Analysis lives in `analysis\/contextMap.ts` and is exported as\n`buildContextMap()` for downstream corpus work.\n\n## Inspect Flag Reference\n\n| Flag              | Short | Description                                                                                       | Default Step |\n| ----------------- | ----- | ------------------------------------------------------------------------------------------------- | ------------ |\n| `--step <n>`      | `-s`  | Target a specific step                                                                            | \u2014            |\n| `--messages`      | `-m`  | Messages context (CE input \u2192 params \u2192 LLM payload)                                                | \u2014            |\n| `--tools`         | `-t`  | Tool calls & results (what agent invoked)                                                         | \u2014            |\n| `--events`        | `-e`  | Raw events (llm_start, llm_result, etc.)                                                          | \u2014            |\n| `--context`       | `-c`  | Runtime context & payload (raw)                                                                   | \u2014            |\n| `--system-role`   | `-r`  | Full system role content                                                                          | 0            |\n| `--env`           |       | Environment context                                                                               | 0            |\n| `--payload`       | `-p`  | Context engine input overview (model, knowledge, tools summary, memory summary, platform context) | 0            |\n| `--payload-tools` | `-T`  | Available tools detail (plugin manifests + LLM function definitions)                              | 0            |\n| `--memory`        | `-M`  | Full user memory (persona, identity, contexts, preferences, experiences)                          | 0            |\n| `--diff <n>`      | `-d`  | Diff against step N (use with `-r` or `--env`)                                                    | \u2014            |\n| `--msg <n>`       |       | Full content of message N from Final LLM Payload                                                  | \u2014            |\n| `--msg-input <n>` |       | Full content of message N from Context Engine Input                                               | \u2014            |\n| `--json`          | `-j`  | Output as JSON (combinable with any flag above)                                                   | \u2014            |\n\nFlags marked \"Default Step: 0\" auto-select step 0 if `--step` is not provided. All flags support `latest` or omitted traceId.\n\n## Typical Debug Workflow\n\n```bash\n# 1. Trigger an agent operation in the dev UI\n\n# 2. See the overview\nagent-tracing inspect\n\n# 3. List all traces, get traceId\nagent-tracing list\n\n# 4. Quick overview of what was fed into context engine\nagent-tracing inspect -p\n\n# 5. Inspect a specific step's messages to see what was sent to the LLM\nagent-tracing inspect TRACE_ID -s 0 -m\n\n# 6. Drill into a truncated message for full content\nagent-tracing inspect TRACE_ID -s 0 --msg 2\n\n# 7. Check available tools vs actual tool calls\nagent-tracing inspect -T      # available tools\nagent-tracing inspect -s 1 -t # actual tool calls & results\n\n# 8. Inspect user memory injected into the conversation\nagent-tracing inspect -M\n\n# 9. Diff system role between steps (multi-step agents)\nagent-tracing inspect TRACE_ID -r -d 2\n```\n\n## Key Types\n\n```typescript\ninterface ExecutionSnapshot {\n  traceId: string;\n  operationId: string;\n  model?: string;\n  provider?: string;\n  startedAt: number;\n  completedAt?: number;\n  completionReason?:\n    'done' | 'error' | 'interrupted' | 'max_steps' | 'cost_limit' | 'waiting_for_human';\n  totalSteps: number;\n  totalTokens: number;\n  totalCost: number;\n  error?: { type: string; message: string };\n  steps: StepSnapshot[];\n}\n\ninterface StepSnapshot {\n  stepIndex: number;\n  stepType: 'call_llm' | 'call_tool';\n  executionTimeMs: number;\n  content?: string; \/\/ LLM output\n  reasoning?: string; \/\/ Reasoning\/thinking\n  inputTokens?: number;\n  outputTokens?: number;\n  toolsCalling?: Array<{ apiName: string; identifier: string; arguments?: string }>;\n  toolsResult?: Array<{\n    apiName: string;\n    identifier: string;\n    isSuccess?: boolean;\n    output?: string;\n  }>;\n  messages?: any[]; \/\/ DB messages before step\n  context?: { phase: string; payload?: unknown; stepContext?: unknown };\n  events?: Array<{ type: string; [key: string]: unknown }>;\n  contextEngine?: {\n    input?: unknown; \/\/ contextEngineInput minus messages + toolsConfig (reconstructible from baseline)\n    output?: unknown; \/\/ processed messages array (final LLM payload)\n    metadata?: unknown; \/\/ pipeline decision records (trim stats, cache gates, truncation counts)\n  };\n}\n```\n\n## --messages Output Structure\n\nWhen using `--messages`, the output shows three sections (if context engine data is available):\n\n1. **Context Engine Input** \u2014 DB messages passed to the engine, with `[0]`, `[1]`, ... indices. Use `--msg-input N` to view full content.\n2. **Context Engine Params** \u2014 systemRole, model, provider, knowledge, tools, userMemory, etc.\n3. **Final LLM Payload** \u2014 Processed messages after context engine (system date injection, user memory, history truncation, etc.), with `[0]`, `[1]`, ... indices. Use `--msg N` to view full content.\n\n## Integration Points\n\n- **Recording**: `apps\/server\/src\/services\/agentRuntime\/AgentRuntimeService\/executeStep\/index.ts` \u2014 in `executeStep()`, after `saveAndPublishStep` builds `stepPresentationData`, writes partial snapshot in dev mode\n- **Context engine capture**: `apps\/server\/src\/modules\/AgentRuntime\/RuntimeExecutors.ts` \u2014 in `call_llm` executor, after `serverMessagesEngine()` returns, calls `ctx.tracingContextEngine(input, output, metadata)`. `AgentRuntimeService.executeStep` buffers it per step and passes it to `traceRecorder.appendStep` as the typed `contextEngine` field (kept off the `events` array to stay out of Redis state).\n- **Store**: `FileSnapshotStore` reads\/writes to `.agent-tracing\/` relative to `process.cwd()`\n","use_cases":["Debugging failed tool calls during agent execution","Analyzing agent decision-making process","Reviewing execution context and metadata","Inspecting LLM calls and context engine data"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/lobehub\/lobehub\/blob\/54382b5c8e81544da454fa6d7b50f461a562c1ee\/.agents\/skills\/agent-tracing\/SKILL.md","source_commit":"54382b5c8e81544da454fa6d7b50f461a562c1ee","license":null,"version":null,"listing_approved_at":"2026-11-22","created_at":"2026-11-21T10:56:10.000000Z","updated_at":"2026-11-22T11:17:05.000000Z","seo_title":"Inspect Agent Execution Traces","seo_description":"Inspect agent execution traces to debug and analyze agent behavior with detailed step-by-step information, including tool calls, execution context, and metadata.","seo_keywords":["agent tracing","debug agent execution","inspect trace details","agent execution analysis","trace metadata review","agent tool calls","execution context inspection"]}}