Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

47.6 KB
Raw Blame
/**
 * Claude-Code JSONL → web ServerEvent normalizer.
 *
 * Self-contained port of the hosted runtime’s replay normalizer
 * (`the hosted runtime`: transformCCMessageToSessionMessage,
 * sessionMessagesToEvents, stripContextSummary/stripSystemBlocks + tool-summary)
 * — this package has no dependency outside itself.
 *
 * Two entry points:
 *  - messagesToEvents(rawLines)      → full SessionEvent[] replay for `session_get`.
 *  - lineToEvents(rawLine, state)    → incremental events for live tailing, PLUS a derived
 *    turn lifecycle (turn_started / turn_ended) so a prompt typed directly in the terminal
 *    renders identically to one sent from the web (mirror-all).
 */

import { harnessWebTool } from '../../lib/harnessWebTools.js'

import type { SubagentSummary, SessionEvent, LiveEvent, LastTurnText } from '../kit/events.js'

interface RawContentBlock {
  type: 'text' | 'tool_use' | 'tool_result' | 'thinking' | 'image'
  text?: string
  thinking?: string
  id?: string
  name?: string
  input?: unknown
  tool_use_id?: string
  content?: string | Array<{ type: string; text?: string }>
  is_error?: boolean
  /** The last TAIL_OUTPUT chars of a string result that mapContentItem clipped. */
  tail?: string
  source?: { type: string; media_type: string; data: string }
}

interface NormalizedMessage {
  type: 'user' | 'assistant'
  message?: { role: 'user' | 'assistant'; content: RawContentBlock[] }
  toolUseResult?: SubagentSummary & { status?: string; durationSeconds?: number }
  /** Raw Anthropic stop_reason from the assistant line (drives turn_ended). */
  stopReason?: string | null
}

const MAX_OUTPUT = 2000
/** Test summaries print last, so the stats read the tail the head clip drops. */
const TAIL_OUTPUT = 600
const MAX_THINKING = 500
const MAX_DIFF_SIDE = 1500
const PREVIEW_LINES = 8

// ── Text cleanup (ported verbatim) ────────────────────────────────────────────────────────────────

/** Strip the compaction-injected context summary; null if the whole message was summary. */
export function stripContextSummary(text: string): string | null {
  const endMarker = '<!-- END CONTEXT SUMMARY -->'
  const idx = text.indexOf(endMarker)
  if (idx === -1) return text
  let remaining = text.slice(idx + endMarker.length)
  remaining = remaining.replace(/^\s*---\s*Now,?\s*continuing.*?:\s*/is, '')
  remaining = remaining.trim()
  return remaining || null
}

/** Strip system-injected blocks not meant for UI display. */
export function stripSystemBlocks(text: string): string {
  return text
    .replace(/<task-notification>[\s\S]*?<\/task-notification>\s*/g, '')
    .replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g, '')
    .replace(/<goal-context>[\s\S]*?<\/goal-context>\s*/g, '')
    .replace(/<dev-server-context>[\s\S]*?<\/dev-server-context>\s*/g, '')
    .replace(/<available-deferred-tools>[\s\S]*?<\/available-deferred-tools>\s*/g, '')
    .replace(/<local-command-caveat>[\s\S]*?<\/local-command-caveat>\s*/g, '')
    .replace(/<command-name>[\s\S]*?<\/command-name>\s*/g, '')
    .replace(/<command-message>[\s\S]*?<\/command-message>\s*/g, '')
    .replace(/<command-args>[\s\S]*?<\/command-args>\s*/g, '')
    .replace(/<local-command-stdout>[\s\S]*?<\/local-command-stdout>\s*/g, '')
    .replace(/Read the output file to retrieve the result:[^\n]*/g, '')
    .trim()
}

/**
 * Bash mode (`!command` in Claude Code) writes the command and its output back into the transcript as a
 * `type:'user'` line — `<bash-input>…</bash-input>` and the `<bash-stdout>`/`<bash-stderr>` that follow.
 * It is the person running a local shell, NOT a prompt to the agent, so it must not open a turn: if it
 * did, the per-turn recap would summarise shell mechanics ("paste the command on one line") instead of
 * what the agent is actually working on, and the tile would drift off-task with every `!`. Stripped ONLY
 * for the turn-detection decision (see `realUserText`), never for display — the transcript still shows
 * the commands. A line carrying real prose ALONGSIDE a bash block keeps counting; only a bash-only line
 * is skipped.
 */
export function stripBashModeBlocks(text: string): string {
  return text
    .replace(/<bash-input>[\s\S]*?<\/bash-input>\s*/g, '')
    .replace(/<bash-stdout>[\s\S]*?<\/bash-stdout>\s*/g, '')
    .replace(/<bash-stderr>[\s\S]*?<\/bash-stderr>\s*/g, '')
    .trim()
}

// Built-in CLI commands that only drive the local TUI and never dispatch an agent turn. Surfacing
// them as a user prompt would open a turn nothing ever closes (device tile stuck busy), so they stay
// invisible — same as before. Anything else (a custom `~/.claude/commands/*.md`, `/goal`, `/review`,
// a plugin skill) DOES run a turn and must be visible.
const LOCAL_ONLY_COMMANDS = new Set([
  'add-dir', 'agents', 'bug', 'clear', 'compact', 'config', 'context', 'copy', 'cost', 'desktop',
  'doctor', 'effort', 'exit', 'export', 'help', 'hooks', 'ide', 'login', 'logout', 'mcp', 'memory',
  'model', 'output-style', 'permissions', 'privacy-settings', 'quit', 'release-notes',
  'reload-plugins', 'resume', 'skills', 'statusline', 'status', 'terminal-setup', 'todos',
  'upgrade', 'vim',
])

/** A whole prompt that is one of LOCAL_ONLY_COMMANDS, typed plainly: `/compact`, `/model opus`. */
function isLocalOnlyCommandLine(text: string): boolean {
  const name = /^\/([A-Za-z][\w-]*)(?:\s|$)/.exec(text.trim())?.[1]
  return name !== undefined && LOCAL_ONLY_COMMANDS.has(name.toLowerCase())
}

