Skip to content

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

✨ feat(agent-tracing): visualize context composition (#18114)

Arvin Xu7c91fe29c7c2
diff --git a/.agents/skills/agent-tracing/SKILL.md b/.agents/skills/agent-tracing/SKILL.md
index ccfa2ab8332..08bb8979626 100644
--- a/.agents/skills/agent-tracing/SKILL.md
+++ b/.agents/skills/agent-tracing/SKILL.md
@@ -132,8 +132,56 @@ agent-tracing inspect <partialOperationId> -p
# Clean up stale partial snapshots
agent-tracing partial clean
+
+# Map the context window composition of every LLM call (cm / map are aliases)
+agent-tracing ctx-map
+agent-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
```
+## ctx-map β€” Context Window Composition
+
+`ctx-map` renders one row per `call_llm` step: the messages that call sent to the model, split
+into typed segments (system / injected block / user / reasoning / tool call / tool result) with
+width proportional to tokens, laid against the model's context window.
+
+The second axis is what `ctx-lint` cannot show: each row is diffed against the previous call, so
+the longest identical **message prefix** β€” the part a provider's prefix cache can reuse β€” is
+marked, along with the first message that mutated and the tokens re-processed behind it. A small
+injected block carrying a relative timestamp (`1m ago` β†’ `now`) invalidates every token after it,
+which shows up as a break marker early in the row.
+
+Reading a row:
+
+- **Block colors** encode role directly: orange system, green user, blue assistant, gray tool.
+ Assistant reasoning, content, and tool calls use different steps of the same blue scale;
+ framework-injected blocks use a lighter orange than the system prompt. Every value is a step
+ index into a LobeHub scale vendored in `viewer/contextMapScales.ts`, with assignments in
+ `viewer/contextMapPalette.ts`. The HTML report ships both themes and follows the system theme.
+- **Neutral message frames** group segments that belong to the same payload message. Every role
+ uses the same frame color: the outline communicates structure only, while the block fill carries
+ role and subtype semantics. The original framed layout uses padding inside each message and a
+ small track gap between messages, keeping each payload message visually distinct.
+- **Fill** says whether the provider reused it: shaded `β–“` (HTML: 60%-opaque hatch) was served
+ from the prefix cache; solid `β–ˆ` (HTML: flat) was re-processed by the model.
+- **The line under the track** is the cache ledger β€” a bracket / green band spanning exactly the
+ cached prefix, then the break marker (`β–²` in the terminal, a red rule through the track in
+ HTML) at the column where reuse stopped, with the reason and the re-processed tokens.
+
+| Flag | Short | Description |
+| --------------- | ----- | ---------------------------------------------------------- |
+| `--html [path]` | | Standalone HTML report (hover a segment for its content) |
+| `--width <n>` | `-w` | Track width in terminal columns |
+| `--window <n>` | | Override the model context window used as the track |
+| `--full-window` | | Always scale to the full window, never to the largest call |
+| `--json` | `-j` | Per-call segments + cache stats |
+
+The track scales to the context window; when the window dwarfs the payloads (a 50k payload on a
+1M window) it falls back to the largest call so the composition stays readable, and the header
+says which basis is in use. Analysis lives in `analysis/contextMap.ts` and is exported as
+`buildContextMap()` for downstream corpus work.
+
## Inspect Flag Reference
| Flag | Short | Description | Default Step |
diff --git a/packages/agent-tracing/package.json b/packages/agent-tracing/package.json
index c2f77ddcae4..8b0b8280921 100644
--- a/packages/agent-tracing/package.json
+++ b/packages/agent-tracing/package.json
@@ -17,7 +17,8 @@
},
"dependencies": {
"commander": "^13.1.0",
- "gpt-tokenizer": "^3.4.0"
+ "gpt-tokenizer": "^3.4.0",
+ "model-bank": "workspace:*"
},
"devDependencies": {
"vitest": "^3.2.6"
diff --git a/packages/agent-tracing/src/analysis/contextLint.ts b/packages/agent-tracing/src/analysis/contextLint.ts
index 19d95f05fe7..5c8d1351591 100644
--- a/packages/agent-tracing/src/analysis/contextLint.ts
+++ b/packages/agent-tracing/src/analysis/contextLint.ts
@@ -97,16 +97,18 @@ const TRUNCATION_MARKER_RE =
// Payload reconstruction
// ---------------------------------------------------------------------------
-interface PayloadMessage {
+export interface PayloadMessage {
content?: unknown;
name?: string;
- reasoning?: string;
+ /** String on most providers, `{ content }` on some β€” normalize before use. */
+ reasoning?: unknown;
+ reasoning_content?: unknown;
role: string;
tool_call_id?: string;
tool_calls?: Array<{ function?: { arguments?: string; name?: string }; id?: string }>;
}
-function contentText(m: PayloadMessage): string {
+export function contentText(m: PayloadMessage): string {
if (typeof m.content === 'string') return m.content;
if (Array.isArray(m.content)) {
return m.content
diff --git a/packages/agent-tracing/src/analysis/contextMap.test.ts b/packages/agent-tracing/src/analysis/contextMap.test.ts
new file mode 100644
index 00000000000..60471577751
--- /dev/null
+++ b/packages/agent-tracing/src/analysis/contextMap.test.ts
@@ -0,0 +1,230 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ExecutionSnapshot } from '../types';
+import { buildContextMap } from './contextMap';
+
+const snapshot = (steps: any[], extra: Partial<ExecutionSnapshot> = {}): ExecutionSnapshot =>
+ ({
+ operationId: 'op_test',
+ startedAt: 0,
+ steps,
+ totalCost: 0,
+ totalSteps: steps.length,
+ totalTokens: 0,
+ traceId: 't',
+ ...extra,
+ }) as ExecutionSnapshot;
+
+const sys = (content: string) => ({ content, role: 'system' });
+const user = (content: string) => ({ content, role: 'user' });
+
+describe('buildContextMap', () => {
+ it('splits an assistant message into reasoning, content and tool-call segments', () => {
+ const map = buildContextMap(
+ snapshot([
+ {
+ contextEngine: {
+ output: [
+ sys('you are a helpful agent'),
+ {
+ content: 'let me look that up',
+ reasoning: 'the user wants the weather',
+ role: 'assistant',
+ tool_calls: [{ function: { arguments: '{}', name: 'getWeather' }, id: 'c1' }],
+ },
+ ],
+ },
+ messagesBaseline: [],
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ ]),
+ );
+
+ expect(map.calls).toHaveLength(1);
+ const kinds = map.calls[0].segments.map((s) => s.kind);
+ expect(kinds).toEqual(['system', 'reasoning', 'assistant', 'tool_call']);
+ // all three assistant segments point back at the same payload message, and share its role
+ expect(map.calls[0].segments.slice(1).every((s) => s.messageIndex === 1)).toBe(true);
+ expect(map.calls[0].segments.map((s) => s.role)).toEqual([
+ 'system',
+ 'assistant',
+ 'assistant',
+ 'assistant',
+ ]);
+ expect(map.calls[0].segments.at(-1)!.label).toBe('getWeather');
+ });
+
+ it('tags injected blocks with the user role that carried them', () => {
+ const map = buildContextMap(
+ snapshot([
+ {
+ contextEngine: {
+ output: [
+ sys('role'),
+ user('<agent_documents_index>\n3 docs'),
+ { content: 'ok', name: 'search', role: 'tool', tool_call_id: 'c1' },
+ ],
+ },
+ messagesBaseline: [],
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ ]),
+ );
+
+ expect(map.calls[0].segments.map((s) => [s.kind, s.role])).toEqual([
+ ['system', 'system'],
+ ['injected', 'user'],
+ ['tool_result', 'tool'],
+ ]);
+ });
+
+ it('marks a payload message with no DB counterpart as an injected block', () => {
+ const map = buildContextMap(
+ snapshot([
+ {
+ contextEngine: {
+ output: [sys('role'), user('<agent_documents_index>\n3 docs'), user('hello there')],
+ },
+ messagesBaseline: [user('hello there')],
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ ]),
+ );
+
+ const [, injected, real] = map.calls[0].segments;
+ expect(injected.kind).toBe('injected');
+ expect(injected.label).toBe('<agent_documents_index>');
+ expect(real.kind).toBe('user');
+ });
+
+ it('keeps the prefix intact when a payload only grows at the end', () => {
+ const first = [sys('role'), user('hello')];
+ const map = buildContextMap(
+ snapshot([
+ {
+ contextEngine: { output: first },
+ messagesBaseline: [],
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ {
+ contextEngine: { output: [...first, { content: 'hi', role: 'assistant' }] },
+ stepIndex: 1,
+ stepType: 'call_llm',
+ },
+ ]),
+ );
+
+ expect(map.calls[1].breakMessageIndex).toBeUndefined();
+ expect(map.calls[1].stablePrefixMessages).toBe(2);
+ expect(map.calls[1].cachedTokens).toBe(map.calls[0].totalTokens);
+ expect(map.summary.brokenPrefixCalls).toBe(0);
+ });
+
+ it('attributes a broken prefix to the mutated message and counts the unchanged tail', () => {
+ const tail = { content: 'a stable assistant answer', role: 'assistant' };
+ const map = buildContextMap(
+ snapshot([
+ {
+ contextEngine: { output: [sys('role'), user('docs updated 1m ago'), tail] },
+ messagesBaseline: [],
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ {
+ // only the injected block changed β€” the tail behind it is byte-identical
+ contextEngine: { output: [sys('role'), user('docs updated just now'), tail] },
+ stepIndex: 1,
+ stepType: 'call_llm',
+ },
+ ]),
+ );
+
+ const second = map.calls[1];
+ expect(second.breakMessageIndex).toBe(1);
+ expect(second.breakReason).toContain('injected block');
+ expect(second.wastedTokens).toBeGreaterThan(0);
+ expect(second.reprocessedTokens).toBe(second.totalTokens - second.cachedTokens);
+ expect(map.summary.brokenPrefixCalls).toBe(1);
+ });
+
+ it('names a compression reset instead of blaming the rewritten message', () => {
+ const map = buildContextMap(
+ snapshot([
+ {
+ contextEngine: { output: [sys('role'), user('turn one'), user('turn two')] },
+ messagesBaseline: [],
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ {
+ contextEngine: { output: [sys('role'), user('<compressed_history_summary>\nrecap')] },
+ isCompressionReset: true,
+ stepIndex: 1,
+ stepType: 'call_llm',
+ },
+ ]),
+ );
+
+ expect(map.calls[1].breakReason).toBe('context compression reset');
+ });
+
+ it('still names the reset when the compressed history only reaches the next call', () => {
+ const map = buildContextMap(
+ snapshot([
+ {
+ contextEngine: { output: [sys('role'), user('turn one'), user('turn two')] },
+ messagesBaseline: [],
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ // compression happens here, but this call still ran on the pre-compression payload
+ {
+ contextEngine: {},
+ isCompressionReset: true,
+ stepIndex: 1,
+ stepType: 'call_llm',
+ },
+ {
+ contextEngine: { output: [sys('role'), user('<compressed_history_summary>\nrecap')] },
+ stepIndex: 2,
+ stepType: 'call_llm',
+ },
+ ]),
+ );
+
+ expect(map.calls[2].breakReason).toBe('context compression reset');
+ });
+
+ it('reports composition of the final call rather than the sum of every call', () => {
+ const map = buildContextMap(
+ snapshot([
+ {
+ contextEngine: { output: [sys('role')] },
+ messagesBaseline: [],
+ stepIndex: 0,
+ stepType: 'call_llm',
+ },
+ {
+ contextEngine: { output: [sys('role'), user('hello')] },
+ stepIndex: 1,
+ stepType: 'call_llm',
+ },
+ ]),
+ );
+
+ const finalCall = map.calls.at(-1)!;
+ const totalKindTokens = Object.values(map.summary.kindTokens).reduce((a, b) => a + b, 0);
+ expect(totalKindTokens).toBe(finalCall.totalTokens);
+ });
+
+ it('returns an empty map when no payload was recorded', () => {
+ const map = buildContextMap(snapshot([{ stepIndex: 0, stepType: 'call_tool' }]));
+ expect(map.calls).toEqual([]);
+ expect(map.payloadSource).toBe('none');
+ expect(map.summary.llmCalls).toBe(0);
+ });
+});
diff --git a/packages/agent-tracing/src/analysis/contextMap.ts b/packages/agent-tracing/src/analysis/contextMap.ts
new file mode 100644
index 00000000000..f1e51c03749
--- /dev/null
+++ b/packages/agent-tracing/src/analysis/contextMap.ts
@@ -0,0 +1,371 @@
+import { encode } from 'gpt-tokenizer';
+
+import type { ExecutionSnapshot } from '../types';
+import { reconstructMessages } from '../utils/reconstruct';
+import { contentText, type PayloadMessage, resolvePayloads } from './contextLint';
+
+/**
+ * Context Map β€” the *shape* of every context window an operation sent to the model,
+ * one row per `call_llm` step. Where `contextLint` collapses the final payload into
+ * scalar shares, this keeps both structural axes:
+ *
+ * - horizontal: each message split into typed segments (system / injected / user /
+ * reasoning / tool_call / tool_result), width proportional to tokens, against the
+ * model's full context window as the track.
+ * - vertical: how each call differs from the previous one β€” the longest identical
+ * message prefix is what a provider's prefix cache can reuse, so the first message
+ * that mutates marks where caching breaks and everything after it gets re-processed.
+ *
+ * The second axis is what makes re-materialized context visible: a 2k injected block
+ * carrying a relative timestamp mutates every call and invalidates the whole tail
+ * behind it, which no single-payload rule can see.
+ */
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+export type SegmentKind =
+ 'system' | 'injected' | 'user' | 'reasoning' | 'assistant' | 'tool_call' | 'tool_result';
+
+/** Payload message roles β€” the wrapper a segment belongs to. */
+export type MessageRole = 'system' | 'user' | 'assistant' | 'tool';
+
+export interface ContextSegment {
+ kind: SegmentKind;
+ /** Short human label: tool name, injected block tag, or the role. */
+ label: string;
+ /** Index of the owning message in the payload β€” several segments may share one. */
+ messageIndex: number;
+ preview: string;
+ /** Role of the owning message β€” segments sharing a messageIndex share a role. */
+ role: MessageRole;
+ tokens: number;
+ /** Identical to the segment at the same position in the previous call's payload. */
+ unchanged: boolean;
+}
+
+export interface ContextCall {
+ /** Message index where the payload first diverges from the previous call. */
+ breakMessageIndex?: number;
+ /** Why the prefix broke, e.g. `injected block <agent_documents_index> mutated`. */
+ breakReason?: string;
+ /** Tokens in the identical leading messages a prefix cache could reuse. */
+ cachedTokens: number;
+ callIndex: number;
+ /** Tokens the model must re-process because the prefix broke before them. */
+ reprocessedTokens: number;
+ segments: ContextSegment[];
+ stablePrefixMessages: number;
+ stepIndex: number;
+ totalTokens: number;
+ /**
+ * Tokens that were byte-identical to the previous call yet sit behind the break β€”
+ * they would have been cache hits had the earlier message not mutated.
+ */
+ wastedTokens: number;
+}
+
+export interface ContextMapSummary {
+ /** Calls whose prefix broke before the payload's own growth point. */
+ brokenPrefixCalls: number;
+ /**
+ * Composition of the final call's context window. Summing every call instead would
+ * count the same system prompt once per call and inflate whatever repeats most.
+ */
+ kindTokens: Record<SegmentKind, number>;
+ llmCalls: number;
+ maxCallTokens: number;
+ totalReprocessedTokens: number;
+ totalWastedTokens: number;
+}
+
+export interface ContextMap {
+ calls: ContextCall[];
+ contextWindowTokens?: number;
+ model?: string;
+ operationId: string;
+ payloadSource: 'ce' | 'legacy' | 'none';
+ provider?: string;
+ summary: ContextMapSummary;
+}
+
+export interface BuildContextMapOptions {
+ /** Model context window used as the track width; omit to scale to the largest call. */
+ contextWindowTokens?: number;
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+const KINDS: SegmentKind[] = [
+ 'system',
+ 'injected',
+ 'user',
+ 'reasoning',
+ 'assistant',
+ 'tool_call',
+ 'tool_result',
+];
+
+const PREVIEW_LEN = 120;
+
+const preview = (text: string) => text.replaceAll(/\s+/g, ' ').trim().slice(0, PREVIEW_LEN);
+
+/** Leading XML-ish tag of an injected block, e.g. `<agent_documents_index>`. */
+function blockTag(text: string): string | undefined {
+ const match = /^\s*<([\w-]+)[\s>]/.exec(text);
+ return match ? `<${match[1]}>` : undefined;
+}
+
+const KIND_NOUN: Record<SegmentKind, string> = {
+ assistant: 'assistant message',
+ injected: 'injected block',
+ reasoning: 'reasoning',
+ system: 'system prompt',
+ tool_call: 'tool call',
+ tool_result: 'tool result',
+ user: 'user message',
+};
+
+/** Break reasons across an operation, ranked by unchanged tokens then by frequency. */
+export function collectBreakReasons(
+ map: ContextMap,
+): Array<{ count: number; reason: string; wasted: number }> {
+ const byReason = new Map<string, { count: number; wasted: number }>();
+ for (const call of map.calls) {
+ if (!call.breakReason) continue;
+ const entry = byReason.get(call.breakReason) ?? { count: 0, wasted: 0 };
+ byReason.set(call.breakReason, {
+ count: entry.count + 1,
+ wasted: entry.wasted + call.wastedTokens,
+ });
+ }
+ return [...byReason]
+ .map(([reason, entry]) => ({ reason, ...entry }))
+ .sort((a, b) => b.wasted - a.wasted || b.count - a.count);
+}
+
+/** Human phrase for a segment, e.g. `injected block <agent_documents_index>`. */
+export function describeSegment(segment: ContextSegment): string {
+ const noun = KIND_NOUN[segment.kind];
+ return segment.label && segment.label !== segment.kind ? `${noun} ${segment.label}` : noun;
+}
+
+/** Reasoning is a string on most providers and a `{ content }` object on some. */
+function reasoningText(m: PayloadMessage): string {
+ const raw = m.reasoning ?? m.reasoning_content;
+ if (typeof raw === 'string') return raw;
+ if (raw && typeof raw === 'object') {
+ const content = (raw as { content?: unknown }).content;
+ return typeof content === 'string' ? content : JSON.stringify(raw);
+ }
+ return '';
+}
+
+/** Full serialized form of a message β€” the unit a prefix cache matches on. */
+function messageSignature(m: PayloadMessage): string {
+ return [
+ m.role,
+ contentText(m),
+ reasoningText(m),
+ m.tool_calls ? JSON.stringify(m.tool_calls) : '',
+ m.tool_call_id ?? '',
+ ].join('\\0');
+}
+
+/**
+ * Content of the DB messages behind a step, normalized for matching. A payload message
+ * that has no counterpart here was synthesized by the Context Engine β€” an injection.
+ */
+function dbMessageKeys(snapshot: ExecutionSnapshot, stepIndex: number): Set<string> {
+ const keys = new Set<string>();
+ const step = snapshot.steps.find((s) => s.stepIndex === stepIndex);
+ const messages =
+ step?.messages ?? (step ? reconstructMessages(snapshot.steps, stepIndex).messages : []);
+ for (const m of messages ?? []) {
+ const text = contentText(m as PayloadMessage);
+ if (text) keys.add(preview(text));
+ }
+ return keys;
+}
+
+/** Anything that is not a known role is treated as an assistant turn. */
+function messageRole(m: PayloadMessage): MessageRole {
+ return m.role === 'system' || m.role === 'user' || m.role === 'tool' ? m.role : 'assistant';
+}
+
+function splitMessage(
+ m: PayloadMessage,
+ messageIndex: number,
+ isInjected: boolean,
+ countTokens: (text: string) => number,
+): ContextSegment[] {
+ const role = messageRole(m);
+ const segment = (kind: SegmentKind, label: string, text: string): ContextSegment | undefined => {
+ const tokens = countTokens(text);
+ return tokens > 0
+ ? { kind, label, messageIndex, preview: preview(text), role, tokens, unchanged: false }
+ : undefined;
+ };
+
+ const text = contentText(m);
+
+ if (m.role === 'system')
+ return [segment('system', 'system', text)].filter(Boolean) as ContextSegment[];
+
+ if (m.role === 'tool') {
+ const label = m.name ?? 'tool result';
+ return [segment('tool_result', label, text)].filter(Boolean) as ContextSegment[];
+ }
+
+ if (m.role === 'user') {
+ const kind: SegmentKind = isInjected ? 'injected' : 'user';
+ const label = (isInjected && blockTag(text)) || (isInjected ? 'injected' : 'user');
+ return [segment(kind, label, text)].filter(Boolean) as ContextSegment[];
+ }
+
+ // assistant β€” reasoning, content and tool calls are distinct kinds of context
+ const toolNames = (m.tool_calls ?? [])
+ .map((c) => c.function?.name)
+ .filter(Boolean)
+ .join(', ');
+ return [
+ segment('reasoning', 'reasoning', reasoningText(m)),
+ segment('assistant', 'assistant', text),
+ segment(
+ 'tool_call',
+ toolNames || 'tool call',
+ m.tool_calls ? JSON.stringify(m.tool_calls) : '',
+ ),
+ ].filter(Boolean) as ContextSegment[];
+}
+
+// ---------------------------------------------------------------------------
+// Build
+// ---------------------------------------------------------------------------
+
+export function buildContextMap(
+ snapshot: ExecutionSnapshot,
+ options: BuildContextMapOptions = {},
+): ContextMap {
+ const tokenCache = new Map<string, number>();
+ const countTokens = (text: string): number => {
+ if (!text || typeof text !== 'string') return 0;
+ const hit = tokenCache.get(text);
+ if (hit !== undefined) return hit;
+ const tokens = encode(text).length;
+ tokenCache.set(text, tokens);
+ return tokens;
+ };
+
+ const { payloadSource, payloads } = resolvePayloads(snapshot);
+ const calls: ContextCall[] = [];
+
+ let prevSignatures: string[] = [];
+ let prevTokens: number[] = [];
+ let prevStepIndex = -1;
+
+ for (const [callIndex, payload] of payloads.entries()) {
+ const dbKeys = dbMessageKeys(snapshot, payload.stepIndex);
+ const signatures = payload.messages.map((m) => messageSignature(m));
+ const messageTokens: number[] = [];
+ const segments: ContextSegment[] = [];
+
+ for (const [messageIndex, m] of payload.messages.entries()) {
+ // A user message the CE produced rather than the user β€” env blocks, doc indexes, memory.
+ const isInjected = m.role === 'user' && !dbKeys.has(preview(contentText(m)));
+ const parts = splitMessage(m, messageIndex, isInjected, countTokens);
+ messageTokens.push(parts.reduce((sum, p) => sum + p.tokens, 0));
+ segments.push(...parts);
+ }
+
+ let stablePrefixMessages = 0;
+ while (
+ stablePrefixMessages < Math.min(prevSignatures.length, signatures.length) &&
+ prevSignatures[stablePrefixMessages] === signatures[stablePrefixMessages]
+ ) {
+ stablePrefixMessages += 1;
+ }
+
+ for (const segment of segments) {
+ segment.unchanged = segment.messageIndex < stablePrefixMessages;
+ }
+
+ const totalTokens = messageTokens.reduce((sum, t) => sum + t, 0);
+ const cachedTokens = messageTokens
+ .slice(0, stablePrefixMessages)
+ .reduce((sum, t) => sum + t, 0);
+
+ // A break only exists when the previous payload's own messages stopped matching;
+ // a payload that merely grew at the end keeps a fully reusable prefix.
+ const broke = callIndex > 0 && stablePrefixMessages < prevSignatures.length;
+ let breakReason: string | undefined;
+ if (broke) {
+ // A compression reset rewrites the history on purpose β€” not a cache fault to fix.
+ // The reset lands in the *next* payload, so the window starts at the previous call.
+ const compressed = snapshot.steps.some(
+ (s) =>
+ s.isCompressionReset && s.stepIndex <= payload.stepIndex && s.stepIndex >= prevStepIndex,
+ );
+ const culprit = segments.find((s) => s.messageIndex === stablePrefixMessages);
+ const resized =
+ (prevTokens[stablePrefixMessages] ?? 0) !== (messageTokens[stablePrefixMessages] ?? 0);
+ breakReason = compressed
+ ? 'context compression reset'
+ : culprit
+ ? `${describeSegment(culprit)} ${resized ? 'resized' : 'mutated'}`
+ : 'payload truncated';
+ }
+
+ // Tokens that survived unchanged but sit behind the break β€” cacheable in principle.
+ let wastedTokens = 0;
+ if (broke) {
+ for (
+ let i = stablePrefixMessages;
+ i < Math.min(prevSignatures.length, signatures.length);
+ i++
+ ) {
+ if (prevSignatures[i] === signatures[i]) wastedTokens += messageTokens[i];
+ }
+ }
+
+ calls.push({
+ breakMessageIndex: broke ? stablePrefixMessages : undefined,
+ breakReason,
+ cachedTokens,
+ callIndex,
+ reprocessedTokens: totalTokens - cachedTokens,
+ segments,
+ stablePrefixMessages,
+ stepIndex: payload.stepIndex,
+ totalTokens,
+ wastedTokens,
+ });
+
+ prevSignatures = signatures;
+ prevTokens = messageTokens;
+ prevStepIndex = payload.stepIndex;
+ }
+
+ const kindTokens = Object.fromEntries(KINDS.map((k) => [k, 0])) as Record<SegmentKind, number>;
+ for (const segment of calls.at(-1)?.segments ?? []) kindTokens[segment.kind] += segment.tokens;
+
+ return {
+ calls,
+ contextWindowTokens: options.contextWindowTokens,
+ model: snapshot.model,
+ operationId: snapshot.operationId,
+ payloadSource,
+ provider: snapshot.provider,
+ summary: {
+ brokenPrefixCalls: calls.filter((c) => c.breakMessageIndex !== undefined).length,
+ kindTokens,
+ llmCalls: calls.length,
+ maxCallTokens: calls.reduce((max, c) => Math.max(max, c.totalTokens), 0),
+ totalReprocessedTokens: calls.reduce((sum, c) => sum + c.reprocessedTokens, 0),
+ totalWastedTokens: calls.reduce((sum, c) => sum + c.wastedTokens, 0),
+ },
+ };
+}
diff --git a/packages/agent-tracing/src/cli/ctx-map.ts b/packages/agent-tracing/src/cli/ctx-map.ts
new file mode 100644
index 00000000000..a05fee46abe
--- /dev/null
+++ b/packages/agent-tracing/src/cli/ctx-map.ts
@@ -0,0 +1,94 @@
+import { mkdir, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { Command } from 'commander';
+import { LOBE_DEFAULT_MODEL_LIST } from 'model-bank';
+
+import { buildContextMap } from '../analysis/contextMap';
+import { renderContextMap } from '../viewer/contextMap';
+import { renderContextMapHtml } from '../viewer/contextMapHtml';
+import { resolveSnapshot } from './resolve';
+
+const red = (s: string) => `\x1B[31m${s}\x1B[39m`;
+const dim = (s: string) => `\x1B[2m${s}\x1B[22m`;
+
+/** Context window of the model the operation ran on, preferring the matching provider. */
+function resolveContextWindow(model?: string, provider?: string): number | undefined {
+ if (!model) return undefined;
+ const matches = LOBE_DEFAULT_MODEL_LIST.filter((m) => m.id === model);
+ const exact = matches.find((m) => m.providerId === provider);
+ return (exact ?? matches[0])?.contextWindowTokens ?? undefined;
+}
+
+export function registerCtxMapCommand(program: Command) {
+ program
+ .command('ctx-map')
+ .alias('cm')
+ .alias('map')
+ .description('Map the context window composition of every LLM call in an operation')
+ .argument('[target]', 'operation id, trace id, snapshot json path, or `latest`')
+ .option('--html [path]', 'write a standalone HTML report instead of terminal output')
+ .option('-w, --width <n>', 'track width in terminal columns')
+ .option('--window <n>', 'override the model context window used as the track')
+ .option('--full-window', 'always scale the track to the full context window')
+ .option('-j, --json', 'JSON output (per-call segments + cache stats)')
+ .action(
+ async (
+ target: string | undefined,
+ opts: {
+ fullWindow?: boolean;
+ html?: boolean | string;
+ json?: boolean;
+ width?: string;
+ window?: string;
+ },
+ ) => {
+ const snapshot = await resolveSnapshot(target);
+ if (!snapshot) {
+ console.error(
+ red(
+ `Snapshot not found${target ? ` for ${target}` : ''} (fetch remote traces first via \`agent-tracing inspect\`)`,
+ ),
+ );
+ process.exit(1);
+ }
+
+ const override = opts.window ? Number.parseInt(opts.window, 10) : undefined;
+ const map = buildContextMap(snapshot, {
+ contextWindowTokens:
+ override && !Number.isNaN(override)
+ ? override
+ : resolveContextWindow(snapshot.model, snapshot.provider),
+ });
+
+ if (opts.json) {
+ console.log(JSON.stringify(map, null, 2));
+ return;
+ }
+
+ if (opts.html) {
+ const target =
+ typeof opts.html === 'string'
+ ? opts.html
+ : path.join('.agent-tracing', '_reports', `ctx-map_${snapshot.operationId}.html`);
+ await mkdir(path.dirname(path.resolve(target)), { recursive: true });
+ await writeFile(
+ target,
+ renderContextMapHtml(map, { fullWindow: opts.fullWindow }),
+ 'utf8',
+ );
+ console.log(`ctx-map report written to ${target}`);
+ console.log(dim(`open file://${path.resolve(target)}`));
+ return;
+ }
+
+ const width = opts.width ? Number.parseInt(opts.width, 10) : undefined;
+ console.log(
+ renderContextMap(map, {
+ fullWindow: opts.fullWindow,
+ width: width && !Number.isNaN(width) ? width : undefined,
+ }),
+ );
+ },
+ );
+}
diff --git a/packages/agent-tracing/src/cli/index.ts b/packages/agent-tracing/src/cli/index.ts
index a9d0f684ccf..96c9f01a04e 100755
--- a/packages/agent-tracing/src/cli/index.ts
+++ b/packages/agent-tracing/src/cli/index.ts
@@ -3,6 +3,7 @@
import { Command } from 'commander';
import { registerCtxLintCommand } from './ctx-lint';
+import { registerCtxMapCommand } from './ctx-map';
import { registerInspectCommand } from './inspect';
import { registerListCommand } from './list';
import { registerPartialCommand } from './partial';
@@ -17,5 +18,6 @@ registerListCommand(program);
registerPartialCommand(program);
registerToolQualityCommand(program);
registerCtxLintCommand(program);
+registerCtxMapCommand(program);
program.parse();
diff --git a/packages/agent-tracing/src/cli/resolve.ts b/packages/agent-tracing/src/cli/resolve.ts
new file mode 100644
index 00000000000..f3056740771
--- /dev/null
+++ b/packages/agent-tracing/src/cli/resolve.ts
@@ -0,0 +1,21 @@
+import { readFile } from 'node:fs/promises';
+
+import { FileSnapshotStore } from '../store/file-store';
+import { isOperationId, RemoteSnapshotStore } from '../store/remote-store';
+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).
+ */
+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;
+}
diff --git a/packages/agent-tracing/src/index.ts b/packages/agent-tracing/src/index.ts
index 0a8ed9d6d81..1f210bedb4d 100644
--- a/packages/agent-tracing/src/index.ts
+++ b/packages/agent-tracing/src/index.ts
@@ -5,6 +5,13 @@ export {
lintSnapshot,
resolvePayloads,
} from './analysis/contextLint';
+export {
+ buildContextMap,
+ type ContextCall,
+ type ContextMap,
+ type ContextSegment,
+ type SegmentKind,
+} from './analysis/contextMap';
export { appendStepToPartial, finalizeSnapshot } from './recorder';
export { FileSnapshotStore } from './store/file-store';
export { isOperationId, parseOperationId } from './store/remote-store';
@@ -25,3 +32,5 @@ export {
renderStepDetail,
renderSummaryTable,
} from './viewer';
+export { renderContextMap } from './viewer/contextMap';
+export { renderContextMapHtml } from './viewer/contextMapHtml';
diff --git a/packages/agent-tracing/src/viewer/contextMap.ts b/packages/agent-tracing/src/viewer/contextMap.ts
new file mode 100644
index 00000000000..92ac2853c6a
--- /dev/null
+++ b/packages/agent-tracing/src/viewer/contextMap.ts
@@ -0,0 +1,202 @@
+import {
+ collectBreakReasons,
+ type ContextCall,
+ type ContextMap,
+ type ContextSegment,
+ type SegmentKind,
+} from '../analysis/contextMap';
+import {
+ ansi,
+ FAMILY_LABEL,
+ FAMILY_ORDER,
+ KIND_LABEL,
+ KINDS_BY_FAMILY,
+ TERMINAL_KIND_COLOR,
+ TERMINAL_LANE_COLOR,
+} from './contextMapPalette';
+
+// ANSI helpers β€” weight from the terminal's own attributes, hue from the LobeHub scales.
+const dim = (s: string) => `\x1B[2m${s}\x1B[22m`;
+const bold = (s: string) => `\x1B[1m${s}\x1B[22m`;
+const red = (s: string) => ansi(TERMINAL_LANE_COLOR.miss, s);
+const green = (s: string) => ansi(TERMINAL_LANE_COLOR.hit, s);
+const cyan = (s: string) => `\x1B[36m${s}\x1B[39m`;
+
+/** Left gutter: `call NN Β· step NN` plus the token column, padded to a fixed width. */
+const LABEL_WIDTH = 20;
+const TOKEN_WIDTH = 8;
+const GUTTER = LABEL_WIDTH + TOKEN_WIDTH + 2;
+
+export function fmtTokens(n: number): string {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;
+ return String(Math.round(n));
+}
+
+/**
+ * The token count one full track represents. Scaling to the context window is what makes
+ * headroom visible, but on a 1M-token window a 50k payload collapses into a few cells and
+ * the composition becomes unreadable β€” so fall back to the largest call when the window
+ * dwarfs the payloads, and say so in the header.
+ */
+export function resolveScaleBasis(
+ map: ContextMap,
+ fullWindow = false,
+): { basis: number; scaledToWindow: boolean } {
+ const window = map.contextWindowTokens;
+ const largest = Math.max(1, map.summary.maxCallTokens);
+ if (!window) return { basis: largest, scaledToWindow: false };
+ if (fullWindow || largest / window >= 0.35) return { basis: window, scaledToWindow: true };
+ return { basis: largest, scaledToWindow: false };
+}
+
+/**
+ * Distribute the track's cells across a call's segments by largest remainder, so widths stay
+ * proportional β€” a rounding floor would make a 200-token segment look like a 20k one.
+ * Segments too small to earn a cell are dropped rather than inflated.
+ */
+function allocateCells(
+ call: ContextCall,
+ scale: number,
+ width: number,
+): { cells: number[]; drawn: ContextSegment[] } {
+ const drawn = call.segments.filter((s) => s.tokens > 0);
+ const exact = drawn.map((s) => s.tokens * scale);
+ const cells = exact.map((v) => Math.floor(v));
+ const target = Math.min(width, Math.round(call.totalTokens * scale));
+
+ let short = target - cells.reduce((sum, c) => sum + c, 0);
+ const byRemainder = exact
+ .map((v, i) => ({ i, remainder: v - Math.floor(v) }))
+ .sort((a, b) => b.remainder - a.remainder);
+ for (const { i } of byRemainder) {
+ if (short <= 0) break;
+ cells[i] += 1;
+ short -= 1;
+ }
+ return { cells, drawn };
+}
+
+/**
+ * Cached segments are drawn shaded and re-processed ones solid, so the fill reinforces the
+ * cache ruler printed underneath the track.
+ */
+function renderTrack(call: ContextCall, scale: number, width: number): string {
+ const { cells, drawn } = allocateCells(call, scale, width);
+ let out = '';
+ let used = 0;
+ for (const [i, segment] of drawn.entries()) {
+ if (cells[i] <= 0 || used + cells[i] > width) continue;
+ used += cells[i];
+ const char = segment.unchanged ? 'β–“' : 'β–ˆ';
+ out += ansi(TERMINAL_KIND_COLOR[segment.kind], char.repeat(cells[i]));
+ }
+ return out + dim('Β·'.repeat(Math.max(0, width - used)));
+}
+
+/**
+ * The line under a track: a bracket spanning exactly the prefix the provider can serve
+ * from cache, then the break marker at the column where reuse stops. Reading down the
+ * column of brackets shows at a glance which calls kept their cache and which lost it.
+ */
+function renderCacheRuler(call: ContextCall, scale: number, width: number): string {
+ const cachedCells = Math.min(width, Math.round(call.cachedTokens * scale));
+ const newTokens = call.totalTokens - call.cachedTokens;
+
+ // The bracket is pure geometry β€” it spans the cached prefix. The figure always lives in
+ // the trailing text so a narrow hit (the interesting case) still reports its size.
+ const bracket = cachedCells >= 2 ? green(`β•°${'─'.repeat(cachedCells - 2)}β•―`) : '';
+
+ if (call.callIndex === 0) {
+ return dim(`${' '.repeat(cachedCells)}β–² cold start Β· ${fmtTokens(call.totalTokens)} uncached`);
+ }
+ if (call.breakMessageIndex === undefined) {
+ return (
+ bracket +
+ green(` cache hit ${fmtTokens(call.cachedTokens)}`) +
+ dim(newTokens > 0 ? ` Β· +${fmtTokens(newTokens)} new` : ' Β· no new tokens')
+ );
+ }
+ return (
+ bracket +
+ red(`β–² BREAK at msg[${call.breakMessageIndex}] Β· ${call.breakReason}`) +
+ dim(
+ ` Β· ${call.cachedTokens > 0 ? `cache hit only ${fmtTokens(call.cachedTokens)}` : 'no cache hit'} Β· ${fmtTokens(call.reprocessedTokens)} re-processed` +
+ (call.wastedTokens > 0 ? ` (${fmtTokens(call.wastedTokens)} unchanged)` : ''),
+ )
+ );
+}
+
+export function renderContextMap(
+ map: ContextMap,
+ options: { fullWindow?: boolean; width?: number } = {},
+): string {
+ const lines: string[] = [];
+ const { summary } = map;
+
+ if (map.calls.length === 0) {
+ return red('No LLM payloads found in this snapshot (no contextEngine.output recorded).');
+ }
+
+ const track =
+ options.width ?? Math.min(Math.max((process.stdout.columns ?? 100) - GUTTER - 4, 40), 100);
+ const { basis, scaledToWindow } = resolveScaleBasis(map, options.fullWindow);
+ const scale = track / basis;
+
+ const modelLabel = [map.model, map.provider].filter(Boolean).join('/') || 'unknown model';
+ const windowNote = map.contextWindowTokens
+ ? scaledToWindow
+ ? `window ${fmtTokens(map.contextWindowTokens)}`
+ : `window ${fmtTokens(map.contextWindowTokens)} (only ${Math.round((summary.maxCallTokens / map.contextWindowTokens) * 100)}% used β€” track scaled to the largest call)`
+ : 'window unknown β€” track scaled to the largest call';
+ lines.push(
+ `${bold('ctx-map')} ${cyan(map.operationId)} ${modelLabel} ` +
+ dim(`${summary.llmCalls} LLM calls Β· ${windowNote} Β· source=${map.payloadSource}`),
+ );
+ lines.push('');
+
+ for (const call of map.calls) {
+ const head =
+ `call ${String(call.callIndex + 1).padStart(2)} Β· step ${String(call.stepIndex).padStart(2)}`.padEnd(
+ LABEL_WIDTH,
+ ) + fmtTokens(call.totalTokens).padStart(TOKEN_WIDTH);
+ lines.push(`${bold(head)} ${renderTrack(call, scale, track)}`);
+ lines.push(`${' '.repeat(GUTTER)}${renderCacheRuler(call, scale, track)}`);
+ }
+
+ lines.push('');
+ lines.push(
+ bold('final window'.padEnd(GUTTER)) + dim(`${fmtTokens(summary.maxCallTokens)} total`),
+ );
+ for (const family of FAMILY_ORDER) {
+ const entries = KINDS_BY_FAMILY[family]
+ .filter((kind) => summary.kindTokens[kind] > 0)
+ .map(
+ (kind) =>
+ `${ansi(TERMINAL_KIND_COLOR[kind], 'β–ˆβ–ˆβ–ˆβ–ˆ')} ${KIND_LABEL[kind]} ${fmtTokens(summary.kindTokens[kind])}`,
+ );
+ if (entries.length > 0) {
+ lines.push(` ${dim(FAMILY_LABEL[family].padEnd(14))}${entries.join(' ')}`);
+ }
+ }
+ lines.push(dim(` ${'fill'.padEnd(14)}β–“ served from cache β–ˆ re-processed by the model`));
+
+ if (summary.brokenPrefixCalls > 0) {
+ lines.push('');
+ lines.push(
+ `${red('β–²')} ${bold(`${summary.brokenPrefixCalls}/${summary.llmCalls}`)} calls broke their prefix cache` +
+ (summary.totalWastedTokens > 0
+ ? `, re-processing ${bold(fmtTokens(summary.totalWastedTokens))} tokens of ${bold('unchanged')} context `
+ : ' ') +
+ dim(`(${fmtTokens(summary.totalReprocessedTokens)} re-processed in total)`),
+ );
+ for (const { count, reason, wasted } of collectBreakReasons(map).slice(0, 5)) {
+ const waste = wasted > 0 ? dim(`, βˆ’${fmtTokens(wasted)} tok unchanged`) : '';
+ lines.push(` ${dim('─')} ${reason} ${dim(`Γ—${count}`)}${waste}`);
+ }
+ }
+
+ return lines.join('\n');
+}
+
+export type { SegmentKind };
diff --git a/packages/agent-tracing/src/viewer/contextMapHtml.test.ts b/packages/agent-tracing/src/viewer/contextMapHtml.test.ts
new file mode 100644
index 00000000000..444698db685
--- /dev/null
+++ b/packages/agent-tracing/src/viewer/contextMapHtml.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ContextMap } from '../analysis/contextMap';
+import { renderContextMapHtml } from './contextMapHtml';
+import { HTML_THEME } from './contextMapPalette';
+
+const map: ContextMap = {
+ calls: [
+ {
+ breakMessageIndex: 1,
+ breakReason: 'injected block resized',
+ cachedTokens: 60,
+ callIndex: 1,
+ reprocessedTokens: 40,
+ segments: [
+ {
+ kind: 'system',
+ label: 'System',
+ messageIndex: 0,
+ preview: 'system prompt',
+ role: 'system',
+ tokens: 60,
+ unchanged: true,
+ },
+ {
+ kind: 'injected',
+ label: 'Injected block',
+ messageIndex: 1,
+ preview: 'framework context',
+ role: 'user',
+ tokens: 40,
+ unchanged: false,
+ },
+ ],
+ stablePrefixMessages: 1,
+ stepIndex: 2,
+ totalTokens: 100,
+ wastedTokens: 0,
+ },
+ ],
+ contextWindowTokens: 100,
+ operationId: 'op_test',
+ payloadSource: 'ce',
+ summary: {
+ brokenPrefixCalls: 1,
+ kindTokens: {
+ assistant: 0,
+ injected: 40,
+ reasoning: 0,
+ system: 60,
+ tool_call: 0,
+ tool_result: 0,
+ user: 0,
+ },
+ llmCalls: 1,
+ maxCallTokens: 100,
+ totalReprocessedTokens: 40,
+ totalWastedTokens: 0,
+ },
+};
+
+describe('renderContextMapHtml', () => {
+ it('preserves the original framed-message layout with neutral borders', () => {
+ const html = renderContextMapHtml(map);
+
+ expect(html).toContain('.track { background: var(--track-bg);');
+ expect(html).toContain('.track-inner { inset: 4px; position: absolute; }');
+ expect(html).toContain('.msg { background: transparent; border-radius: 7px; bottom: 0;');
+ expect(html).toContain(
+ '.msg::before { border-radius: inherit; box-shadow: inset 0 0 0 2px var(--border);',
+ );
+ expect(html).toContain('.msg.cached-message::before { opacity: 0.3; }');
+ expect(html).toContain(
+ 'class="msg cached-message" data-message-index="0" style="left:0.000%;width:calc(60.000% - 3px)"',
+ );
+ expect(html).toContain(
+ 'class="msg" data-message-index="1" style="left:60.000%;width:calc(40.000%)"',
+ );
+ expect(html).not.toContain('class="msg system"');
+ expect(html).not.toContain('class="msg user"');
+ expect(html).toContain('class="seg cached"');
+ expect(html).toContain('class="cut" style="left:60.000%"');
+ expect(html).toContain(
+ '.cut { background: var(--lane-miss); bottom: -11px; position: absolute; top: -11px; transform: translateX(-50%); width: 2px;',
+ );
+ expect(html).toContain(
+ '.cut::before { background: var(--lane-miss); clip-path: polygon(0 0, 100% 0, 50% 100%);',
+ );
+ expect(html).toContain('class="band hit" style="left:calc(0.000%);width:calc(60.000%)"');
+ expect(html).toContain(
+ 'class="band miss" style="left:calc(60.000% + 3px);width:calc(40.000% - 3px)"',
+ );
+ });
+
+ it('renders cache hits at 30% opacity and reserves hatching for re-processed context', () => {
+ const html = renderContextMapHtml(map);
+
+ expect(html).toContain('.seg.cached { opacity: 0.3; }');
+ expect(html).not.toContain('.seg.cached::before');
+ expect(html).toContain(
+ '.seg.reprocessed::before { background-image: repeating-linear-gradient',
+ );
+ expect(html).toContain('class="seg reprocessed"');
+ expect(html).toContain('served from cache</div>');
+ expect(html).toContain('re-processed by the model</div>');
+ });
+
+ it('colors an injected user message as user content and marks it with an injection badge', () => {
+ const html = renderContextMapHtml(map);
+
+ expect(html).toContain('background:var(--kind-user);flex:40 1 0');
+ expect(html).toContain('<span class="inject-mark" title="Framework injected">I</span>');
+ expect(html).toContain('.inject-mark { align-items: center; background: var(--kind-system);');
+ expect(html).toContain('class="swatch injected" style="background:var(--kind-user)"');
+ expect(html).toContain(
+ '.swatch.injected::after { align-items: center; background: var(--kind-system);',
+ );
+ });
+
+ it('orders assistant content, tool calls, and reasoning from darkest to lightest', () => {
+ expect(HTML_THEME.light.kind.assistant).toBe('#0d78ce');
+ expect(HTML_THEME.light.kind.tool_call).toBe('#76baff');
+ expect(HTML_THEME.light.kind.reasoning).toBe('#acd4ff');
+ expect(HTML_THEME.dark.kind.assistant).toBe('#0d78ce');
+ expect(HTML_THEME.dark.kind.tool_call).toBe('#439aed');
+ expect(HTML_THEME.dark.kind.reasoning).toBe('#a7d3ff');
+ });
+
+ it('uses a neutral gray for tool results', () => {
+ expect(HTML_THEME.light.kind.tool_result).toBe('#a4a6a8');
+ expect(HTML_THEME.dark.kind.tool_result).toBe('#595b5e');
+ });
+
+ it('aligns the cache lane to the track inset and uses a bright system orange', () => {
+ const html = renderContextMapHtml(map);
+
+ expect(html).toContain('.lane { height: 9px; margin: 5px 5px 0; position: relative; }');
+ expect(HTML_THEME.light.kind.system).toBe('#f88c13');
+ expect(HTML_THEME.dark.kind.system).toBe('#ff9927');
+ });
+
+ it('positions cache-break copy at the same token boundary as the cut marker', () => {
+ const html = renderContextMapHtml(map);
+
+ expect(html).toContain(
+ '.lanetext { font-size: 11.5px; margin: 5px 5px 0; min-height: 14px; position: relative; }',
+ );
+ expect(html).toContain('.lanetext .at-boundary { position: absolute;');
+ expect(html).toContain('<span class="at-boundary" style="left:60.000%">');
+ });
+
+ it('organizes the legend by conversation role before assistant details', () => {
+ const html = renderContextMapHtml(map);
+
+ expect(html).toContain('<div class="fname">Conversation</div>');
+ expect(html).toContain('System <span class="num">60</span>');
+ expect(html).toContain('User <span class="num">40</span>');
+ expect(html).toContain('Assistant <span class="num">0</span>');
+ expect(html).toContain('Tool <span class="num">0</span>');
+ expect(html).toContain('<div class="fname">Assistant</div>');
+ expect(html).toContain('Reasoning <span class="num">0</span>');
+ expect(html).toContain('Content <span class="num">0</span>');
+ expect(html).toContain('Tool use <span class="num">0</span>');
+ expect(html).toContain('<div class="fname">Marker</div>');
+ expect(html).toContain('Injected block <span class="num">40</span>');
+ });
+});
diff --git a/packages/agent-tracing/src/viewer/contextMapHtml.ts b/packages/agent-tracing/src/viewer/contextMapHtml.ts
new file mode 100644
index 00000000000..760b05845cc
--- /dev/null
+++ b/packages/agent-tracing/src/viewer/contextMapHtml.ts
@@ -0,0 +1,347 @@
+import {
+ collectBreakReasons,
+ type ContextCall,
+ type ContextMap,
+ type ContextSegment,
+} from '../analysis/contextMap';
+import { fmtTokens, resolveScaleBasis } from './contextMap';
+import { HTML_THEME, KIND_LABEL, type LaneTone, type ThemeColors } from './contextMapPalette';
+
+/**
+ * Standalone HTML rendering of a {@link ContextMap} β€” one row per LLM call, segment
+ * width proportional to tokens, against the model's context window as the track.
+ * Self-contained (no assets, no scripts) so it can be dropped into a PR or an issue.
+ *
+ * Three things carry the story, in this order of visual weight: the cache band under each
+ * track (how much of this call the provider could reuse), the break marker (where reuse
+ * stopped and why), and the segment colors (what the window is made of).
+ *
+ * Colors come from the LobeHub scales via CSS custom properties, so the light and dark
+ * variants are the same document β€” the report follows the reader's system theme.
+ */
+
+const escapeHtml = (s: string) =>
+ s
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;');
+
+/** Flatten a theme into the custom properties the stylesheet and inline widths reference. */
+function themeVars(theme: ThemeColors): string {
+ const entries: string[] = [
+ `--surface: ${theme.surface}`,
+ `--surface-raised: ${theme.surfaceRaised}`,
+ `--track-bg: ${theme.trackBg}`,
+ `--border: ${theme.border}`,
+ `--divider: ${theme.divider}`,
+ `--hatch: ${theme.hatch}`,
+ `--text: ${theme.text}`,
+ `--text-dim: ${theme.textDim}`,
+ `--tip-bg: ${theme.tipBg}`,
+ `--tip-text: ${theme.tipText}`,
+ ];
+ for (const [kind, color] of Object.entries(theme.kind)) entries.push(`--kind-${kind}: ${color}`);
+ for (const [tone, color] of Object.entries(theme.lane)) entries.push(`--lane-${tone}: ${color}`);
+ for (const [tone, color] of Object.entries(theme.laneText)) {
+ entries.push(`--lane-text-${tone}: ${color}`);
+ }
+ return entries.join(';\n ') + ';';
+}
+
+const STYLE = `
+ :root {
+ ${themeVars(HTML_THEME.light)}
+ color-scheme: light dark;
+ }
+ @media (prefers-color-scheme: dark) {
+ :root {
+ ${themeVars(HTML_THEME.dark)}
+ }
+ }
+
+ * { box-sizing: border-box; }
+ body { background: var(--surface); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif; margin: 0; padding: 40px 48px; }
+ h1 { font-size: 24px; margin: 0 0 6px; }
+ .sub { color: var(--text-dim); font-size: 13px; line-height: 1.7; margin-bottom: 34px; }
+ .sub code { background: var(--surface-raised); border-radius: 4px; padding: 1px 5px; }
+
+ .row { align-items: flex-start; display: flex; gap: 16px; margin-bottom: 22px; }
+ .label { flex: 0 0 178px; padding-top: 14px; text-align: right; }
+ .label .name { font-size: 14px; font-weight: 600; }
+ .label .tokens { color: var(--text-dim); font-size: 12px; font-variant-numeric: tabular-nums; margin-top: 2px; }
+ .lanes { flex: 1; min-width: 0; }
+
+ .track { background: var(--track-bg); border: 1.5px solid var(--border); border-radius: 8px; height: 58px; position: relative; }
+ .track-inner { inset: 4px; position: absolute; }
+ /* Every message uses the same neutral frame. Absolute token coordinates keep the same
+ boundary aligned across calls; the visual gap is deducted from the preceding message
+ instead of accumulating and stretching rows that contain more messages. */
+ .msg { background: transparent; border-radius: 7px; bottom: 0; display: flex; gap: 1px; padding: 3px; position: absolute; top: 0; }
+ .msg::before { border-radius: inherit; box-shadow: inset 0 0 0 2px var(--border); content: ''; inset: 0; pointer-events: none; position: absolute; z-index: 1; }
+ .msg.cached-message::before { opacity: 0.3; }
+ .seg { border-radius: 3px; min-width: 1px; position: relative; }
+ /* Cache hits recede through opacity alone. Hatching is reserved for context the model had
+ to re-process after a prefix break, so the two cache states never compete visually. */
+ .seg.cached { opacity: 0.3; }
+ .seg.reprocessed::before { background-image: repeating-linear-gradient(45deg, var(--hatch) 0 3px, transparent 3px 7px); content: ''; inset: 0; position: absolute; }
+ .inject-mark { align-items: center; background: var(--kind-system); border: 1px solid var(--kind-system); border-radius: 999px; color: var(--surface); display: flex; font-size: 7px; font-weight: 700; height: 13px; justify-content: center; letter-spacing: -0.02em; position: absolute; right: -5px; top: -7px; width: 13px; z-index: 12; }
+ .seg .tip { background: var(--tip-bg); border-radius: 6px; bottom: calc(100% + 10px); color: var(--tip-text); display: none; font-size: 12px; left: 0; line-height: 1.5; max-width: 460px; padding: 8px 10px; position: absolute; width: max-content; z-index: 20; }
+ .seg:hover .tip { display: block; }
+ .seg .tip b { color: var(--kind-injected); }
+
+ /* Break marker: a full-bleed rule through the track with the reason anchored to it. */
+ .cut { background: var(--lane-miss); bottom: -11px; position: absolute; top: -11px; transform: translateX(-50%); width: 2px; z-index: 10; }
+ .cut::before { background: var(--lane-miss); clip-path: polygon(0 0, 100% 0, 50% 100%); content: ''; height: 7px; left: 50%; position: absolute; top: 0; transform: translateX(-50%); width: 12px; }
+
+ /* Cache lane: bands carry the geometry only β€” the figures live on the line below, where
+ no amount of proportional narrowing can clip them. */
+ /* Match track-inner exactly: the track contributes a 1px border plus its 4px inset. */
+ .lane { height: 9px; margin: 5px 5px 0; position: relative; }
+ .band { border-radius: 3px; bottom: 0; position: absolute; top: 0; }
+ .band.hit { background: var(--lane-hit); }
+ .band.miss { background: var(--lane-miss); }
+ .band.cold { background: var(--lane-cold); }
+ .band.new { background: var(--lane-new); }
+ .lanetext { font-size: 11.5px; margin: 5px 5px 0; min-height: 14px; position: relative; }
+ .lanetext .at-boundary { position: absolute; top: 0; white-space: nowrap; }
+ .lanetext .hit { color: var(--lane-text-hit); }
+ .lanetext .miss { color: var(--lane-text-miss); font-weight: 600; }
+ .lanetext .cold { color: var(--lane-text-cold); }
+ .lanetext .new { color: var(--lane-text-new); }
+ .lanetext .sep { color: var(--divider); padding: 0 6px; }
+
+ .legend { border-top: 1px solid var(--divider); margin-top: 34px; padding-top: 20px; }
+ .legend h2 { font-size: 13px; letter-spacing: 0.04em; margin: 0 0 14px; text-transform: uppercase; }
+ .family { align-items: baseline; display: flex; gap: 14px; margin-bottom: 9px; }
+ .family .fname { color: var(--text-dim); flex: 0 0 110px; font-size: 12px; text-align: right; }
+ .family .items { display: flex; flex-wrap: wrap; gap: 18px; }
+ .family .items div { align-items: center; display: flex; font-size: 13px; gap: 7px; }
+ .family .items span.num { color: var(--text-dim); }
+ .swatch { border-radius: 4px; display: inline-block; height: 14px; width: 26px; }
+ .swatch.frame { background: transparent; border: 2px solid var(--border); }
+ .swatch.cached { opacity: 0.3; }
+ .swatch.hatch { background-image: repeating-linear-gradient(45deg, var(--hatch) 0 3px, transparent 3px 7px); }
+ .swatch.injected { position: relative; }
+ .swatch.injected::after { align-items: center; background: var(--kind-system); border: 1px solid var(--kind-system); border-radius: 999px; color: var(--surface); content: 'I'; display: flex; font-size: 6px; font-weight: 700; height: 10px; justify-content: center; position: absolute; right: -4px; top: -5px; width: 10px; }
+
+ .summary { background: var(--surface-raised); border: 1px solid var(--divider); border-radius: 8px; font-size: 13px; line-height: 1.8; margin-top: 28px; padding: 16px 20px; }
+ .summary b { color: var(--lane-text-miss); }
+ .summary ul { margin: 8px 0 0; padding-left: 20px; }
+`;
+
+interface MessageGroup {
+ messageIndex: number;
+ segments: ContextSegment[];
+ tokens: number;
+}
+
+/** Collapse a call's flat segment list back into the messages they came from. */
+function groupByMessage(call: ContextCall): MessageGroup[] {
+ const groups: MessageGroup[] = [];
+ for (const segment of call.segments) {
+ if (segment.tokens <= 0) continue;
+ const last = groups.at(-1);
+ if (last?.messageIndex === segment.messageIndex) {
+ last.segments.push(segment);
+ last.tokens += segment.tokens;
+ continue;
+ }
+ groups.push({
+ messageIndex: segment.messageIndex,
+ segments: [segment],
+ tokens: segment.tokens,
+ });
+ }
+ return groups;
+}
+
+export function renderContextMapHtml(
+ map: ContextMap,
+ options: { fullWindow?: boolean } = {},
+): string {
+ const { summary } = map;
+ const { basis, scaledToWindow } = resolveScaleBasis(map, options.fullWindow);
+ const modelLabel = [map.model, map.provider].filter(Boolean).join(' / ') || 'unknown model';
+ const pct = (tokens: number) => (tokens / Math.max(1, basis)) * 100;
+
+ const rows = map.calls
+ .map((call) => {
+ let offset = 0;
+ let cutLeft: number | undefined;
+ const messageGroups = groupByMessage(call);
+ const messages = messageGroups
+ .map((message, messagePosition) => {
+ const messageLeft = offset;
+ if (
+ cutLeft === undefined &&
+ call.breakMessageIndex !== undefined &&
+ message.messageIndex >= call.breakMessageIndex
+ ) {
+ cutLeft = offset;
+ }
+ offset += pct(message.tokens);
+
+ const isInjected = message.segments.some((segment) => segment.kind === 'injected');
+ const isCachedMessage = message.segments.every((segment) => segment.unchanged);
+ const segments = message.segments
+ .map((segment) => {
+ const cacheState = segment.unchanged
+ ? 'cached'
+ : call.breakMessageIndex === undefined
+ ? 'new'
+ : 'reprocessed';
+ const cacheLabel =
+ cacheState === 'cached'
+ ? 'served from cache'
+ : cacheState === 'reprocessed'
+ ? 're-processed'
+ : 'new context';
+ const colorKind = segment.kind === 'injected' ? segment.role : segment.kind;
+ const tip = `msg[${segment.messageIndex}] Β· ${KIND_LABEL[segment.kind]} Β· ${fmtTokens(segment.tokens)} tok Β· ${cacheLabel}<br><b>${escapeHtml(segment.label)}</b><br>${escapeHtml(segment.preview)}`;
+ return `<div class="seg ${cacheState}" style="background:var(--kind-${colorKind});flex:${segment.tokens} 1 0"><span class="tip">${tip}</span></div>`;
+ })
+ .join('');
+ const injectedMark = isInjected
+ ? '<span class="inject-mark" title="Framework injected">I</span>'
+ : '';
+ const messageWidth = `${pct(message.tokens).toFixed(3)}%${messagePosition < messageGroups.length - 1 ? ' - 3px' : ''}`;
+ return `<div class="msg${isCachedMessage ? ' cached-message' : ''}" data-message-index="${message.messageIndex}" style="left:${messageLeft.toFixed(3)}%;width:calc(${messageWidth})">${segments}${injectedMark}</div>`;
+ })
+ .join('');
+
+ const cut =
+ cutLeft === undefined ? '' : `<div class="cut" style="left:${cutLeft.toFixed(3)}%"></div>`;
+
+ // The lane restates the row as cache economics: what was reused, what was paid for.
+ const restTone: LaneTone =
+ call.callIndex === 0 ? 'cold' : call.breakMessageIndex === undefined ? 'new' : 'miss';
+ const band = (tone: LaneTone, tokens: number, left: number, hasLeadingGap = false) =>
+ tokens > 0
+ ? `<div class="band ${tone}" style="left:calc(${pct(left).toFixed(3)}%${hasLeadingGap ? ' + 3px' : ''});width:calc(${pct(tokens).toFixed(3)}%${hasLeadingGap ? ' - 3px' : ''})"></div>`
+ : '';
+ const lane =
+ band('hit', call.cachedTokens, 0) +
+ band(restTone, call.reprocessedTokens, call.cachedTokens, call.cachedTokens > 0);
+
+ const sep = '<span class="sep">Β·</span>';
+ const hitText =
+ call.cachedTokens > 0
+ ? `<span class="hit">βœ“ cache hit ${fmtTokens(call.cachedTokens)}</span>`
+ : '';
+ const restText =
+ call.callIndex === 0
+ ? `<span class="cold">cold start β€” ${fmtTokens(call.totalTokens)} uncached</span>`
+ : call.breakMessageIndex === undefined
+ ? `<span class="new">${call.reprocessedTokens > 0 ? `+${fmtTokens(call.reprocessedTokens)} new` : 'identical payload β€” nothing re-processed'}</span>`
+ : `<span class="miss">β–² cache broke at msg[${call.breakMessageIndex}] β€” ${escapeHtml(call.breakReason ?? '')}</span>${sep}<span class="miss">βœ‚ ${fmtTokens(call.reprocessedTokens)} re-processed${call.wastedTokens > 0 ? `, ${fmtTokens(call.wastedTokens)} of it unchanged` : ''}</span>`;
+ const laneText =
+ call.breakMessageIndex === undefined
+ ? [hitText, restText].filter(Boolean).join(sep)
+ : `${hitText}<span class="at-boundary" style="left:${pct(call.cachedTokens).toFixed(3)}%">${restText}</span>`;
+
+ const share = map.contextWindowTokens
+ ? ` Β· ${Math.round((call.totalTokens / map.contextWindowTokens) * 100)}% of window`
+ : '';
+
+ return `<div class="row">
+ <div class="label">
+ <div class="name">Call ${call.callIndex + 1}</div>
+ <div class="tokens">step ${call.stepIndex} Β· ${fmtTokens(call.totalTokens)} tok${share}</div>
+ </div>
+ <div class="lanes">
+ <div class="track"><div class="track-inner">${messages}${cut}</div></div>
+ <div class="lane">${lane}</div>
+ <div class="lanetext">${laneText}</div>
+ </div>
+ </div>`;
+ })
+ .join('\n');
+
+ const legendItem = (
+ label: string,
+ colorKind: keyof typeof summary.kindTokens,
+ tokens: number,
+ injected = false,
+ ) =>
+ `<div><span class="swatch${injected ? ' injected' : ''}" style="background:var(--kind-${colorKind})"></span>${label} <span class="num">${fmtTokens(tokens)}</span></div>`;
+ const legendRow = (label: string, items: string[]) =>
+ `<div class="family"><div class="fname">${label}</div><div class="items">${items.join('')}</div></div>`;
+
+ const roleTokens = {
+ assistant:
+ summary.kindTokens.assistant + summary.kindTokens.reasoning + summary.kindTokens.tool_call,
+ system: summary.kindTokens.system,
+ tool: summary.kindTokens.tool_result,
+ user: summary.kindTokens.user + summary.kindTokens.injected,
+ };
+ const legend = [
+ legendRow('Conversation', [
+ legendItem('System', 'system', roleTokens.system),
+ legendItem('User', 'user', roleTokens.user),
+ legendItem('Assistant', 'assistant', roleTokens.assistant),
+ legendItem('Tool', 'tool_result', roleTokens.tool),
+ ]),
+ legendRow('Assistant', [
+ legendItem('Reasoning', 'reasoning', summary.kindTokens.reasoning),
+ legendItem('Content', 'assistant', summary.kindTokens.assistant),
+ legendItem('Tool use', 'tool_call', summary.kindTokens.tool_call),
+ ]),
+ legendRow('Marker', [legendItem('Injected block', 'user', summary.kindTokens.injected, true)]),
+ ].join('');
+
+ const summaryBlock =
+ summary.brokenPrefixCalls === 0
+ ? ''
+ : `<div class="summary">
+ <b>${summary.brokenPrefixCalls} / ${summary.llmCalls}</b> calls broke their prefix cache${
+ summary.totalWastedTokens > 0
+ ? `, re-processing <b>${fmtTokens(summary.totalWastedTokens)}</b> tokens of context that had not changed`
+ : ''
+ }
+ (${fmtTokens(summary.totalReprocessedTokens)} re-processed in total).
+ <ul>${collectBreakReasons(map)
+ .slice(0, 5)
+ .map(
+ ({ count, reason, wasted }) =>
+ `<li>${escapeHtml(reason)} Γ—${count}${wasted > 0 ? ` β€” ${fmtTokens(wasted)} tok unchanged` : ''}</li>`,
+ )
+ .join('')}</ul>
+ </div>`;
+
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>ctx-map Β· ${escapeHtml(map.operationId)}</title>
+<style>${STYLE}</style>
+</head>
+<body>
+<h1>Context window composition per LLM call</h1>
+<div class="sub">
+ <code>${escapeHtml(map.operationId)}</code> Β· ${escapeHtml(modelLabel)} Β·
+ ${summary.llmCalls} calls Β· ${
+ map.contextWindowTokens
+ ? `window ${fmtTokens(map.contextWindowTokens)}${scaledToWindow ? '' : ` (only ${Math.round((summary.maxCallTokens / map.contextWindowTokens) * 100)}% used β€” track scaled to the largest call)`}`
+ : 'window unknown β€” track scaled to the largest call'
+ } Β·
+ source=${map.payloadSource}<br>
+ Each row is one context window snapshot Β· neutral frames mark message boundaries while block
+ color identifies system, user, assistant, and tool context Β· the band below splits what the prefix
+ cache served and what the model had to re-process
+</div>
+${rows}
+<div class="legend">
+ <h2>Final window Β· ${fmtTokens(summary.maxCallTokens)}</h2>
+ ${legend}
+ <div class="family"><div class="fname">Fill</div><div class="items">
+ <div><span class="swatch frame"></span>message boundary</div>
+ <div><span class="swatch cached" style="background:var(--kind-tool_call)"></span>served from cache</div>
+ <div><span class="swatch hatch" style="background-color:var(--kind-tool_call)"></span>re-processed by the model</div>
+ </div></div>
+</div>
+${summaryBlock}
+</body>
+</html>
+`;
+}
diff --git a/packages/agent-tracing/src/viewer/contextMapPalette.ts b/packages/agent-tracing/src/viewer/contextMapPalette.ts
new file mode 100644
index 00000000000..7f6bb3f4cc2
--- /dev/null
+++ b/packages/agent-tracing/src/viewer/contextMapPalette.ts
@@ -0,0 +1,160 @@
+import type { SegmentKind } from '../analysis/contextMap';
+import { blue, type ColorScale, green, orange, red, sand, slate } from './contextMapScales';
+
+/**
+ * Palette for the context map, built from the LobeHub scales (vendored in
+ * `contextMapScales.ts`) so the report reads as part of the product rather than a one-off
+ * chart theme. Every value below is a step index into a scale β€” nothing is hand-picked.
+ *
+ * Role is the primary encoding: orange system, green user, blue assistant, gray tool.
+ * Assistant internals use different steps of the same blue scale. Injected content inherits
+ * the color of the role carrying it; the HTML renderer marks injection separately.
+ */
+
+export type SegmentFamily = 'framework' | 'conversation' | 'execution';
+
+/** Cache economics of a span: reused, re-processed after a break, appended, or uncached. */
+export type LaneTone = 'hit' | 'miss' | 'new' | 'cold';
+
+export const FAMILY_LABEL: Record<SegmentFamily, string> = {
+ conversation: 'Conversation',
+ execution: 'Execution',
+ framework: 'Framework',
+};
+
+/** Families in the order they typically appear in a payload. */
+export const FAMILY_ORDER: SegmentFamily[] = ['framework', 'conversation', 'execution'];
+
+export const KIND_LABEL: Record<SegmentKind, string> = {
+ assistant: 'Assistant',
+ injected: 'Injected block',
+ reasoning: 'Reasoning',
+ system: 'System',
+ tool_call: 'Tool call',
+ tool_result: 'Tool result',
+ user: 'User turn',
+};
+
+/** Ordered by reading flow inside each family. */
+export const KINDS_BY_FAMILY: Record<SegmentFamily, SegmentKind[]> = {
+ conversation: ['user', 'assistant'],
+ execution: ['reasoning', 'tool_call', 'tool_result'],
+ framework: ['system', 'injected'],
+};
+
+/**
+ * Step indices per kind. Light themes descend the scale (dark = prominent), dark themes
+ * ascend it, so "most prominent member of the family" holds either way.
+ */
+const KIND_STEPS: Record<SegmentKind, { dark: number; light: number; scale: ColorScale }> = {
+ system: { dark: 9, light: 9, scale: orange },
+ injected: { dark: 6, light: 7, scale: orange },
+ user: { dark: 8, light: 9, scale: green },
+ reasoning: { dark: 10, light: 6, scale: blue },
+ tool_call: { dark: 8, light: 8, scale: blue },
+ assistant: { dark: 6, light: 10, scale: blue },
+ tool_result: { dark: 7, light: 7, scale: slate },
+};
+
+const LANE_STEPS: Record<LaneTone, { dark: number; light: number; scale: ColorScale }> = {
+ hit: { dark: 9, light: 9, scale: green },
+ miss: { dark: 9, light: 9, scale: red },
+ new: { dark: 7, light: 8, scale: blue },
+ cold: { dark: 6, light: 6, scale: slate },
+};
+
+/** Lane text needs to carry contrast against the page, so it sits a step further out. */
+const LANE_TEXT_STEPS: Record<LaneTone, { dark: number; light: number; scale: ColorScale }> = {
+ hit: { dark: 10, light: 10, scale: green },
+ miss: { dark: 10, light: 10, scale: red },
+ new: { dark: 10, light: 10, scale: blue },
+ cold: { dark: 10, light: 10, scale: slate },
+};
+
+const pick = (
+ steps: { dark: number; light: number; scale: ColorScale },
+ theme: 'light' | 'dark',
+) => (theme === 'light' ? steps.scale.light[steps.light] : steps.scale.dark[steps.dark]);
+
+const mapSteps = <K extends string>(
+ steps: Record<K, { dark: number; light: number; scale: ColorScale }>,
+ theme: 'light' | 'dark',
+) =>
+ Object.fromEntries(
+ Object.entries<{ dark: number; light: number; scale: ColorScale }>(steps).map(([key, step]) => [
+ key,
+ pick(step, theme),
+ ]),
+ ) as Record<K, string>;
+
+export interface ThemeColors {
+ border: string;
+ divider: string;
+ /** Stripe overlay marking re-processed segments β€” must darken on light, lighten on dark. */
+ hatch: string;
+ kind: Record<SegmentKind, string>;
+ lane: Record<LaneTone, string>;
+ laneText: Record<LaneTone, string>;
+ /** Page background. */
+ surface: string;
+ /** Raised surface: code chips, legend swatch backdrop. */
+ surfaceRaised: string;
+ text: string;
+ textDim: string;
+ tipBg: string;
+ tipText: string;
+ trackBg: string;
+}
+
+function buildTheme(theme: 'light' | 'dark'): ThemeColors {
+ const neutral = theme === 'light' ? sand.light : sand.dark;
+ const structure = theme === 'light' ? slate.light : slate.dark;
+ return {
+ border: theme === 'light' ? structure[11] : structure[7],
+ divider: neutral[3],
+ hatch: theme === 'light' ? 'rgba(0, 0, 0, 0.26)' : 'rgba(255, 255, 255, 0.3)',
+ kind: mapSteps(KIND_STEPS, theme),
+ lane: mapSteps(LANE_STEPS, theme),
+ laneText: mapSteps(LANE_TEXT_STEPS, theme),
+ surface: neutral[1],
+ surfaceRaised: neutral[2],
+ text: structure[12],
+ textDim: structure[10],
+ tipBg: theme === 'light' ? structure[12] : neutral[3],
+ tipText: theme === 'light' ? neutral[0] : structure[12],
+ trackBg: neutral[2],
+ };
+}
+
+export const HTML_THEME: Record<'light' | 'dark', ThemeColors> = {
+ dark: buildTheme('dark'),
+ light: buildTheme('light'),
+};
+
+/**
+ * A terminal may be light or dark and cannot tell us which, so it uses the mid steps of the
+ * light scales β€” saturated enough to read on a dark background, dark enough on a light one.
+ */
+export const TERMINAL_KIND_COLOR: Record<SegmentKind, string> = {
+ system: orange.light[9],
+ injected: orange.light[7],
+ user: green.light[9],
+ reasoning: blue.light[6],
+ tool_call: blue.light[8],
+ assistant: blue.light[10],
+ tool_result: slate.light[7],
+};
+
+export const TERMINAL_LANE_COLOR: Record<LaneTone, string> = {
+ cold: slate.light[8],
+ hit: green.light[9],
+ miss: red.light[9],
+ new: blue.light[9],
+};
+
+/** 24-bit foreground color β€” the ramps need more than the 8 ANSI slots. */
+export function ansi(hex: string, text: string): string {
+ if (process.env.NO_COLOR) return text;
+ const n = Number.parseInt(hex.slice(1), 16);
+ return `\x1B[38;2;${(n >> 16) & 255};${(n >> 8) & 255};${n & 255}m${text}\x1B[39m`;
+}
diff --git a/packages/agent-tracing/src/viewer/contextMapScales.ts b/packages/agent-tracing/src/viewer/contextMapScales.ts
new file mode 100644
index 00000000000..5ce39beb3b2
--- /dev/null
+++ b/packages/agent-tracing/src/viewer/contextMapScales.ts
@@ -0,0 +1,247 @@
+/**
+ * LobeHub color scales, vendored from the "@lobehub/ui/color" entry point at v5.28.0.
+ *
+ * Copied rather than imported: this package is a dev-only CLI and the UI library would be
+ * by far its heaviest dependency, in exchange for seven arrays of hex strings. Only the
+ * scales the context map uses are kept.
+ *
+ * Each scale is the standard 13-step LobeHub ramp β€” 0 is the page background, 9 the solid
+ * fill, 12 the highest-contrast text. Refresh by re-reading "@lobehub/ui/color" and
+ * re-emitting this file; the step indices in contextMapPalette.ts stay valid.
+ */
+
+export interface ColorScale {
+ dark: string[];
+ light: string[];
+}
+
+export const blue: ColorScale = {
+ dark: [
+ '#000415',
+ '#001740',
+ '#00285b',
+ '#003b79',
+ '#004f98',
+ '#0064b6',
+ '#0d78ce',
+ '#2d8ae0',
+ '#439aed',
+ '#60b1ff',
+ '#a7d3ff',
+ '#e0f0ff',
+ '#ffffff',
+ ],
+ light: [
+ '#ffffff',
+ '#fcfcff',
+ '#f2f8ff',
+ '#e5f1ff',
+ '#d5e9ff',
+ '#c2e0ff',
+ '#acd4ff',
+ '#93c8ff',
+ '#76baff',
+ '#57abf9',
+ '#0d78ce',
+ '#003b79',
+ '#000415',
+ ],
+};
+
+export const green: ColorScale = {
+ dark: [
+ '#000503',
+ '#001d12',
+ '#002d1d',
+ '#003f28',
+ '#005232',
+ '#00653c',
+ '#007944',
+ '#1b8d4d',
+ '#3ba05a',
+ '#62c473',
+ '#96cd92',
+ '#cde6c3',
+ '#ffffff',
+ ],
+ light: [
+ '#ffffff',
+ '#f4fdeb',
+ '#e7f8dd',
+ '#d8f2ce',
+ '#c7eabd',
+ '#b4e1ac',
+ '#a0d79b',
+ '#89cc8a',
+ '#71c179',
+ '#379d4a',
+ '#007944',
+ '#003f28',
+ '#000503',
+ ],
+};
+
+export const orange: ColorScale = {
+ dark: [
+ '#070300',
+ '#291900',
+ '#462b00',
+ '#684100',
+ '#8e5900',
+ '#b36f00',
+ '#d18000',
+ '#e88b00',
+ '#f89200',
+ '#ff9927',
+ '#ffd1b1',
+ '#fff1eb',
+ '#ffffff',
+ ],
+ light: [
+ '#ffffff',
+ '#fffcff',
+ '#fff8f6',
+ '#fff1eb',
+ '#ffe9dd',
+ '#ffdeca',
+ '#ffd1b1',
+ '#ffc293',
+ '#ffb06a',
+ '#f88c13',
+ '#d18000',
+ '#684100',
+ '#070300',
+ ],
+};
+
+export const purple: ColorScale = {
+ dark: [
+ '#0d000b',
+ '#2e002a',
+ '#42003e',
+ '#560053',
+ '#670e66',
+ '#781e78',
+ '#892b8a',
+ '#9a399e',
+ '#ab46b2',
+ '#bd54c6',
+ '#d590da',
+ '#edc7ee',
+ '#ffffff',
+ ],
+ light: [
+ '#ffffff',
+ '#fff6fb',
+ '#ffe7fd',
+ '#fdd6fe',
+ '#f6c4f8',
+ '#eeb1f1',
+ '#e49ce8',
+ '#d886de',
+ '#cb6ed2',
+ '#bd54c6',
+ '#892b8a',
+ '#560053',
+ '#0d000b',
+ ],
+};
+
+export const red: ColorScale = {
+ dark: [
+ '#0f0003',
+ '#380015',
+ '#560023',
+ '#780032',
+ '#9d0042',
+ '#c10251',
+ '#d6225d',
+ '#e43165',
+ '#ee3a6a',
+ '#f4416c',
+ '#ffb0b7',
+ '#ffe8e8',
+ '#ffffff',
+ ],
+ light: [
+ '#ffffff',
+ '#fffbff',
+ '#fff3f3',
+ '#ffe8e8',
+ '#ffdadb',
+ '#ffc7ca',
+ '#ffb0b7',
+ '#ff94a1',
+ '#ff6f87',
+ '#f4416c',
+ '#d6225d',
+ '#780032',
+ '#0f0003',
+ ],
+};
+
+export const sand: ColorScale = {
+ dark: [
+ '#000000',
+ '#1c1c18',
+ '#262521',
+ '#30302b',
+ '#3a3a35',
+ '#45453f',
+ '#505049',
+ '#5c5b54',
+ '#67675f',
+ '#73726a',
+ '#7f7e76',
+ '#bcbab2',
+ '#ffffff',
+ ],
+ light: [
+ '#ffffff',
+ '#fcf9f3',
+ '#edebe4',
+ '#dfddd5',
+ '#d1cfc7',
+ '#c3c1b9',
+ '#b5b3ab',
+ '#a7a69d',
+ '#999890',
+ '#8c8b83',
+ '#7f7e76',
+ '#4b4a44',
+ '#111',
+ ],
+};
+
+export const slate: ColorScale = {
+ dark: [
+ '#000000',
+ '#1b1c1d',
+ '#242527',
+ '#2e2f32',
+ '#383a3c',
+ '#434547',
+ '#4e5052',
+ '#595b5e',
+ '#64676a',
+ '#707276',
+ '#7b7e82',
+ '#b8babc',
+ '#ffffff',
+ ],
+ light: [
+ '#ffffff',
+ '#f9f9fa',
+ '#ebebec',
+ '#dcddde',
+ '#cecfd0',
+ '#bfc1c3',
+ '#b1b3b5',
+ '#a4a6a8',
+ '#96989b',
+ '#898b8e',
+ '#7b7e82',
+ '#484a4d',
+ '#111',
+ ],
+};