mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-30 06:17:06 +00:00
* feat(cli): cross-flavor inline image display via MCP and ACP Share display_image prompt across MCP-bridge flavors (Cursor, Gemini, Kimi, Codex, Claude, OpenCode), auto-approve the tool in buildHapiMcpBridge, handle ACP image content blocks, and harden generated-image registration with content sniffing. Closes tiann/hapi#956 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): render generated-image cards reliably in chat Keep object URLs stable across refetch, upscale tiny inline images, fetch generated-image bytes with cache no-store (avoid empty 304 bodies), and load hapiMcpUrl from per-session API in hapi-display-image tooling. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(cli+web): display_video MCP for inline mp4/webm (#956) Add display_video alongside display_image, video MIME sniffing with avif guard, web GeneratedImageCard video player, and hapi-display-image auto-routing. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(cli+web): cross-flavor display_video parity with images (#956) Share display_video prompts across MCP-bridge flavors, auto-approve the tool, register mp4/webm via path sniffing, render inline video in web on the existing generated-image RPC path, and restore robust media card fetch. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): ACP image ordering and inline media source provenance Flush buffered assistant text before async generated_image emit from ACP image blocks (PR #958 review Major). Add optional source metadata on generated-image wire messages (ingress, flavor, toolCallId, toolName) for MCP, ACP, and Codex tool-result paths. Seeds artifact-event follow-up #966. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli+web): address PR #958 review Majors on media order and stale blobs Queue ACP session updates and await async image registration before later events; clear GeneratedImageCard blob state when imageId changes. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): await ACP queue after late-drain before turn_complete Straggler session/update during drainLateBuffers can queue async image registration; re-await sessionUpdateQueue so generated_image is not emitted after turn_complete. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(scripts): route AVIF ftyp brands to display_image in helper Match server-side detectImageMimeType so .avif files are not sent to display_video and rejected as unsupported video. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(#956): agent inline-media doctor and discovery fixes - hapi doctor inline-media: probe bridges, print per-session inline commands - Expose hapiMcpUrl on session list summaries (stops false "no MCP" scans) - Helper script: match cursorSessionId prefixes; HAPI_SESSION_ID path-only mode - ACP bridge prompt: shell fallback + HAPI session id vs agent id rule Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): allow immutable cache for generated media blobs Drop cache: no-store on generated-image fetch so browser can reuse hub immutable responses; on 304 re-read via force-cache (#927, PR review). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#956): Cursor native MCP overlay; drop user-turn bridge prepend Cursor ACP ignores session/new mcpServers. Write .cursor/mcp.json and run agent mcp enable hapi instead. Remove HAPI_MCP_BRIDGE_PROMPT from user turns on ACP remotes; enrich MCP tool descriptions for discovery. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve non-HAPI mcp.json keys on Cursor overlay cleanup Cleanup only removes or restores the hapi MCP entry instead of rewriting the full pre-session snapshot, so concurrent edits to other servers survive. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): handle generated_image in Grok ACP launcher switch Upstream Grok launcher exhaustiveness broke after AgentMessage gained generated_image for cross-flavor inline media. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): rebase fallout for display_video + OpenCode skill lookup Gate display_video in the STDIO bridge, restore OpenCode first-prompt TITLE_INSTRUCTION (skill_lookup), and update tool-list test expectations. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): leave user-owned hapi MCP entry alone on overlay cleanup Only undo mcpServers.hapi when it still matches the exact entry this session installed; concurrent Cursor/user edits of that key survive. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): exact-match auto-approve for display_image and display_video Move media tools off substring name/id hints onto the exact-name set so forged lookalike tools are not approved in default permission mode. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): drop dead Cursor bridge prompt; put guidance in MCP descriptions Cursor must not get a user-turn media prepend (prompt-taint). Remove unused HAPI_MCP_BRIDGE_PROMPT_CURSOR and embed DISPLAY_*_PROMPT_CURSOR in the display_image/display_video MCP tool descriptions instead. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): require user approval for display_image and display_video Those tools read arbitrary local paths into chat; keep them on MCP approval_mode prompt and out of default-mode auto-approve exact names. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: re-trigger Codex PR review after provider 503 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): ignore URI-only ACP image blocks that read local disk Passive ACP agentMessageChunk handling must not load file:// or bare paths; local media goes through prompt-gated display_image/display_video. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): allowlist MP4 ftyp brands for video sniffing Reject HEIC/HEIF and other non-video ISO-BMFF containers instead of treating every non-AVIF ftyp as video/mp4. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): keep Cursor ACP startup if MCP overlay fails Wrap installCursorMcpOverlay so a malformed project .cursor/mcp.json cannot abort the session; continue without inline media tools. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): fail doctor inline-media when checks fail Exit non-zero whenever required checks fail, even if an active hapiMcpUrl bridge is present. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): expect display_video when change_title is disabled Native ACP title mode still exposes display_image and display_video; update startHappyServer test after rebase onto 0.23.4. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): keep ACP title sync synchronous outside media queue session_info_update title forwarding (#1028) must not wait on the async message-handler queue used for inline media ordering. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): sniff media headers only; advertise OpenCode display_video Read 16 bytes for detectMediaTool instead of the whole file, and include hapi_display_video in OPENCODE_NATIVE_TOOL_INSTRUCTION for remote ACP. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): show Cursor generate_image inline in HAPI chat cursor/generate_image only emitted a tool card; register filePath or base64 imageData into generatedImages and emit generated_image so the web chat card renders (issue #956 / swear01 report). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): ignore path-only Cursor generate_image reads Path-only filePath registration bypassed permission-gated display_image / display_video MCP tools. Keep base64 imageData only; local paths must go through MCP approval. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): gate inline media base64 length before decode Reject oversized ACP/Cursor base64 payloads by character count so the CLI never allocates past the 25 MB generated-image cap. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): require EBML DocType webm for inline video sniff Bare EBML magic matches Matroska/MKV too; only accept DocType webm. Also restore annotated Playwright cursor in annotatedVideoUseOption. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(scripts): read 128-byte header for WebM DocType sniff detectMediaTool only loaded 16 bytes, so EBML DocType webm was often missing and valid WebM files fell through to display_image. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): compare generated-image source by value in reconcile Wire normalization allocates a fresh source object each pass; reference equality forced media-card recomputation on every reload/SSE refresh. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): inject Cursor MCP enable for overlay unit tests installCursorMcpOverlay always spawned `agent mcp enable`; tests now pass a noop so the suite never shells out to a real Cursor binary. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): shell-quote doctor inline-media helper command Paths and session prefixes with spaces/metacharacters broke the copied snippet; JSON.stringify each interpolated argument. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): fix doctor inline-media quote path expectation Repo root from scriptPath is three levels up (cli/), not the parent of cli. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli/web): per-session Cursor MCP overlay id and bound tiny-image scale Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): redact generate_image base64 from logs and fix doctor MCP ids Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): harden inline-media doctor for packaged installs and hub headers Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): lock Cursor mcp.json updates and bound ACP media filenames Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve mcp.json mode and token-scoped overlay locks Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): publish Cursor MCP lock owners via link(2) and treat EPERM as alive Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): fail closed on stale MCP locks; keep concurrent mcp.json top-level keys Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): roll back Cursor MCP overlay when agent mcp enable fails Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): await ACP session queue in suppressUpdatesDuring tests #958 queues handleUpdate for media registration; upstream compact tests assumed sync delivery after restore. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): capture ACP handler at enqueue; keep display_video manual Close two Major review findings on #958: suppress queue leak after restore, and Claude --allowedTools auto-approving local-path video. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: write through symlinked mcp.json; lazy-load inline video Preserve user Cursor MCP symlinks on atomic overlay writes, and require explicit Load video before fetching large generated-video blobs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): use valid TerminalToolDisplayMode in media card test Co-authored-by: Cursor <cursoragent@cursor.com> * fix(scripts): require unique session prefix in display helper Reject ambiguous prefix matches so images/videos cannot land in the wrong HAPI chat when multiple agent session ids share a prefix. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): always cleanup Cursor MCP overlay on teardown Run overlay cleanup in finally so cancelAll/disconnect failures cannot leave a dead hapi-<sessionId> entry in .cursor/mcp.json. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): handle Copilot generated_image; refuse MCP symlinks Unblock typecheck after Antigravity/Copilot merge, and fail closed when .cursor/mcp.json or .cursor is a project-controlled symlink. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: abort restore deliveryMode; prune dead Cursor MCP overlays Unblock web typecheck after steer merge, and recover orphaned hapi-* mcp.json entries via HAPI_MCP_OVERLAY_PID ownership stamps. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): recover dead-PID Cursor MCP overlay locks Token-matched unlock so a crash mid-lock no longer permanently disables inline media; keep live-owner waits identity-safe. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): serialize Cursor MCP stale-lock recovery Acquire an exclusive recovery lock before token-matched unlink so two recoverers cannot remove a successor's live mcp.json lock. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): fail closed on stale Cursor MCP overlay locks Withdraw racy auto-recovery: pathname check-then-unlink/rename can steal a successor lock. Stale locks throw with an explicit rm hint instead. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): drop duplicate deliveryMode on abort restore Merge left both steer and queue; keep queue so retries after abort do not re-bind to a later Pi turn. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): bound inline media reads on open fd Close TOCTOU between pathname size check and readFile for display_image / display_video and registerGeneratedImageFromPath. Also preserve non-PID env edits on Cursor MCP overlay cleanup. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): repair happyMcpStdioBridge test syntax after merge Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): write Cursor MCP overlay to ~/.cursor, not the project Keep ephemeral hapi-<sessionId> bridges out of the checked-out tree so agents cannot git-add a live loopback URL. Tests inject mcpConfigDir. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): point Cursor MCP diagnostics at ~/.cursor/mcp.json Co-authored-by: Cursor <cursoragent@cursor.com> * feat(media): add audio and file display --------- Co-authored-by: HeavyGee <133152184+heavygee@users.noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Debian <heavygee@oos-linux.in.lockhouse>
1039 lines
44 KiB
TypeScript
1039 lines
44 KiB
TypeScript
import type { AgentReasoningBlock, AgentTextBlock, ChatBlock, CliOutputBlock, CodexReviewBlock, ToolCallBlock, ToolPermission } from '@/chat/types'
|
|
import type { TracedMessage } from '@/chat/tracer'
|
|
import { createCliOutputBlock, isCliOutputText, mergeCliOutputBlocks } from '@/chat/reducerCliOutput'
|
|
import { parseMessageAsEvent } from '@/chat/reducerEvents'
|
|
import { collectTitleChanges, ensureToolBlock, extractTitleFromChangeTitleInput, isChangeTitleToolName, type PermissionEntry } from '@/chat/reducerTools'
|
|
import { isSubagentToolName } from '@/chat/subagentTool'
|
|
import { asString, isObject } from '@hapi/protocol'
|
|
|
|
function getEventString(event: Record<string, unknown>, key: string): string | null {
|
|
return asString(event[key])
|
|
}
|
|
|
|
function getEventNumber(event: Record<string, unknown>, key: string): number | null {
|
|
const value = event[key]
|
|
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
|
}
|
|
|
|
function getAgentRunStartedAt(event: Record<string, unknown>): number | null {
|
|
return getEventNumber(event, 'startedAt') ?? getEventNumber(event, 'started_at')
|
|
}
|
|
|
|
function getAgentRunCompletedAt(event: Record<string, unknown>): number | null {
|
|
return getEventNumber(event, 'completedAt') ?? getEventNumber(event, 'completed_at')
|
|
}
|
|
|
|
function setEarliestStartedAt(block: ToolCallBlock, startedAt: number | null): void {
|
|
if (startedAt === null) return
|
|
const nextStartedAt = block.tool.startedAt === null
|
|
? startedAt
|
|
: Math.min(block.tool.startedAt, startedAt)
|
|
if (nextStartedAt !== block.tool.startedAt) {
|
|
block.tool = { ...block.tool, startedAt: nextStartedAt }
|
|
}
|
|
}
|
|
|
|
// Mirror of setEarliestStartedAt for the Claude-entry execution-machine start
|
|
// timestamp. Only ever fed a real Claude `agentTimestamp` (never the hub
|
|
// receive time) so the both-or-neither contract in `toolDurationMs` holds; a
|
|
// null argument is a no-op. Takes the earliest so it also backfills correctly
|
|
// when the tool_result entry was processed before the tool_use entry.
|
|
function setEarliestExecStartedAt(block: ToolCallBlock, execStartedAt: number | null): void {
|
|
if (execStartedAt === null) return
|
|
const nextExecStartedAt = block.tool.execStartedAt === null
|
|
? execStartedAt
|
|
: Math.min(block.tool.execStartedAt, execStartedAt)
|
|
if (nextExecStartedAt !== block.tool.execStartedAt) {
|
|
block.tool = { ...block.tool, execStartedAt: nextExecStartedAt }
|
|
}
|
|
}
|
|
|
|
function getAgentRunCardId(event: Record<string, unknown>, fallback: string): string {
|
|
return getEventString(event, 'cardId') ?? getEventString(event, 'card_id') ?? fallback
|
|
}
|
|
|
|
function isFallbackAgentRunCardId(cardId: string, agentId: string | null): boolean {
|
|
return agentId !== null && cardId === `codex-agent:${agentId}`
|
|
}
|
|
|
|
function mapAgentRunStatusToToolState(status: string | null): ToolCallBlock['tool']['state'] {
|
|
if (status === 'completed') return 'completed'
|
|
if (
|
|
status === 'failed'
|
|
|| status === 'error'
|
|
|| status === 'canceled'
|
|
|| status === 'cancelled'
|
|
|| status === 'notFound'
|
|
|| status === 'not_found'
|
|
) return 'error'
|
|
if (status === 'pending') return 'pending'
|
|
return 'running'
|
|
}
|
|
|
|
function isTerminalAgentRunState(state: ToolCallBlock['tool']['state']): boolean {
|
|
return state === 'completed' || state === 'error'
|
|
}
|
|
|
|
function isNonTerminalAgentRunState(state: ToolCallBlock['tool']['state']): boolean {
|
|
return state === 'running' || state === 'pending'
|
|
}
|
|
|
|
function shouldIgnoreAgentRunNonTerminalUpdateAfterTerminal(
|
|
block: ToolCallBlock,
|
|
nextState: ToolCallBlock['tool']['state'],
|
|
event: Record<string, unknown>
|
|
): boolean {
|
|
if (!isTerminalAgentRunState(block.tool.state)) return false
|
|
if (!isNonTerminalAgentRunState(nextState)) return false
|
|
|
|
const activityKind = getEventString(event, 'activityKind') ?? getEventString(event, 'activity_kind')
|
|
return activityKind === 'wait_agent' || activityKind === 'close_agent'
|
|
}
|
|
|
|
function isCloseAgentCleanupUpdate(event: Record<string, unknown>): boolean {
|
|
const activityKind = getEventString(event, 'activityKind') ?? getEventString(event, 'activity_kind')
|
|
if (activityKind === 'close_agent' || activityKind === 'closed') return true
|
|
|
|
const activity = getEventString(event, 'activity')
|
|
const statusText = getEventString(event, 'statusText') ?? getEventString(event, 'status_text')
|
|
if (activityKind !== 'canceled' || (activity !== 'Closed' && statusText !== 'Closed')) return false
|
|
|
|
const result = isObject(event.result) ? event.result : null
|
|
return Boolean(result && (isObject(result.previous_status) || isObject(result.previousStatus)))
|
|
}
|
|
|
|
function shouldIgnoreAgentRunCloseCleanupAfterTerminal(
|
|
block: ToolCallBlock,
|
|
status: string | null,
|
|
event: Record<string, unknown>
|
|
): boolean {
|
|
if (!isTerminalAgentRunState(block.tool.state)) return false
|
|
if (status === 'failed' || status === 'error') return false
|
|
return isCloseAgentCleanupUpdate(event)
|
|
}
|
|
|
|
function getAgentRunDisplayPatch(event: Record<string, unknown>): Record<string, unknown> {
|
|
const patch: Record<string, unknown> = {}
|
|
const summary = getEventString(event, 'summary')
|
|
const activity = getEventString(event, 'activity')
|
|
const activityKind = getEventString(event, 'activityKind') ?? getEventString(event, 'activity_kind')
|
|
|
|
if (summary) patch.summary = summary
|
|
if (activity) patch.activity = activity
|
|
if (activityKind) patch.activityKind = activityKind
|
|
|
|
return patch
|
|
}
|
|
|
|
function getAgentRunFingerprint(event: Record<string, unknown>): string | null {
|
|
const summary = getEventString(event, 'summary')
|
|
if (summary) return summary
|
|
|
|
const input = isObject(event.input) ? event.input : null
|
|
const direct = input ? asString(input.message) ?? asString(input.prompt) : null
|
|
if (direct) return direct.replace(/\s+/g, ' ').trim()
|
|
|
|
if (input && Array.isArray(input.items)) {
|
|
const text = input.items
|
|
.map((item) => isObject(item) ? asString(item.text) : null)
|
|
.filter((part): part is string => Boolean(part))
|
|
.join('\n\n')
|
|
.replace(/\s+/g, ' ')
|
|
.trim()
|
|
return text.length > 0 ? text : null
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
function isAgentNotFoundUpdate(event: Record<string, unknown>): boolean {
|
|
const status = getEventString(event, 'status')
|
|
const activityKind = getEventString(event, 'activityKind') ?? getEventString(event, 'activity_kind')
|
|
return status === 'notFound'
|
|
|| status === 'not_found'
|
|
|| activityKind === 'not_found'
|
|
}
|
|
|
|
function isAgentToolOnlyUpdate(event: Record<string, unknown>): boolean {
|
|
const activityKind = getEventString(event, 'activityKind') ?? getEventString(event, 'activity_kind')
|
|
return activityKind === 'wait_agent'
|
|
|| activityKind === 'send_input'
|
|
|| activityKind === 'resume_agent'
|
|
|| activityKind === 'close_agent'
|
|
|| isAgentNotFoundUpdate(event)
|
|
}
|
|
|
|
function isOrphanAgentRunBlock(block: ToolCallBlock): boolean {
|
|
if (block.children.length > 0) return false
|
|
if (block.tool.result !== undefined) return false
|
|
if (block.tool.state === 'completed' || block.tool.state === 'error') return false
|
|
if (isObject(block.tool.input) && (asString(block.tool.input.agentId) || asString(block.tool.input.agent_id))) {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
function prefixAgentTraceId(agentId: string, kind: 'trace' | 'call', id: string): string {
|
|
const prefix = `codex-agent:${agentId}:`
|
|
return id.startsWith(prefix) ? id : `${prefix}${kind}:${id}`
|
|
}
|
|
|
|
function normalizeTraceMessage(
|
|
agentId: string,
|
|
message: unknown,
|
|
source: TracedMessage,
|
|
): TracedMessage[] {
|
|
const data = isObject(message) ? message : null
|
|
if (!data || typeof data.type !== 'string') return []
|
|
|
|
const traceId = prefixAgentTraceId(agentId, 'trace', asString(data.id) ?? `${source.id}:trace`)
|
|
const createdAt = source.createdAt
|
|
const base = {
|
|
localId: null,
|
|
createdAt,
|
|
isSidechain: false,
|
|
meta: source.meta
|
|
}
|
|
|
|
if (data.type === 'error' && typeof data.message === 'string') {
|
|
return [{
|
|
...base,
|
|
id: traceId,
|
|
role: 'event',
|
|
content: { type: 'error', message: data.message }
|
|
} as TracedMessage]
|
|
}
|
|
|
|
if (data.type === 'message' && typeof data.message === 'string') {
|
|
return [{
|
|
...base,
|
|
id: traceId,
|
|
role: 'agent',
|
|
content: [{ type: 'text', text: data.message, uuid: traceId, parentUUID: null }]
|
|
} as TracedMessage]
|
|
}
|
|
|
|
if (data.type === 'reasoning' && typeof data.message === 'string') {
|
|
return [{
|
|
...base,
|
|
id: traceId,
|
|
role: 'agent',
|
|
content: [{ type: 'reasoning', text: data.message, uuid: traceId, streamId: traceId, parentUUID: null }]
|
|
} as TracedMessage]
|
|
}
|
|
|
|
if (data.type === 'tool-call' && typeof data.callId === 'string') {
|
|
const callId = prefixAgentTraceId(agentId, 'call', data.callId)
|
|
return [{
|
|
...base,
|
|
id: traceId,
|
|
role: 'agent',
|
|
content: [{
|
|
type: 'tool-call',
|
|
id: callId,
|
|
name: asString(data.name) ?? 'unknown',
|
|
input: data.input,
|
|
description: null,
|
|
uuid: traceId,
|
|
parentUUID: null
|
|
}]
|
|
} as TracedMessage]
|
|
}
|
|
|
|
if (data.type === 'tool-call-result' && typeof data.callId === 'string') {
|
|
const callId = prefixAgentTraceId(agentId, 'call', data.callId)
|
|
return [{
|
|
...base,
|
|
id: traceId,
|
|
role: 'agent',
|
|
content: [{
|
|
type: 'tool-result',
|
|
tool_use_id: callId,
|
|
content: data.output,
|
|
is_error: Boolean(data.is_error),
|
|
uuid: traceId,
|
|
parentUUID: null
|
|
}]
|
|
} as TracedMessage]
|
|
}
|
|
|
|
if (data.type === 'token_count') {
|
|
return []
|
|
}
|
|
|
|
if (data.type === 'ready' || data.type === 'task_complete') {
|
|
return [{
|
|
...base,
|
|
id: traceId,
|
|
role: 'event',
|
|
content: { type: 'ready', agentId }
|
|
} as TracedMessage]
|
|
}
|
|
|
|
return [{
|
|
...base,
|
|
id: traceId,
|
|
role: 'event',
|
|
content: {
|
|
type: 'message',
|
|
message: asString(data.statusText) ?? asString(data.status) ?? data.type
|
|
}
|
|
} as TracedMessage]
|
|
}
|
|
|
|
export function reduceTimeline(
|
|
messages: TracedMessage[],
|
|
context: {
|
|
permissionsById: Map<string, PermissionEntry>
|
|
groups: Map<string, TracedMessage[]>
|
|
consumedGroupIds: Set<string>
|
|
titleChangesByToolUseId: Map<string, string>
|
|
emittedTitleChangeToolUseIds: Set<string>
|
|
}
|
|
): { blocks: ChatBlock[]; toolBlocksById: Map<string, ToolCallBlock>; hasReadyEvent: boolean } {
|
|
const blocks: ChatBlock[] = []
|
|
const toolBlocksById = new Map<string, ToolCallBlock>()
|
|
const agentRunBlocksByCardId = new Map<string, ToolCallBlock>()
|
|
const agentRunCardByAgentId = new Map<string, string>()
|
|
const agentRunTraceMessagesByCardId = new Map<string, TracedMessage[]>()
|
|
const pendingAgentRunCardByFingerprint = new Map<string, string>()
|
|
const textBlocksByStreamId = new Map<string, AgentTextBlock>()
|
|
const reasoningBlocksByStreamId = new Map<string, AgentReasoningBlock>()
|
|
let hasReadyEvent = false
|
|
|
|
const ensureAgentRunBlock = (
|
|
cardId: string,
|
|
seed: {
|
|
createdAt: number
|
|
invokedAt?: number | null
|
|
model?: string | null
|
|
localId: string | null
|
|
meta?: unknown
|
|
input?: unknown
|
|
}
|
|
): ToolCallBlock => {
|
|
const block = ensureToolBlock(blocks, toolBlocksById, cardId, {
|
|
createdAt: seed.createdAt,
|
|
invokedAt: seed.invokedAt,
|
|
model: seed.model,
|
|
localId: seed.localId,
|
|
meta: seed.meta,
|
|
name: 'CodexAgent',
|
|
input: seed.input,
|
|
description: null
|
|
})
|
|
agentRunBlocksByCardId.set(cardId, block)
|
|
return block
|
|
}
|
|
|
|
const refreshAgentRunChildren = (cardId: string): void => {
|
|
const block = agentRunBlocksByCardId.get(cardId)
|
|
if (!block) return
|
|
const traceMessages = agentRunTraceMessagesByCardId.get(cardId) ?? []
|
|
if (traceMessages.length === 0) {
|
|
block.children = []
|
|
return
|
|
}
|
|
|
|
const child = reduceTimeline(traceMessages, {
|
|
permissionsById: context.permissionsById,
|
|
groups: new Map(),
|
|
consumedGroupIds: new Set<string>(),
|
|
titleChangesByToolUseId: collectTitleChanges(traceMessages),
|
|
emittedTitleChangeToolUseIds: new Set<string>()
|
|
})
|
|
block.children = child.blocks
|
|
}
|
|
|
|
const patchAgentRunInput = (block: ToolCallBlock, patch: Record<string, unknown>): void => {
|
|
const current = isObject(block.tool.input) ? block.tool.input : {}
|
|
block.tool = {
|
|
...block.tool,
|
|
input: {
|
|
...current,
|
|
...patch
|
|
}
|
|
}
|
|
}
|
|
|
|
const removeAgentRunBlock = (cardId: string): void => {
|
|
const block = agentRunBlocksByCardId.get(cardId)
|
|
if (!block) return
|
|
const index = blocks.findIndex((candidate) => candidate === block)
|
|
if (index !== -1) {
|
|
blocks.splice(index, 1)
|
|
}
|
|
toolBlocksById.delete(cardId)
|
|
agentRunBlocksByCardId.delete(cardId)
|
|
agentRunTraceMessagesByCardId.delete(cardId)
|
|
for (const [fingerprint, pendingCardId] of pendingAgentRunCardByFingerprint) {
|
|
if (pendingCardId === cardId) {
|
|
pendingAgentRunCardByFingerprint.delete(fingerprint)
|
|
}
|
|
}
|
|
}
|
|
|
|
const mergeAgentRunBlock = (fromCardId: string, toCardId: string, toBlock: ToolCallBlock): void => {
|
|
if (fromCardId === toCardId) return
|
|
|
|
const fromBlock = agentRunBlocksByCardId.get(fromCardId)
|
|
if (!fromBlock || fromBlock === toBlock) return
|
|
|
|
const fromInput = isObject(fromBlock.tool.input) ? fromBlock.tool.input : {}
|
|
const toInput = isObject(toBlock.tool.input) ? toBlock.tool.input : {}
|
|
if (Object.keys(fromInput).length > 0 || Object.keys(toInput).length > 0) {
|
|
toBlock.tool.input = {
|
|
...fromInput,
|
|
...toInput
|
|
}
|
|
}
|
|
|
|
toBlock.createdAt = Math.min(toBlock.createdAt, fromBlock.createdAt)
|
|
toBlock.tool.createdAt = Math.min(toBlock.tool.createdAt, fromBlock.tool.createdAt)
|
|
if (fromBlock.tool.startedAt !== null) {
|
|
toBlock.tool.startedAt = toBlock.tool.startedAt === null
|
|
? fromBlock.tool.startedAt
|
|
: Math.min(toBlock.tool.startedAt, fromBlock.tool.startedAt)
|
|
}
|
|
if (fromBlock.tool.completedAt !== null) {
|
|
toBlock.tool.completedAt = toBlock.tool.completedAt === null
|
|
? fromBlock.tool.completedAt
|
|
: Math.max(toBlock.tool.completedAt, fromBlock.tool.completedAt)
|
|
}
|
|
// Keep the exec-timestamp pair merged the same way as startedAt/
|
|
// completedAt so a merged card never carries a stale exec pair (agent-run
|
|
// cards currently never carry exec timestamps, but keep the invariant).
|
|
if (fromBlock.tool.execStartedAt !== null) {
|
|
toBlock.tool.execStartedAt = toBlock.tool.execStartedAt === null
|
|
? fromBlock.tool.execStartedAt
|
|
: Math.min(toBlock.tool.execStartedAt, fromBlock.tool.execStartedAt)
|
|
}
|
|
if (fromBlock.tool.execCompletedAt !== null) {
|
|
toBlock.tool.execCompletedAt = toBlock.tool.execCompletedAt === null
|
|
? fromBlock.tool.execCompletedAt
|
|
: Math.max(toBlock.tool.execCompletedAt, fromBlock.tool.execCompletedAt)
|
|
}
|
|
toBlock.durationMs = toBlock.durationMs ?? fromBlock.durationMs
|
|
toBlock.usage = toBlock.usage ?? fromBlock.usage
|
|
toBlock.model = toBlock.model ?? fromBlock.model
|
|
|
|
if (!isTerminalAgentRunState(toBlock.tool.state) && isTerminalAgentRunState(fromBlock.tool.state)) {
|
|
toBlock.tool.state = fromBlock.tool.state
|
|
}
|
|
if (toBlock.tool.result === undefined && fromBlock.tool.result !== undefined) {
|
|
toBlock.tool.result = fromBlock.tool.result
|
|
}
|
|
|
|
const fromTrace = agentRunTraceMessagesByCardId.get(fromCardId) ?? []
|
|
const toTrace = agentRunTraceMessagesByCardId.get(toCardId) ?? []
|
|
if (fromTrace.length > 0 || toTrace.length > 0) {
|
|
const mergedTrace = [...toTrace, ...fromTrace]
|
|
.sort((left, right) => left.createdAt - right.createdAt || left.id.localeCompare(right.id))
|
|
agentRunTraceMessagesByCardId.set(toCardId, mergedTrace)
|
|
agentRunTraceMessagesByCardId.delete(fromCardId)
|
|
refreshAgentRunChildren(toCardId)
|
|
} else if (toBlock.children.length === 0 && fromBlock.children.length > 0) {
|
|
toBlock.children = fromBlock.children
|
|
}
|
|
|
|
const index = blocks.findIndex((candidate) => candidate === fromBlock)
|
|
if (index !== -1) {
|
|
blocks.splice(index, 1)
|
|
}
|
|
toolBlocksById.delete(fromCardId)
|
|
agentRunBlocksByCardId.delete(fromCardId)
|
|
|
|
for (const [fingerprint, pendingCardId] of pendingAgentRunCardByFingerprint) {
|
|
if (pendingCardId === fromCardId) {
|
|
pendingAgentRunCardByFingerprint.set(fingerprint, toCardId)
|
|
}
|
|
}
|
|
for (const [mappedAgentId, mappedCardId] of agentRunCardByAgentId) {
|
|
if (mappedCardId === fromCardId) {
|
|
agentRunCardByAgentId.set(mappedAgentId, toCardId)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Pre-scan: collect UUIDs of system-injected user turns (sidechain
|
|
// prompts, task notifications, system reminders). These are used below
|
|
// to identify sentinel auto-replies ("No response requested.") whose
|
|
// parentUUID points to one of these injected messages.
|
|
const injectedTurnUuids = new Set<string>()
|
|
for (const msg of messages) {
|
|
if (msg.role !== 'agent' || !msg.isSidechain) continue
|
|
for (const c of msg.content) {
|
|
if (c.type === 'sidechain') {
|
|
injectedTurnUuids.add(c.uuid)
|
|
}
|
|
}
|
|
}
|
|
|
|
for (const msg of messages) {
|
|
if (msg.role === 'event') {
|
|
if (msg.content.type === 'ready') {
|
|
hasReadyEvent = true
|
|
continue
|
|
}
|
|
if (msg.content.type === 'token-count') {
|
|
continue
|
|
}
|
|
// abort-restore is a side-effect signal for the web composer,
|
|
// not a visible chat event. Skip it in the timeline.
|
|
if (msg.content.type === 'abort-restore') {
|
|
continue
|
|
}
|
|
if (msg.content.type === 'turn-duration') {
|
|
const targetId = msg.content.targetMessageId
|
|
const durationMs = msg.content.durationMs as number
|
|
type DurationBearingBlock = AgentTextBlock | AgentReasoningBlock | CliOutputBlock | ToolCallBlock
|
|
const isDurationTarget = (b: ChatBlock): b is DurationBearingBlock | CodexReviewBlock =>
|
|
b.kind === 'agent-text' || b.kind === 'agent-reasoning' || b.kind === 'codex-review' || b.kind === 'cli-output' || b.kind === 'tool-call'
|
|
let foundIndex = -1
|
|
|
|
if (targetId) {
|
|
foundIndex = blocks.findLastIndex(b => isDurationTarget(b) && (b.id === targetId || b.id.startsWith(`${targetId}:`)))
|
|
if (foundIndex === -1) {
|
|
foundIndex = blocks.findLastIndex(b => b.kind === 'tool-call' && b.tool.id === targetId)
|
|
}
|
|
}
|
|
|
|
if (foundIndex === -1) {
|
|
foundIndex = blocks.findLastIndex(isDurationTarget)
|
|
}
|
|
|
|
if (foundIndex !== -1) {
|
|
const b = blocks[foundIndex]
|
|
if (isDurationTarget(b)) {
|
|
b.durationMs = durationMs
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
|
|
if (
|
|
msg.content.type === 'agent-run-start'
|
|
|| msg.content.type === 'agent-run-update'
|
|
|| msg.content.type === 'agent-run-trace'
|
|
) {
|
|
const event = msg.content as Record<string, unknown>
|
|
const agentId = getEventString(event, 'agentId') ?? getEventString(event, 'agent_id')
|
|
const fallbackCardId = agentId ? `codex-agent:${agentId}` : msg.id
|
|
const rawCardId = getAgentRunCardId(event, fallbackCardId)
|
|
const previousCardId = agentId ? agentRunCardByAgentId.get(agentId) ?? null : null
|
|
const previousIsFallback = previousCardId !== null && isFallbackAgentRunCardId(previousCardId, agentId)
|
|
const rawIsFallback = isFallbackAgentRunCardId(rawCardId, agentId)
|
|
const cardId = agentId && previousCardId && !previousIsFallback && rawIsFallback
|
|
? previousCardId
|
|
: rawCardId
|
|
const mergeFromCardId = agentId
|
|
&& previousCardId
|
|
&& previousCardId !== cardId
|
|
&& previousIsFallback
|
|
&& !rawIsFallback
|
|
? previousCardId
|
|
: null
|
|
const fingerprint = getAgentRunFingerprint(event)
|
|
|
|
if (
|
|
msg.content.type === 'agent-run-update'
|
|
&& agentId
|
|
&& !previousCardId
|
|
&& rawIsFallback
|
|
&& isAgentToolOnlyUpdate(event)
|
|
) {
|
|
continue
|
|
}
|
|
|
|
if (msg.content.type === 'agent-run-start' && !agentId && fingerprint) {
|
|
const previousCardId = pendingAgentRunCardByFingerprint.get(fingerprint)
|
|
const previousBlock = previousCardId ? agentRunBlocksByCardId.get(previousCardId) : null
|
|
if (previousCardId && previousCardId !== cardId && previousBlock && isOrphanAgentRunBlock(previousBlock)) {
|
|
removeAgentRunBlock(previousCardId)
|
|
}
|
|
pendingAgentRunCardByFingerprint.set(fingerprint, cardId)
|
|
}
|
|
|
|
const block = ensureAgentRunBlock(cardId, {
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
model: msg.model,
|
|
localId: msg.localId,
|
|
meta: msg.meta,
|
|
input: event.input
|
|
})
|
|
|
|
if (mergeFromCardId) {
|
|
mergeAgentRunBlock(mergeFromCardId, cardId, block)
|
|
}
|
|
if (agentId) {
|
|
agentRunCardByAgentId.set(agentId, cardId)
|
|
}
|
|
|
|
if (msg.content.type === 'agent-run-start') {
|
|
const status = getEventString(event, 'status') ?? 'running'
|
|
const startedAt = getAgentRunStartedAt(event) ?? msg.createdAt
|
|
patchAgentRunInput(block, {
|
|
agentId,
|
|
agentStatus: status,
|
|
statusText: getEventString(event, 'statusText') ?? getEventString(event, 'status_text') ?? 'Starting',
|
|
...getAgentRunDisplayPatch(event)
|
|
})
|
|
const nextState = mapAgentRunStatusToToolState(status)
|
|
block.tool = { ...block.tool, state: nextState }
|
|
if (nextState === 'running') {
|
|
setEarliestStartedAt(block, startedAt)
|
|
}
|
|
continue
|
|
}
|
|
|
|
if (msg.content.type === 'agent-run-update') {
|
|
const status = getEventString(event, 'status') ?? 'running'
|
|
const nextState = mapAgentRunStatusToToolState(status)
|
|
const startedAt = getAgentRunStartedAt(event)
|
|
if (
|
|
shouldIgnoreAgentRunNonTerminalUpdateAfterTerminal(block, nextState, event)
|
|
|| shouldIgnoreAgentRunCloseCleanupAfterTerminal(block, status, event)
|
|
) {
|
|
continue
|
|
}
|
|
patchAgentRunInput(block, {
|
|
agentId,
|
|
agentStatus: status,
|
|
statusText: getEventString(event, 'statusText') ?? getEventString(event, 'status_text') ?? status,
|
|
...getAgentRunDisplayPatch(event)
|
|
})
|
|
block.tool = { ...block.tool, state: nextState }
|
|
if (nextState === 'running') {
|
|
setEarliestStartedAt(block, startedAt ?? msg.createdAt)
|
|
}
|
|
if (nextState === 'completed' || nextState === 'error') {
|
|
setEarliestStartedAt(block, startedAt)
|
|
block.tool = { ...block.tool, completedAt: getAgentRunCompletedAt(event) ?? msg.createdAt }
|
|
}
|
|
if ('result' in event) {
|
|
block.tool = { ...block.tool, result: event.result }
|
|
} else if ('error' in event) {
|
|
block.tool = { ...block.tool, result: event.error }
|
|
} else if ('spawnResult' in event) {
|
|
block.tool = { ...block.tool, result: event.spawnResult }
|
|
}
|
|
continue
|
|
}
|
|
|
|
if (msg.content.type === 'agent-run-trace') {
|
|
const traceAgentId = agentId
|
|
if (!traceAgentId) continue
|
|
const startedAt = getAgentRunStartedAt(event)
|
|
const traceCardId = agentRunCardByAgentId.get(traceAgentId) ?? cardId
|
|
const traceBlock = ensureAgentRunBlock(traceCardId, {
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
model: msg.model,
|
|
localId: msg.localId,
|
|
meta: msg.meta,
|
|
input: agentRunBlocksByCardId.has(traceCardId) ? undefined : { agentId: traceAgentId }
|
|
})
|
|
const tracePatch: Record<string, unknown> = {
|
|
agentId: traceAgentId,
|
|
agentStatus: traceBlock.tool.state,
|
|
...getAgentRunDisplayPatch(event)
|
|
}
|
|
if (!isTerminalAgentRunState(traceBlock.tool.state)) {
|
|
tracePatch.statusText = getEventString(event, 'statusText') ?? getEventString(event, 'status_text') ?? 'Running'
|
|
}
|
|
patchAgentRunInput(traceBlock, {
|
|
...tracePatch
|
|
})
|
|
const traceMessages = agentRunTraceMessagesByCardId.get(traceCardId) ?? []
|
|
traceMessages.push(...normalizeTraceMessage(traceAgentId, event.message, msg))
|
|
agentRunTraceMessagesByCardId.set(traceCardId, traceMessages)
|
|
refreshAgentRunChildren(traceCardId)
|
|
if (traceBlock.tool.state !== 'completed' && traceBlock.tool.state !== 'error') {
|
|
traceBlock.tool.state = 'running'
|
|
setEarliestStartedAt(traceBlock, startedAt ?? msg.createdAt)
|
|
}
|
|
continue
|
|
}
|
|
}
|
|
|
|
blocks.push({
|
|
kind: 'agent-event',
|
|
id: msg.id,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
model: msg.model,
|
|
event: msg.content,
|
|
meta: msg.meta
|
|
})
|
|
continue
|
|
}
|
|
|
|
const event = parseMessageAsEvent(msg)
|
|
if (event) {
|
|
blocks.push({
|
|
kind: 'agent-event',
|
|
id: msg.id,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
model: msg.model,
|
|
event,
|
|
meta: msg.meta
|
|
})
|
|
continue
|
|
}
|
|
|
|
if (msg.role === 'user') {
|
|
if (isCliOutputText(msg.content.text, msg.meta)) {
|
|
blocks.push(createCliOutputBlock({
|
|
id: msg.id,
|
|
localId: msg.localId,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
text: msg.content.text,
|
|
source: 'user',
|
|
meta: msg.meta
|
|
}))
|
|
continue
|
|
}
|
|
blocks.push({
|
|
kind: 'user-text',
|
|
id: msg.id,
|
|
localId: msg.localId,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
text: msg.content.text,
|
|
attachments: msg.content.attachments,
|
|
status: msg.status,
|
|
originalText: msg.originalText,
|
|
meta: msg.meta
|
|
})
|
|
continue
|
|
}
|
|
|
|
if (msg.role === 'agent') {
|
|
// When the message contains a Task/Agent tool_use, Claude often writes
|
|
// the prompt as a text block before the tool_use block. We only want to
|
|
// suppress that exact prompt text — not every text block in the message.
|
|
const taskToolCall = msg.content.find(
|
|
(c) => c.type === 'tool-call' && isSubagentToolName(c.name)
|
|
)
|
|
const taskPromptText: string | null = (() => {
|
|
if (!taskToolCall || taskToolCall.type !== 'tool-call') return null
|
|
const input = taskToolCall.input
|
|
if (typeof input === 'object' && input !== null && 'prompt' in input) {
|
|
const p = (input as { prompt: unknown }).prompt
|
|
if (typeof p === 'string') return p
|
|
}
|
|
return null
|
|
})()
|
|
|
|
for (let idx = 0; idx < msg.content.length; idx += 1) {
|
|
const c = msg.content[idx]
|
|
if (c.type === 'text') {
|
|
// Skip "No response requested." — Claude's sentinel auto-response
|
|
// to system-injected messages (task notifications, system reminders).
|
|
//
|
|
// Structural checks to avoid false positives:
|
|
// 1. msg.content.length === 1 — no tool calls or reasoning alongside
|
|
// 2. c.parentUUID points to a known injected turn UUID (collected
|
|
// in pre-scan from sidechain content blocks)
|
|
// 3. Exact text match on the known sentinel phrase
|
|
if (
|
|
msg.content.length === 1 &&
|
|
c.parentUUID !== null &&
|
|
injectedTurnUuids.has(c.parentUUID)
|
|
) {
|
|
const trimmedText = c.text.trim()
|
|
if (trimmedText === 'No response requested.' || trimmedText === 'No response requested') {
|
|
continue
|
|
}
|
|
}
|
|
|
|
// Skip text blocks that are just the Task tool prompt (already shown in tool card)
|
|
if (taskPromptText && c.text.trim() === taskPromptText.trim()) continue
|
|
|
|
if (isCliOutputText(c.text, msg.meta)) {
|
|
blocks.push(createCliOutputBlock({
|
|
id: `${msg.id}:${idx}`,
|
|
localId: msg.localId,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
usage: msg.usage,
|
|
model: msg.model,
|
|
text: c.text,
|
|
source: 'assistant',
|
|
meta: msg.meta
|
|
}))
|
|
continue
|
|
}
|
|
const streamId = asString(c.streamId)
|
|
if (streamId) {
|
|
const existing = textBlocksByStreamId.get(streamId)
|
|
if (existing) {
|
|
existing.text = c.text
|
|
existing.usage = msg.usage
|
|
existing.model = msg.model
|
|
existing.meta = msg.meta
|
|
existing.invokedAt = msg.invokedAt
|
|
continue
|
|
}
|
|
}
|
|
|
|
const block: AgentTextBlock = {
|
|
kind: 'agent-text',
|
|
id: `${msg.id}:${idx}`,
|
|
localId: msg.localId,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
usage: msg.usage,
|
|
model: msg.model,
|
|
text: c.text,
|
|
meta: msg.meta
|
|
}
|
|
blocks.push(block)
|
|
if (streamId) {
|
|
textBlocksByStreamId.set(streamId, block)
|
|
}
|
|
continue
|
|
}
|
|
|
|
if (c.type === 'generated-image') {
|
|
blocks.push({
|
|
kind: 'generated-image',
|
|
id: `${msg.id}:${idx}`,
|
|
localId: msg.localId,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
imageId: c.imageId,
|
|
fileName: c.fileName,
|
|
mimeType: c.mimeType,
|
|
source: c.source,
|
|
meta: msg.meta
|
|
})
|
|
continue
|
|
}
|
|
|
|
if (c.type === 'reasoning') {
|
|
const streamId = asString(c.streamId)
|
|
if (streamId) {
|
|
const existing = reasoningBlocksByStreamId.get(streamId)
|
|
if (existing) {
|
|
existing.text = c.text
|
|
existing.usage = msg.usage
|
|
existing.model = msg.model
|
|
existing.meta = msg.meta
|
|
existing.invokedAt = msg.invokedAt
|
|
continue
|
|
}
|
|
}
|
|
|
|
const block: AgentReasoningBlock = {
|
|
kind: 'agent-reasoning',
|
|
id: `${msg.id}:${idx}`,
|
|
localId: msg.localId,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
usage: msg.usage,
|
|
model: msg.model,
|
|
text: c.text,
|
|
meta: msg.meta
|
|
}
|
|
blocks.push(block)
|
|
if (streamId) {
|
|
reasoningBlocksByStreamId.set(streamId, block)
|
|
}
|
|
continue
|
|
}
|
|
|
|
if (c.type === 'codex-review') {
|
|
blocks.push({
|
|
kind: 'codex-review',
|
|
id: `${msg.id}:${idx}`,
|
|
localId: msg.localId,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
usage: msg.usage,
|
|
model: msg.model,
|
|
review: c.review,
|
|
meta: msg.meta
|
|
})
|
|
continue
|
|
}
|
|
|
|
if (c.type === 'summary') {
|
|
blocks.push({
|
|
kind: 'agent-event',
|
|
id: `${msg.id}:${idx}`,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
model: msg.model,
|
|
event: { type: 'message', message: c.summary },
|
|
meta: msg.meta
|
|
})
|
|
continue
|
|
}
|
|
|
|
if (c.type === 'tool-call') {
|
|
if (isChangeTitleToolName(c.name)) {
|
|
const title = context.titleChangesByToolUseId.get(c.id) ?? extractTitleFromChangeTitleInput(c.input)
|
|
if (title && !context.emittedTitleChangeToolUseIds.has(c.id)) {
|
|
context.emittedTitleChangeToolUseIds.add(c.id)
|
|
blocks.push({
|
|
kind: 'agent-event',
|
|
id: `${msg.id}:${idx}`,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
model: msg.model,
|
|
event: { type: 'title-changed', title },
|
|
meta: msg.meta
|
|
})
|
|
}
|
|
continue
|
|
}
|
|
|
|
const permission = context.permissionsById.get(c.id)?.permission
|
|
|
|
const block = ensureToolBlock(blocks, toolBlocksById, c.id, {
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
usage: msg.usage,
|
|
model: msg.model,
|
|
localId: msg.localId,
|
|
meta: msg.meta,
|
|
name: c.name,
|
|
input: c.input,
|
|
description: c.description,
|
|
nativeTitle: c.nativeTitle,
|
|
nativeKind: c.nativeKind,
|
|
progress: c.progress,
|
|
permission,
|
|
agentTimestamp: msg.agentTimestamp
|
|
})
|
|
|
|
if (block.tool.state === 'pending') {
|
|
block.tool = { ...block.tool, state: 'running' }
|
|
}
|
|
// Backfill both the hub-clock start and the Claude exec start
|
|
// regardless of state (not just the pending→running
|
|
// transition), so a tool_result reduced before its tool_use
|
|
// still lowers startedAt to the (earlier) tool_use receive
|
|
// time. Otherwise both hub ends equal the result time and
|
|
// toolDurationMs reads 0.0s. setEarliest* take the min; a
|
|
// null exec timestamp is a no-op, leaving exec start unset so
|
|
// toolDurationMs falls back to hub times on both sides.
|
|
setEarliestStartedAt(block, msg.createdAt)
|
|
setEarliestExecStartedAt(block, msg.agentTimestamp ?? null)
|
|
|
|
if (isSubagentToolName(c.name) && !context.consumedGroupIds.has(msg.id)) {
|
|
const sidechain = context.groups.get(msg.id) ?? null
|
|
if (sidechain && sidechain.length > 0) {
|
|
context.consumedGroupIds.add(msg.id)
|
|
const child = reduceTimeline(sidechain, context)
|
|
hasReadyEvent = hasReadyEvent || child.hasReadyEvent
|
|
block.children = child.blocks
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
|
|
if (c.type === 'tool-result') {
|
|
const title = context.titleChangesByToolUseId.get(c.tool_use_id) ?? null
|
|
if (title) {
|
|
if (!context.emittedTitleChangeToolUseIds.has(c.tool_use_id)) {
|
|
context.emittedTitleChangeToolUseIds.add(c.tool_use_id)
|
|
blocks.push({
|
|
kind: 'agent-event',
|
|
id: `${msg.id}:${idx}`,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
model: msg.model,
|
|
event: { type: 'title-changed', title },
|
|
meta: msg.meta
|
|
})
|
|
}
|
|
continue
|
|
}
|
|
|
|
const permissionEntry = context.permissionsById.get(c.tool_use_id)
|
|
const permissionFromResult = c.permissions ? ({
|
|
id: c.tool_use_id,
|
|
status: c.permissions.result === 'approved' ? 'approved' : 'denied',
|
|
date: c.permissions.date,
|
|
mode: c.permissions.mode,
|
|
allowedTools: c.permissions.allowedTools,
|
|
decision: c.permissions.decision
|
|
} satisfies ToolPermission) : undefined
|
|
|
|
const permission = (() => {
|
|
if (permissionFromResult && permissionEntry?.permission) {
|
|
return {
|
|
...permissionEntry.permission,
|
|
...permissionFromResult,
|
|
allowedTools: permissionFromResult.allowedTools ?? permissionEntry.permission.allowedTools,
|
|
decision: permissionFromResult.decision ?? permissionEntry.permission.decision
|
|
} satisfies ToolPermission
|
|
}
|
|
return permissionFromResult ?? permissionEntry?.permission
|
|
})()
|
|
|
|
const block = ensureToolBlock(blocks, toolBlocksById, c.tool_use_id, {
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
usage: msg.usage,
|
|
model: msg.model,
|
|
localId: msg.localId,
|
|
meta: msg.meta,
|
|
name: permissionEntry?.toolName ?? 'Tool',
|
|
input: permissionEntry?.input ?? null,
|
|
description: null,
|
|
permission
|
|
// NOTE: no agentTimestamp seed here. execStartedAt must
|
|
// only ever originate from a tool_use entry; the tool_use
|
|
// path backfills it via setEarliestExecStartedAt. Seeding
|
|
// it from the result entry would, on a reorder with a
|
|
// timestamp-less tool_use, leave execStartedAt ===
|
|
// execCompletedAt (the result stamp) → a bogus 0 duration
|
|
// instead of the correct hub-time fallback.
|
|
})
|
|
|
|
block.tool = {
|
|
...block.tool,
|
|
result: c.content,
|
|
completedAt: msg.createdAt,
|
|
// Only a real Claude timestamp — never the hub receive
|
|
// time — so toolDurationMs never subtracts two clocks.
|
|
// Null here leaves the tool on the hub-time fallback.
|
|
execCompletedAt: msg.agentTimestamp ?? null,
|
|
state: c.is_error ? 'error' : 'completed'
|
|
}
|
|
continue
|
|
}
|
|
|
|
if (c.type === 'sidechain') {
|
|
// Extract task-notification summaries as visible events
|
|
const trimmedPrompt = c.prompt.trimStart()
|
|
if (trimmedPrompt.startsWith('<task-notification>')) {
|
|
const summary = trimmedPrompt.match(/<summary>([\s\S]*?)<\/summary>/)?.[1]?.trim()
|
|
if (summary) {
|
|
blocks.push({
|
|
kind: 'agent-event',
|
|
id: `${msg.id}:${idx}`,
|
|
createdAt: msg.createdAt,
|
|
invokedAt: msg.invokedAt,
|
|
model: msg.model,
|
|
event: { type: 'message', message: summary },
|
|
meta: msg.meta
|
|
})
|
|
}
|
|
}
|
|
// Skip rendering prompt text (already in parent Task tool card or not user-visible)
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return { blocks: mergeCliOutputBlocks(blocks), toolBlocksById, hasReadyEvent }
|
|
}
|