/**
 * `<command-name>/goal</command-name>…<command-args>x</command-args>` → `/goal x`.
 *
 * Claude Code records a slash command ONLY as these tags (the expansion it actually sends to the
 * model is written as a separate `isMeta` line, which we suppress). `stripSystemBlocks` erases the
 * tags, so without this the whole line normalizes to "" → `realUserText` returns null → NO
 * `turn_started` is ever emitted for a command prompt. That broke the device's goal mode: the
 * injected `/goal <text>` ran fine in the terminal, but `SessionInputController` never saw the turn
 * open and reported "The agent did not accept the message" after its submit retries — and the recap
 * had no user message to lead with.
 */
function commandPromptText(text: string): string | null {
  const name = text.match(/<command-name>\s*([^<]*?)\s*<\/command-name>/)?.[1]
  if (!name) return null
  const bare = name.replace(/^\//, '').trim()
  if (!bare || LOCAL_ONLY_COMMANDS.has(bare.toLowerCase())) return null
  const args = text.match(/<command-args>([\s\S]*?)<\/command-args>/)?.[1]?.trim() ?? ''
  return args ? `/${bare} ${args}` : `/${bare}`
}

/** Short title heuristic for a thinking block (first 3-8 words of the first line). */
function extractThinkingTitle(thinking: string): string | null {
  const trimmed = thinking.trim()
  if (!trimmed || trimmed.length < 10) return null
  const firstLine = trimmed.split('\n')[0].replace(/^[\s#*\->]+/, '').trim()
  if (!firstLine) return null
  const words = firstLine.split(/\s+/).slice(0, 8)
  if (words.length < 2) return null
  let title = words.join(' ').replace(/[.,:;!?]+$/, '')
  if (title.length > 60) title = title.slice(0, 57) + '...'
  return title
}

/** The short ⎿ label shown after a tool finishes (e.g. "Read 247 lines"). */
function computeToolSummary(toolName: string, rawOutput: string, isError: boolean): string {
  if (isError) return rawOutput.split('\n')[0]?.slice(0, 80) || 'Error'
  switch (toolName) {
    case 'Bash': {
      const match = rawOutput.match(/^Exit code (\d+)/)
      return match ? `Exit ${match[1]}` : 'Done'
    }
    case 'Read': {
      const lineCount = (rawOutput.match(/^\s*\d+→/gm) || []).length
      return lineCount > 0 ? `Read ${lineCount} lines` : 'Read'
    }
    case 'Write':
    case 'WriteFile':
      return rawOutput.includes('successfully') ? 'Written' : rawOutput.slice(0, 60)
    case 'Edit':
    case 'EditFile':
      return rawOutput.includes('successfully') ? 'Updated' : rawOutput.slice(0, 60)
    case 'Glob': {
      const count = rawOutput.trim() ? rawOutput.trim().split('\n').length : 0
      return `${count} file${count !== 1 ? 's' : ''}`
    }
    case 'Grep': {
      const count = rawOutput.trim() ? rawOutput.trim().split('\n').length : 0
      return `${count} match${count !== 1 ? 'es' : ''}`
    }
    case 'WebFetch':
    case 'WebSearch':
      return 'Fetched'
    case 'TodoRead':
    case 'TodoWrite':
      return 'Done'
    default:
      return rawOutput.split('\n')[0]?.slice(0, 80) || 'Done'
  }
}

// ── Raw JSONL line → normalized message (port of transformCCMessageToSessionMessage) ─────────────

function smartWriteInput(input: Record<string, unknown>): Record<string, unknown> {
  const raw = input.content as string
  const lines = raw.split('\n')
  const preview = lines.slice(0, PREVIEW_LINES).join('\n')
  return {
    ...input,
    content: undefined,
    content_stats: {
      lines: lines.length,
      chars: raw.length,
      preview: preview + (lines.length > PREVIEW_LINES ? '\n…' : ''),
    },
  }
}

function smartEditInput(input: Record<string, unknown>): Record<string, unknown> {
  const truncSide = (s: unknown): unknown => {
    if (typeof s !== 'string') return s
    if (s.length <= MAX_DIFF_SIDE) return s
    const half = Math.floor(MAX_DIFF_SIDE / 2)
    return s.slice(0, half) + '\n…\n' + s.slice(s.length - half)
  }
  return { ...input, old_string: truncSide(input.old_string), new_string: truncSide(input.new_string) }
}

function mapContentItem(item: unknown): RawContentBlock {
  const c = (item ?? {}) as Record<string, unknown> // a null content block must not throw on `.type`
  const type = (c.type || 'text') as RawContentBlock['type']

  if (type === 'image') {
    return { type: 'image', source: c.source as RawContentBlock['source'] }
  }

  let resultContent = c.content as RawContentBlock['content']
  let tail: string | undefined
  if (type === 'tool_result' && typeof resultContent === 'string' && resultContent.length > MAX_OUTPUT) {
    tail = resultContent.slice(-TAIL_OUTPUT)
    resultContent = resultContent.slice(0, MAX_OUTPUT) + '\n…[truncated]'
  }

  let toolInput = c.input as Record<string, unknown> | undefined
  let toolName = c.name as string | undefined
  // On a Local model the web tools come from the `harness` MCP server; the transcript should not
  // look different for it, so they take the native cards here, at the one raw→normalized point.
  const webTool = type === 'tool_use' ? harnessWebTool(toolName, toolInput) : null
  if (webTool) {
    toolName = webTool.tool
    toolInput = webTool.input
  }
  if (type === 'tool_use' && toolInput) {
    if ((toolName === 'Write' || toolName === 'WriteFile') && typeof toolInput.content === 'string' && toolInput.content.length > 500) {
      toolInput = smartWriteInput(toolInput)
    } else if (
      (toolName === 'Edit' || toolName === 'EditFile') &&
      (((toolInput.old_string as string)?.length ?? 0) > MAX_DIFF_SIDE || ((toolInput.new_string as string)?.length ?? 0) > MAX_DIFF_SIDE)
    ) {
      toolInput = smartEditInput(toolInput)
    }
  }

  return {
    type,
    text: c.text as string | undefined,
    thinking: c.thinking as string | undefined,
    id: c.id as string | undefined,
    name: toolName,
    input: toolInput,
    tool_use_id: c.tool_use_id as string | undefined,
    content: resultContent,
    is_error: c.is_error as boolean | undefined,
    ...(tail ? { tail } : {}),
  }
}

/** Parse one raw JSONL entry into a normalized user/assistant message (null for other types). */
export function transformLine(rawMessage: Record<string, unknown>): NormalizedMessage | null {
  const type = rawMessage.type as string
  if (type !== 'user' && type !== 'assistant') return null

  const messageObj = rawMessage.message as Record<string, unknown> | undefined
  let messageContent: RawContentBlock[] | undefined

  if (messageObj) {
    const role = messageObj.role as string
    const content = messageObj.content
    if (role === 'user' || role === 'assistant') {
      if (typeof content === 'string') {
        messageContent = [{ type: 'text', text: content }]
      } else if (Array.isArray(content)) {
        messageContent = content.length > 0 ? content.map(mapContentItem) : [{ type: 'text', text: '' }]
      } else if (content === null || content === undefined) {
        messageContent = [{ type: 'text', text: '' }]
      }
    }
  } else if (type === 'user') {
    const directContent = rawMessage.content
    if (typeof directContent === 'string') {
      messageContent = [{ type: 'text', text: directContent }]
    } else if (Array.isArray(directContent)) {
      messageContent = directContent.map(mapContentItem)
    }
  }

  let toolUseResult: NormalizedMessage['toolUseResult']
  if (rawMessage.tool_use_result || rawMessage.toolUseResult) {
    const tr = (rawMessage.tool_use_result || rawMessage.toolUseResult) as Record<string, unknown>
    toolUseResult = {
      status: (tr.status || 'complete') as string,
      agentId: (tr.agentId ?? tr.agent_id) as string | undefined,
      agentType: (tr.agentType ?? tr.agent_type) as string | undefined,
      totalTokens: tr.totalTokens as number | undefined,
      totalDurationMs: tr.totalDurationMs as number | undefined,
      totalToolUseCount: tr.totalToolUseCount as number | undefined,
      // WebSearch carries its search time here (the CLI's "Did 1 search in Ns" line).
      durationSeconds: typeof tr.durationSeconds === 'number' ? tr.durationSeconds : undefined,
    }
  }

  const role = (messageObj?.role || (type === 'user' ? 'user' : 'assistant')) as 'user' | 'assistant'

  if (role === 'user' && messageContent) {
    for (const block of messageContent) {
      if (block.type !== 'text' || !block.text) continue
      // A typed slash command survives as `/name args`; everything else is stripped as before.
      block.text = commandPromptText(block.text) ?? stripSystemBlocks(block.text)
    }
  }

  if (messageContent === undefined) messageContent = [{ type: 'text', text: '' }]

  return {
    type: type as 'user' | 'assistant',
    message: { role, content: messageContent },
    toolUseResult,
    stopReason: (messageObj?.stop_reason as string | null | undefined) ?? null,
  }
}

// ── Shared per-message event emission ─────────────────────────────────────────────────────────────

// Auto-fix / platform prompts filtered from replay (sent by the platform, not the user).
const SYSTEM_PROMPT_PATTERNS = [
  'The dev server is running but the app has an error:',
  'Please fix this code issue. Check the page component, routing, and any compile errors.',
  '<!-- CONTEXT SUMMARY',
  'This session is being continued from a previous conversation',
  '<local-command-stdout>Compacted',
]

function isSystemPrompt(content: RawContentBlock[]): boolean {
  const text = content.filter((c) => c.type === 'text' && c.text).map((c) => c.text!).join('')
  return SYSTEM_PROMPT_PATTERNS.some((p) => text.includes(p))
}

/** A REAL user prompt (not a tool_result echo, not a platform prompt). Returns the cleaned text or null. */
/**
 * An ESC interrupt (terminal, or a Stop from the web/device) is written to the transcript as a plain user
 * line — `type:'user'`, `userType:'external'`, no `isMeta`, no flag of ANY kind — so its text is the only
 * thing distinguishing it from something the user typed. Treating it as a prompt opened a brand-new turn at
 * the instant a turn was cancelled, and the device then counted seconds forever on a turn no assistant
 * would ever answer. Covers the `for tool use` variant too. A user who literally types this loses one turn
 * card; that is the cheaper failure.
 */
const INTERRUPT_MARKER = /^\[Request interrupted by user[^\]]*\]$/

/** The user-authored text of a line, before interrupt markers are judged. null = not a user prompt. */
function userTextRaw(msg: NormalizedMessage): string | null {
  if (msg.type !== 'user' || !msg.message) return null
  const content = msg.message.content
  if (isSystemPrompt(content)) return null
  if (content.some((c) => c.type === 'tool_result')) return null
  const parts: string[] = []
  for (const block of content) {
    if (block.type !== 'text' || !block.text) continue
    let cleaned = stripContextSummary(block.text)
    if (cleaned) cleaned = stripSystemBlocks(cleaned)
    if (cleaned && !cleaned.match(/^\[Image: original \d+x\d+/)) parts.push(cleaned)
  }
  const text = parts.join('\n')
  return text || null
}

/**
 * An async sub-agent's REAL completion. Claude's `Agent` tool returns in milliseconds with
 * "Async agent launched successfully." — that `tool_result` is a launch ack, not a result, and taking it
 * for one made the device tick a sub-agent off the moment it started. The actual finish arrives much
 * later as a `type:"user"` record the CLI injects into the parent transcript:
 *
 *   <task-notification><task-id>…</task-id><tool-use-id>toolu_018wkW…</tool-use-id>
 *   <output-file>…</output-file><status>completed</status><summary>Agent "…" finished…
 *
 * `stripSystemBlocks` erases the whole block, so it correctly starts no turn — but that also meant the
 * only signal a sub-agent had finished was being thrown away. Read it here, keyed by tool-use-id.
 *
 * Takes the RAW record, not a NormalizedMessage: `transformLine` already ran the strip (line ~304), so by
 * then the text block is empty and there is nothing left to parse.
 */
function taskNotificationEvent(raw: Record<string, unknown>): LiveEvent | null {
  // One that finishes while its parent still works comes as a `queued_command` attachment, the more common
  // delivery (real 2.1.270–2.1.287). Read from user records alone, it never finished on the dial.
  const attachment = raw.type === 'attachment' ? raw.attachment as { type?: unknown; prompt?: unknown } | undefined : undefined
  if (raw.type !== 'user' && attachment?.type !== 'queued_command') return null
  const content = attachment ? attachment.prompt : (raw.message as { content?: unknown } | undefined)?.content ?? raw.content
  let text = ''
  if (typeof content === 'string') text = content
  else if (Array.isArray(content)) {
    text = content
      .map((b) => (typeof b === 'string' ? b : (b as RawContentBlock)?.type === 'text' ? String((b as RawContentBlock).text ?? '') : ''))
      .join('\n')
  }
  if (!text.includes('<task-notification>')) return null
  const id = text.match(/<tool-use-id>([^<]+)<\/tool-use-id>/)?.[1]?.trim()
  if (!id) return null
  const status = text.match(/<status>([^<]+)<\/status>/)?.[1]?.trim() || 'completed'
  const summary = text.match(/<summary>([\s\S]*?)(?:<\/summary>|$)/)?.[1]?.trim()
  return { type: 'subagent_finished', payload: { id, status, ...(summary ? { summary } : {}) } }
}

/** True for the synthetic line an interrupt leaves behind. It ends a turn; it never starts one. */
function isInterruptLine(msg: NormalizedMessage): boolean {
  const text = userTextRaw(msg)
  return text !== null && INTERRUPT_MARKER.test(text)
}

// Every caller of this asks "is this a prompt the user made?" — turn slicing for replay and the recap's
// user-message source as well as the live turn lifecycle — and an interrupt marker is not one of those.
function realUserText(msg: NormalizedMessage): string | null {
  const text = userTextRaw(msg)
  if (text === null || INTERRUPT_MARKER.test(text)) return null
  // Claude Code 2.1.290 also writes a built-in command it runs itself as a plain user line ("/compact"),
  // ahead of the tagged record `commandPromptText` already keeps out. Taken as a prompt, it opened a turn
  // nothing ever closed: after a /compact the agent read working, then unknown, until the next message
  // (found by daemon QA). The same list decides both forms.
  if (isLocalOnlyCommandLine(text)) return null
  // A `!command` line is not a prompt — skip it so the turn (and its recap) stays anchored to the last
  // real ask. Only when nothing but bash blocks remain: a message that also carries prose still counts.
  if (!stripBashModeBlocks(text)) return null
  return text
}

/**
 * Extract the last real user prompt and the assistant text that followed it from
 * raw Claude JSONL. This is the recap source of truth: it matches replay parsing
 * rules, skips tool_result echoes / platform prompts / compact metadata, and only
 * summarizes assistant text blocks.
 */
export function lastTurnTextFromRawLines(rawLines: string[]): LastTurnText | null {
  let userMessage = ''
  // What the assistant said AFTER its last tool call: the answer. Everything before it is narration of
  // the work ("Let me check the logs"), kept aside because a turn that never reached an answer (it ended
  // on a tool call, or was interrupted) still has something to summarize.
  let assistantParts: string[] = []
  let narration: string[] = []

  for (const line of rawLines) {
    if (!line.trim()) continue
    let raw: Record<string, unknown>
    try { raw = JSON.parse(line) as Record<string, unknown> } catch { continue }
    const compact = compactEventFromRaw(raw)
    if (compact !== undefined) continue

    const msg = transformLine(raw)
    if (!msg?.message) continue

    const userText = realUserText(msg)
    if (userText !== null) {
      userMessage = userText
      assistantParts = []
      narration = []
      continue
    }

    if (msg.type !== 'assistant') continue
    const text = msg.message.content
      .filter((c) => c.type === 'text' && c.text)
      .map((c) => c.text!)
      .join('')
      .trim()
    if (text) assistantParts.push(text)
    // A tool call closes the stretch of text before it: that was narration, and the answer is what comes
    // after the last one. Without this a long working turn is summarized by its FIRST line, so the
    // dial and the reader show "Let me look at the logs" instead of what was found.
    if (msg.message.content.some((c) => c.type === 'tool_use')) {
      narration = narration.concat(assistantParts)
      assistantParts = []
    }
  }

  const assistantText = (assistantParts.length ? assistantParts : narration).join('\n\n').trim()
  return assistantText ? { userMessage, assistantText } : null
}

/** Aggregates computed from a sub-agent's OWN transcript. Async/background agents never get totals
 *  in the launcher's toolUseResult (it only records `{isAsync, status:'async_launched', agentId}` at
 *  launch) — the real numbers live in `<session>/subagents/agent-<id>.jsonl`. totalTokens mirrors the
 *  CLI's definition: input + output + cache_read + cache_creation summed over assistant turns. Taken a
 *  line at a time, so a long transcript is never held whole. */
export class SubagentStats {
  private toolCount = 0
  private tokens = 0
  private first: number | undefined
  private last: number | undefined

  push(line: string): void {
    if (!line.trim()) return
    let raw: Record<string, unknown>
    try { raw = JSON.parse(line) as Record<string, unknown> } catch { return }
    if (!raw || typeof raw !== 'object') return
    const ts = typeof raw.timestamp === 'string' ? Date.parse(raw.timestamp) : NaN
    if (!Number.isNaN(ts)) { if (this.first === undefined) this.first = ts; this.last = ts }
    if (raw.type !== 'assistant') return
    const msg = raw.message as { content?: unknown; usage?: Record<string, unknown> } | undefined
    if (!msg) return
    if (Array.isArray(msg.content)) {
      for (const b of msg.content) if ((b as { type?: string }).type === 'tool_use') this.toolCount++
    }
    const u = msg.usage
    if (u) {
      this.tokens += (Number(u.input_tokens) || 0) + (Number(u.output_tokens) || 0)
        + (Number(u.cache_read_input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0)
    }
  }

  result(): { totalToolUseCount: number; totalDurationMs?: number; totalTokens?: number } {
    const { first, last } = this
    return {
      totalToolUseCount: this.toolCount,
      totalDurationMs: first !== undefined && last !== undefined && last > first ? last - first : undefined,
      totalTokens: this.tokens || undefined,
    }
  }
}

export function subagentStatsFromRawLines(rawLines: string[]): { totalToolUseCount: number; totalDurationMs?: number; totalTokens?: number } {
  const stats = new SubagentStats()
  for (const line of rawLines) stats.push(line)
  return stats.result()
}

/** Emit tool_end events for a user message's tool_result blocks. */
function toolResultEvents(msg: NormalizedMessage, toolIdToName: Map<string, string>): SessionEvent[] {
  const events: SessionEvent[] = []
  if (!msg.message) return events
  for (const block of msg.message.content) {
    if (block.type !== 'tool_result') continue
    const toolUseId = block.tool_use_id || ''
    const isError = block.is_error === true
    let rawOutput = ''
    if (typeof block.content === 'string') {
      rawOutput = block.content
    } else if (Array.isArray(block.content)) {
      rawOutput = block.content.filter((c) => c.type === 'text' && c.text).map((c) => c.text!).join('')
    }
    const toolName = toolIdToName.get(toolUseId) || ''
    const summary = computeToolSummary(toolName, rawOutput, isError)
    // Only a shell result feeds the turn stats; any other tool's tail would travel for nothing.
    const outputTail = toolName === 'Bash' ? block.tail ?? rawOutput.slice(-TAIL_OUTPUT) : undefined
    if (rawOutput.length > MAX_OUTPUT) rawOutput = rawOutput.slice(0, MAX_OUTPUT) + '\n…[truncated]'
    const agg = msg.toolUseResult
    const subagent = agg?.agentId
      ? { agentId: agg.agentId, agentType: agg.agentType, totalTokens: agg.totalTokens, totalDurationMs: agg.totalDurationMs, totalToolUseCount: agg.totalToolUseCount }
      : undefined
    events.push({
      type: 'tool_end',
      payload: {
        id: toolUseId, tool: toolName, output: rawOutput, ...(outputTail !== undefined ? { outputTail } : {}), isError, summary,
        ...(subagent ? { subagent } : {}),
        ...(typeof agg?.durationSeconds === 'number' ? { durationSeconds: agg.durationSeconds } : {}),
      },
    })
  }
  return events
}

/** Emit thinking/text/tool_start events for an assistant message's blocks. */
function assistantEvents(
  msg: NormalizedMessage,
  toolIdToName: Map<string, string>,
  thinkingIdPrefix: string,
  thinkingCounterStart = 0,
): SessionEvent[] {
  const events: SessionEvent[] = []
  if (!msg.message) return events
  let thinkingCounter = thinkingCounterStart
  for (const block of msg.message.content) {
    if (block.type === 'thinking' && block.thinking) {
      const thinkingId = `${thinkingIdPrefix}${thinkingCounter++}`
      const thinkingContent = block.thinking.length > MAX_THINKING
        ? block.thinking.slice(0, MAX_THINKING) + '\n…[truncated]'
        : block.thinking
      events.push({ type: 'thinking_delta', payload: { content: thinkingContent, thinkingId } })
      const title = extractThinkingTitle(block.thinking)
      if (title) events.push({ type: 'thinking_title', payload: { thinkingId, title } })
    } else if (block.type === 'text' && block.text) {
      events.push({ type: 'text_delta', payload: { content: block.text } })
    } else if (block.type === 'tool_use') {
      const toolId = block.id || ''
      const toolName = block.name || ''
      toolIdToName.set(toolId, toolName)
      let toolInput = block.input
      if (toolInput && typeof toolInput === 'object') {
        const inputCopy = { ...(toolInput as Record<string, unknown>) }
        for (const [key, val] of Object.entries(inputCopy)) {
          if (typeof val === 'string' && val.length > MAX_OUTPUT) {
            inputCopy[key] = val.slice(0, MAX_OUTPUT) + '\n…[truncated]'
          }
        }
        toolInput = inputCopy
      }
      events.push({ type: 'tool_start', payload: { id: toolId, tool: toolName, input: toolInput } })
    }
  }
  return events
}

// ── Compaction lines ────────────────────────────────────────────────────────────────────────────
//
// When a tmux claude session compacts (auto or `/compact`), it does an IN-FILE compact: the JSONL
// keeps the SAME sessionId and is append-only (pre-compact history stays on disk), so the byte-offset
// tail streams straight through — there is no dead file to re-point at and no truncation to re-read.
// The compact only injects a few bookkeeping lines we must handle so the stream stays clean:
//   • `system` / `subtype:"compact_boundary"` (+ `compactMetadata.trigger`) → one `context_compact`
//     indicator (purely a UI hint; the actual stream continuity is already guaranteed by the tail).
//   • the injected `isCompactSummary` user line (the big "This session is being continued…" summary)
//     and any `isMeta` bookkeeping line → suppressed via the AUTHORITATIVE flags (not a fragile
//     English-string match), so the summary is never rendered as a giant fake user turn / new turn.
//
// Returns the events to emit for a compact line (possibly `[]` to suppress it), or `undefined` when
// `raw` is not a compact line and should fall through to the normal user/assistant path.
export function compactEventFromRaw(raw: Record<string, unknown>): SessionEvent[] | undefined {
  if (raw.type === 'system' && raw.subtype === 'compact_boundary') {
    const meta = raw.compactMetadata as { trigger?: string } | undefined
    return [{
      type: 'context_compact',
      payload: {
        message: 'Context was compacted — the previous conversation has been summarized to free up space.',
        ...(meta?.trigger ? { trigger: meta.trigger } : {}),
      },
    }]
  }
  if (raw.isCompactSummary === true) return []
  if (raw.isMeta === true) {
    // NOT all isMeta user lines are bookkeeping. A `/loop` iteration is a REAL prompt that Claude
    // submits on the user's behalf every time the loop fires, and it is written as isMeta — so blanket
    // suppression made every iteration after the first invisible: no turn_started, therefore no recap,
    // therefore nothing on the device, while the loop kept running perfectly in the terminal.
    //
    // The discriminator is `promptSource`, which Claude sets authoritatively (same principle as the
    // flags above — never an English-string match):
    //   'typed'   + no isMeta → the human typed it
    //   'system'  + isMeta    → submitted programmatically: a loop iteration. This IS a turn.
    //   (absent)  + isMeta    → real bookkeeping: a compact summary, or a slash command's expansion
    //                           text. Still suppressed, so one `/goal` is not three user turns.
    if (raw.type === 'user' && raw.promptSource === 'system') return undefined
    return []
  }
  return undefined
}

// ── Full replay (session_get) ─────────────────────────────────────────────────────────────────────

/** Convert a whole session's raw JSONL lines to replay events (same render path as streaming). */
/**
 * A message the person typed while Claude Code was working. Claude Code delivers it into the running
 * turn as a `queued_command` attachment, not a prompt record. The live view leaves it out on purpose
 * (it opens no turn there), but the history must show it: without it a reopened conversation answered a
 * question it never showed (found by daemon QA with Claude Code 2.1.290). Sub-agent hand-backs and
 * Claude's own continuations arrive the same way, and they are not the person's words.
 */
function queuedHumanPrompt(raw: Record<string, unknown>): string | null {
  if (raw.type !== 'attachment') return null
  const attachment = raw.attachment as { type?: unknown; commandMode?: unknown; prompt?: unknown; origin?: { kind?: unknown } } | undefined
  if (attachment?.type !== 'queued_command' || attachment.commandMode !== 'prompt' || attachment.origin?.kind !== 'human') return null
  const prompt = attachment.prompt
  const text = typeof prompt === 'string' ? prompt
    : Array.isArray(prompt) ? prompt.map((block) => (block as { type?: unknown; text?: unknown })?.type === 'text' ? String((block as { text?: unknown }).text ?? '') : '').join('\n')
    : ''
  return text.trim() ? text : null
}

export function messagesToEvents(rawLines: string[]): SessionEvent[] {
  const events: SessionEvent[] = []
  const toolIdToName = new Map<string, string>()
  let thinkingCounter = 0
  let inAutoFixSequence = false
  let continuedAt = -1

  for (const line of rawLines) {
    if (!line.trim()) continue
    let raw: Record<string, unknown>
    try { raw = JSON.parse(line) as Record<string, unknown> } catch { continue }
    const compact = compactEventFromRaw(raw)
    if (compact) { events.push(...compact); continue } // compact boundary → indicator; summary/meta → suppressed
    const queued = queuedHumanPrompt(raw)
    if (queued) { events.push({ type: 'user_message', payload: { content: queued } }); continue }
    // A pass a blocking Stop hook continued, as the live view starts it (lineToEvents), once per pass.
    const continued = stopHookContinuation(raw)
    if (continued !== null) {
      if (continuedAt !== events.length - 1) events.push({ type: 'user_message', payload: { content: continued } })
      continuedAt = events.length - 1
      continue
    }
    const msg = transformLine(raw)
    if (!msg?.message) continue

    if (msg.type === 'user') {
      const content = msg.message.content
      if (isSystemPrompt(content)) { inAutoFixSequence = true; continue }
      const hasToolResult = content.some((c) => c.type === 'tool_result')
      const hasUserText = content.some((c) => c.type === 'text' && c.text?.trim())
      if (inAutoFixSequence && hasToolResult && !hasUserText) continue
      if (inAutoFixSequence) inAutoFixSequence = false

      if (!hasToolResult) {
        const textParts: string[] = []
        const images: Array<{ media_type: string; data: string }> = []
        for (const block of content) {
          if (block.type === 'text' && block.text) {
            let cleaned = stripContextSummary(block.text)
            if (cleaned) cleaned = stripSystemBlocks(cleaned)
            if (cleaned && !cleaned.match(/^\[Image: original \d+x\d+/)) textParts.push(cleaned)
          } else if (block.type === 'image' && block.source) {
            images.push({ media_type: block.source.media_type, data: block.source.data })
          }
        }
        const textContent = textParts.join('\n')
        if (textContent || images.length > 0) {
          events.push({ type: 'user_message', payload: { content: textContent, ...(images.length > 0 ? { images } : {}) } })
        }
        continue
      }

      events.push(...toolResultEvents(msg, toolIdToName))
      continue
    }

    // assistant
    if (inAutoFixSequence) continue
    const before = events.length
    events.push(...assistantEvents(msg, toolIdToName, 'thinking-hist-', thinkingCounter))
    // keep the per-session thinking counter monotonic across messages
    thinkingCounter += events.slice(before).filter((e) => e.type === 'thinking_delta').length
  }

  events.push({ type: 'done', payload: { result: 'success' } })
  return events
}

/**
 * Turn-snapped pagination window over raw JSONL lines, for `session_get` with `{limit, before}`.
 * `before` = uuid of the oldest line the client already holds (exclusive upper bound). Returns the
 * line slice to feed `messagesToEvents` plus cursor metadata.
 *
 * The window START is snapped back to a real user-prompt line so a window never splits an assistant
 * turn's `tool_use` from its `tool_result`: `messagesToEvents` is stateful (`toolIdToName` carries a
 * tool_use id → name across lines so the later tool_result renders the tool name), so a mid-turn cut
 * would drop tool names. A user-prompt line never sits between a tool_use and its tool_result, so
 * snapping there keeps every turn whole.
 */
/**
 * What a Claude history page knows of one line: the cursor that names it, and whether a page may start
 * there — a real user prompt, so a turn is never split. Shared by `windowRawLines` and the bounded pager
 * (lib/transcriptPages.ts), so the two cannot drift apart.
 */
export function claudePageLine(line: string): { cursor: string | null; startsPage: boolean } {
  if (!line.trim()) return { cursor: null, startsPage: false }
  let raw: Record<string, unknown>
  try { raw = JSON.parse(line) as Record<string, unknown> } catch { return { cursor: null, startsPage: false } }
  const cursor = (raw.uuid ?? raw.id ?? raw.message_id ?? null) as string | null
  const msg = transformLine(raw)
  return { cursor, startsPage: msg ? realUserText(msg) !== null : false }
}

export function windowRawLines(
  rawLines: string[],
  opts: { limit: number; before?: string },
): { window: string[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {
  // Per-line uuid + whether the line is a real user-prompt turn start (parse each line once).
  const meta = rawLines.map((line) => {
    const { cursor, startsPage } = claudePageLine(line)
    return { uuid: cursor, turnStart: startsPage }
  })

  let endIndex = rawLines.length
  if (opts.before) {
    const ci = meta.findIndex((m) => m.uuid === opts.before)
    // Cursor no longer in the file (should not happen — the transcript is append-only) → signal a
    // full reload rather than returning a wrong window.
    if (ci < 0) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }
    endIndex = ci // exclusive: the client already holds this line
  }

  let start = Math.max(0, endIndex - opts.limit)
  while (start > 0 && !meta[start].turnStart) start--

  return {
    window: rawLines.slice(start, endIndex),
    hasMore: start > 0,
    oldestCursor: meta[start]?.uuid ?? null,
  }
}

// ── Live tailing (watcher lines) with derived turn lifecycle ──────────────────────────────────────

export interface TurnState {
  turnOpen: boolean
  toolIdToName: Map<string, string>
  /** tool_use ids started but not yet resolved by a tool_result. */
  pendingTools: Set<string>
  thinkingCounter: number
  /** Before the counter in a live thinking id. A fold that starts mid-transcript names its window here
   *  (lib/attachTranscript.ts), so its ids cannot repeat ones another fold of the same session sent. */
  thinkingPrefix?: string
  /** The open turn is one a blocking Stop hook continued (`stopHookContinuation`), not a prompt's. */
  continued?: boolean
  /** How many turns this state has opened: a Stop hook closes only the turn that was open as it arrived
   *  (core/turns/turnHooks.ts). */
  opened?: number
}

/**
 * The turn a Stop hook that blocked keeps going, or null. `/goal` is built on such a hook, and people write
 * their own. Claude Code writes the hook's feedback as a hidden `isMeta` user line, then one of these, then
 * works on in the SAME turn with no prompt line between (real 2.1.282/2.1.283):
 *   {"type":"attachment","attachment":{"type":"goal_status","met":false,"condition":"…","reason":"…"}}
 *   {"type":"attachment","attachment":{"type":"hook_blocking_error","hookEvent":"Stop","blockingError":{"blockingError":"…"}}}
 * The pass's end_turn had closed the turn, so the rest ran with none open: no turn_ended, no recap, and
 * idle whenever a tool outlasted the work lease. A `sentinel` goal_status restates an active goal at start.
 * The label matches the Codex normalizer's goal continuations.
 */
export function stopHookContinuation(raw: Record<string, unknown>): string | null {
  if (raw.type !== 'attachment') return null
  const attachment = raw.attachment as Record<string, unknown> | undefined
  if (attachment?.type === 'goal_status' && attachment.met === false && attachment.sentinel !== true) {
    const condition = typeof attachment.condition === 'string' ? attachment.condition.trim() : ''
    return condition ? `Continuing goal: ${condition}` : 'Continuing goal'
  }
  if (attachment?.type === 'hook_blocking_error' && attachment.hookEvent === 'Stop') {
    const blocking = attachment.blockingError as { blockingError?: unknown } | undefined
    const reason = typeof blocking?.blockingError === 'string' ? blocking.blockingError.trim().split('\n')[0].trim() : ''
    return reason ? `Continuing: ${reason.length > 200 ? `${reason.slice(0, 197)}...` : reason}` : 'Continuing'
  }
  return null
}

export function newTurnState(): TurnState {
  return { turnOpen: false, toolIdToName: new Map(), pendingTools: new Set(), thinkingCounter: 0 }
}

// Terminal assistant stop reasons that close a turn. `tool_use` is deliberately absent (the turn
// continues into the tool). `pause_turn` is absent too — it may legitimately resume; the Stop hook
// (which only fires when the agent is truly done) is the authoritative catch-all for that case.
// `max_tokens`/`refusal` are included so a turn that ends on them still closes from the JSONL alone.
const TERMINAL_STOP_REASONS = new Set(['end_turn', 'stop_sequence', 'max_tokens', 'refusal'])

/**
 * Convert ONE appended JSONL line into live events. Derives turn_started/turn_ended from content:
 *  - a real user prompt  → (turn_ended if one was open) + turn_started{userMessage}
 *  - assistant blocks    → thinking/text/tool_start (tool ids tracked as pending)
 *  - user tool_results   → tool_end (resolves pending ids)
 *  - assistant stop_reason in TERMINAL_STOP_REASONS with no pending tools → turn_ended
 */
export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {
  if (!rawLine.trim()) return []
  let raw: Record<string, unknown>
  try { raw = JSON.parse(rawLine) as Record<string, unknown> } catch { return [] }
  // A valid-JSON but non-object line (the literal `null`, a number, a bare string) would make the
  // property access in compactEventFromRaw / transformLine throw — and on the unguarded watcher path
  // that kills the daemon. Any non-object line has nothing to emit.
  if (!raw || typeof raw !== 'object') return []
  // Compaction: emit the boundary indicator; suppress the injected summary/meta lines. The turn state
  // is left untouched, so an auto-compact that fires MID-TURN keeps the open turn open (the assistant
  // continuation after the boundary just streams under it) instead of the summary opening a fake turn.
  const compact = compactEventFromRaw(raw)
  if (compact) return compact
  // Sub-agent finished. Deliberately does NOT touch the turn state: the parent turn already closed on the
  // launch ack, and this record is not a prompt.
  const finished = taskNotificationEvent(raw)
  if (finished) return [finished]
  // A Stop hook that blocked: the pass's end_turn closed the turn Claude Code works on in. Open it again.
  const continued = stopHookContinuation(raw)
  if (continued !== null) {
    if (state.turnOpen) return []
    state.turnOpen = true
    state.opened = (state.opened ?? 0) + 1
    state.pendingTools.clear()
    state.continued = true
    return [{ type: 'turn_started', payload: { userMessage: continued } }]
  }
  // Claude Code's own record that its turn is over. A continued pass can end with no output: when the hook
  // refuses again, Claude Code pauses the goal and writes only notices and this (real 2.1.283), with no
  // end_turn or Stop to close what was opened above. Every other turn is closed as before.
  if (raw.type === 'system' && raw.subtype === 'turn_duration') {
    if (!state.turnOpen || !state.continued) return []
    state.turnOpen = false
    state.pendingTools.clear()
    return [{ type: 'turn_ended', payload: {} }]
  }
  const msg = transformLine(raw)
  if (!msg?.message) return []

  const events: LiveEvent[] = []

  if (msg.type === 'user') {
    // Interrupt: close the open turn and start NOTHING. This is also the only signal for an ESC pressed
    // straight in the terminal — no cancel frame reaches the adapter there — so the turn has to end here.
    if (isInterruptLine(msg)) {
      if (!state.turnOpen) return []
      state.turnOpen = false
      state.pendingTools.clear()
      return [{ type: 'turn_ended', payload: { aborted: true } }]
    }
    const userText = realUserText(msg)
    if (userText !== null) {
      // New prompt (typed in the terminal OR injected from the web) — starts a turn.
      if (state.turnOpen) events.push({ type: 'turn_ended', payload: {} })
      state.turnOpen = true
      state.opened = (state.opened ?? 0) + 1
      state.pendingTools.clear()
      state.continued = false
      events.push({ type: 'turn_started', payload: { userMessage: userText } })
      return events
    }
    // tool_result echoes: resolve pending tools.
    const ends = toolResultEvents(msg, state.toolIdToName)
    for (const e of ends) {
      if (e.type === 'tool_end') state.pendingTools.delete(e.payload.id)
    }
    events.push(...ends)
    return events
  }

  // assistant
  const before = events.length
  events.push(...assistantEvents(msg, state.toolIdToName, state.thinkingPrefix ?? 'thinking-live-', state.thinkingCounter))
  state.thinkingCounter += events.slice(before).filter((e) => e.type === 'thinking_delta').length
  for (const e of events) {
    if (e.type === 'tool_start') state.pendingTools.add(e.payload.id)
  }

  const stop = msg.stopReason
  if (state.turnOpen && stop && TERMINAL_STOP_REASONS.has(stop) && state.pendingTools.size === 0) {
    state.turnOpen = false
    events.push({ type: 'turn_ended', payload: {} })
  }
  return events
}

function parseRecord(rawLine: string): Record<string, unknown> | null {
  if (!rawLine.trim()) return null
  try {
    const raw = JSON.parse(rawLine) as unknown
    return raw && typeof raw === 'object' ? raw as Record<string, unknown> : null
  } catch { return null }
}

/**
 * The record `lineToEvents` opens a turn on — a real user prompt — decided from the record alone, as
 * `lineToEvents` decides it whatever came before. Attaching reads a transcript backward to the last
 * one of these and folds only from there (lib/attachTranscript.ts): every turn-scoped piece of
 * `TurnState` is reset by it, so the fold from here ends exactly where the whole-history fold does.
 */
export function startsClaudeTurn(rawLine: string): boolean {
  const raw = parseRecord(rawLine)
  if (!raw || compactEventFromRaw(raw) || taskNotificationEvent(raw)) return false
  const msg = transformLine(raw)
  if (!msg?.message || msg.type !== 'user' || isInterruptLine(msg)) return false
  return realUserText(msg) !== null
}

/**
 * The tool calls a Claude record makes (`defines`) and the earlier calls whose results it carries
 * (`references`), decided along `lineToEvents`' own branches. A result names its tool from the call
 * `lineToEvents` saw earlier, so an attach that starts mid-transcript reaches back for the calls its
 * turn's results answer (lib/attachTranscript.ts).
 */
export function claudeToolLinks(rawLine: string): { defines: string[]; references: string[] } {
  const raw = parseRecord(rawLine)
  if (!raw || compactEventFromRaw(raw) || taskNotificationEvent(raw)) return { defines: [], references: [] }
  const msg = transformLine(raw)
  if (!msg?.message) return { defines: [], references: [] }
  if (msg.type === 'assistant') {
    return { defines: msg.message.content.filter((block) => block.type === 'tool_use').map((block) => block.id || ''), references: [] }
  }
  if (isInterruptLine(msg) || realUserText(msg) !== null) return { defines: [], references: [] }
  return { defines: [], references: msg.message.content.filter((block) => block.type === 'tool_result').map((block) => block.tool_use_id || '') }
}

/** `tailFileUntil` selector for `lastTurnTextFromRawLines`: stop on the prompt it resets on, keep the
 *  assistant records it reads after that, and drop everything else it ignores — so a recap reads the
 *  last turn's text instead of the whole conversation. */
export function selectClaudeRecapLine(line: string): 'keep' | 'skip' | 'stop' {
  const raw = parseRecord(line)
  if (!raw || compactEventFromRaw(raw) !== undefined) return 'skip'
  const msg = transformLine(raw)
  if (!msg?.message) return 'skip'
  if (realUserText(msg) !== null) return 'stop'
  return msg.type === 'assistant' ? 'keep' : 'skip'
}