import { randomUUID } from 'node:crypto' import { getEventBus } from '../transport/event-bus' import { persistSessionEvent } from './event-persistence' import { log } from '../logger' import { redispatchWorkForSession } from './work-dispatch' /** * Extract plain text from various message payload formats. * Handles: * { content: "text" } * { message: { role: "user", content: "text" } } * { message: { content: [{type:"text",text:"..."}] } } */ function extractContent(payload: unknown): string { if (!payload || typeof payload !== 'object') { return typeof payload === 'string' ? payload : '' } const p = payload as Record // Direct content field if (typeof p.content === 'string' && p.content) return p.content // message.content (child process format) const msg = p.message if (msg && typeof msg === 'object') { const mc = (msg as Record).content if (typeof mc === 'string') return mc if (Array.isArray(mc)) { return mc .filter( (b: unknown) => typeof b === 'object' && b !== null && (b as Record).type === 'text', ) .map( (b: Record) => (b as Record).text || '', ) .join('') } } return '' } /** * Normalize event payload into a flat structure with guaranteed `content` string. * Preserves original payload in `raw` field and keeps tool-specific fields. */ export function normalizePayload( type: string, payload: unknown, ): Record { if (!payload || typeof payload !== 'object') { return { content: typeof payload === 'string' ? payload : '', raw: payload } } const p = payload as Record const content = extractContent(payload) const normalized: Record = { content, raw: payload, } if (typeof p.uuid === 'string' && p.uuid) normalized.uuid = p.uuid if (typeof p.isSynthetic === 'boolean') normalized.isSynthetic = p.isSynthetic // SA-mode artifact escape hatch: the web gallery's AI dispatch tags its // user event so the worker can grant itself the artifact tool before the // turn starts. Purely a hint — ACP/legacy consumers may ignore it. if (p.artifact_dispatch === true) normalized.artifact_dispatch = true if (typeof p.status === 'string') normalized.status = p.status if (typeof p.subtype === 'string') normalized.subtype = p.subtype // Preserve tool fields if (p.tool_name) normalized.tool_name = p.tool_name if (p.name) normalized.tool_name = p.name if (p.tool_input) normalized.tool_input = p.tool_input if (p.input) normalized.tool_input = p.input // Preserve permission fields if (p.request_id) normalized.request_id = p.request_id if (p.request) normalized.request = p.request if (p.approved !== undefined) normalized.approved = p.approved if (p.updated_input) normalized.updated_input = p.updated_input // Rule updates ("always allow" / plan-approval mode switches) — without // this the field is dropped here and toClientPayload never sees it, so // updated_permissions from the web UI silently no-ops on the worker. if (p.updated_permissions) normalized.updated_permissions = p.updated_permissions // Preserve control_response body — the web UI needs subtype/request_id/error // to reconcile optimistic control requests (e.g. set_permission_mode). if (p.response) normalized.response = p.response // Preserve the mode reported by the worker's system/status message so the // web UI's permission-mode indicator stays in sync with the CLI. if (typeof p.permissionMode === 'string') normalized.permissionMode = p.permissionMode // Preserve message field for backward compat if (p.message) normalized.message = p.message if (type === 'task_state') { if (typeof p.task_list_id === 'string') normalized.task_list_id = p.task_list_id if (typeof p.taskListId === 'string') normalized.taskListId = p.taskListId if (Array.isArray(p.tasks)) normalized.tasks = p.tasks } // Rewind marker (POST /web/sessions/:id/rewind) — the truncation target // every viewer (live SSE + history replay) needs. Without this the generic // content/raw normalization hides target_event_id and the web adapter // ignores its own rewind. if (type === 'conversation_rewound') { if (typeof p.target_event_id === 'string') normalized.target_event_id = p.target_event_id if (typeof p.message_uuid === 'string') normalized.message_uuid = p.message_uuid } // Artifact lifecycle events (CLI upload / web edit) — meta-only fields // surfaced for the web UI's session artifacts badge. The HTML content is // intentionally NOT preserved: events go to every live SSE subscriber. if (type === 'artifact_created' || type === 'artifact_updated') { if (typeof p.id === 'string') normalized.id = p.id if (typeof p.title === 'string') normalized.title = p.title if (typeof p.version === 'number') normalized.version = p.version if (typeof p.url === 'string') normalized.url = p.url } // Memory lifecycle events (memdir backend / recall / dream) — meta-only // fields for the web UI's memory sidebar. File content is intentionally // NOT preserved on the wire; the sidebar fetches it on demand. if ( type === 'memory_changed' || type === 'memory_dream_started' || type === 'memory_dream_completed' || type === 'memory_recall' ) { if (typeof p.path === 'string') normalized.path = p.path if (typeof p.name === 'string') normalized.name = p.name if (typeof p.type === 'string') normalized.type = p.type if (typeof p.layer === 'string') normalized.layer = p.layer if (typeof p.scope === 'string') normalized.scope = p.scope if (typeof p.summary === 'string') normalized.summary = p.summary if (typeof p.query === 'string') normalized.query = p.query if (typeof p.sessionId === 'string') normalized.sessionId = p.sessionId if (Array.isArray(p.hits)) normalized.hits = p.hits } // Preserve result usage/cost so the web UI can render cumulative session // totals (mirrors the CLI StatusLine). `result` text + `is_error` survive // too — error-subtyped results (worker crash / timeout exit signal) must // render their reason in the Web UI, not just flip the status to idle. if (type === 'result' || type === 'result_success') { if (p.usage && typeof p.usage === 'object') normalized.usage = p.usage if (typeof p.total_cost_usd === 'number') normalized.total_cost_usd = p.total_cost_usd if (typeof p.result === 'string') normalized.result = p.result if (typeof p.is_error === 'boolean') normalized.is_error = p.is_error } // Streaming deltas — the child emits type:'stream_event' (raw Anthropic // stream event under .event) when spawned with --include-partial-messages. if (type === 'stream_event') { if (p.event && typeof p.event === 'object') normalized.event = p.event } // system/init — preserve the command/skill tables and Remote Control // capability set that the Web UI's dynamic command menu and per-worker UI // gating consume. Runs after ingestBridgeMessage's generic system branch // (which keeps these fields) and re-preserves them here so the generic // content/raw normalization above doesn't drop them. Mirrors the v2 // worker-events POST path, which passes the raw SDK message straight here. if (type === 'system' && p.subtype === 'init') { if (Array.isArray(p.slash_commands)) normalized.slash_commands = p.slash_commands if (Array.isArray(p.slash_command_details)) normalized.slash_command_details = p.slash_command_details if (Array.isArray(p.skills)) normalized.skills = p.skills if (Array.isArray(p.skill_details)) normalized.skill_details = p.skill_details if ( p.remote_capabilities && typeof p.remote_capabilities === 'object' && !Array.isArray(p.remote_capabilities) ) { normalized.remote_capabilities = p.remote_capabilities } } // SDK system events (subagent panel state). normalizePayload runs after // ingestBridgeMessage, which already spreads the full msg for these // subtypes — re-preserve the fields here so they survive the generic // content/raw normalization above. Without this, the web UI's subagent // panel would only see content='' and lose task_id/description/usage/etc. if ( type === 'system' && (p.subtype === 'task_started' || p.subtype === 'task_progress' || p.subtype === 'task_notification' || p.subtype === 'session_state_changed') ) { if (typeof p.task_id === 'string') normalized.task_id = p.task_id if (typeof p.tool_use_id === 'string') normalized.tool_use_id = p.tool_use_id if (typeof p.description === 'string') normalized.description = p.description if (p.usage && typeof p.usage === 'object') normalized.usage = p.usage if (typeof p.last_tool_name === 'string') normalized.last_tool_name = p.last_tool_name if (typeof p.summary === 'string') normalized.summary = p.summary if (Array.isArray(p.workflow_progress)) normalized.workflow_progress = p.workflow_progress if (typeof p.task_type === 'string') normalized.task_type = p.task_type if (typeof p.workflow_name === 'string') normalized.workflow_name = p.workflow_name if (typeof p.prompt === 'string') normalized.prompt = p.prompt if (typeof p.status === 'string') normalized.status = p.status if (typeof p.output_file === 'string') normalized.output_file = p.output_file if (typeof p.state === 'string') normalized.state = p.state } return normalized } /** Event types that are display-only streaming deltas — never retained in * the history window and never persisted (the final assistant message * carries the full content). */ const TRANSIENT_EVENT_TYPES = new Set(['stream_event', 'partial_assistant']) // ─── Control-request response watchdog ───────────────────────────────────── // // Web→worker control_requests (get_context_usage / interrupt / set_model / …) // are programmatic RPCs that a healthy worker answers in well under a // second (every subtype branch of handleServerControlRequest writes a // response). A pending request older than the threshold therefore means the // worker's write path is wedged — responses are queued behind a stalled // uploader and never reach the server, while its WS keeps reading (the // zombie state observed as "session stuck running, new messages get no // response"). The sweep fires the same recovery the ws-handler inactivity // close uses: a fresh work item → worker poll → brand-new transport. interface PendingControlRequest { sessionId: string subtype: string sentAt: number /** Recovery already dispatched for this wedge episode. */ recoveryFired: boolean } const pendingControlRequests = new Map() /** Web→worker control_request has 90s to be answered before recovery fires. * Generous vs. the web UI's own 8s control round-trip timeout — only a * genuinely dead write path should trip it. */ const CONTROL_RESPONSE_TIMEOUT_MS = 90_000 /** Reap unanswerable entries (worker gone mid-RPC) so the map stays bounded. */ const PENDING_REAP_MS = CONTROL_RESPONSE_TIMEOUT_MS * 4 function recordOutboundControlRequest( sessionId: string, payload: unknown, ): void { const p = payload as { request_id?: unknown request?: { subtype?: unknown } } | null if (!p || typeof p.request_id !== 'string') return pendingControlRequests.set(p.request_id, { sessionId, subtype: typeof p.request?.subtype === 'string' ? p.request.subtype : '(unknown)', sentAt: Date.now(), recoveryFired: false, }) } function settleControlResponse(payload: unknown): void { const resp = (payload as { response?: { request_id?: unknown } } | null) ?.response if (resp && typeof resp.request_id === 'string') { pendingControlRequests.delete(resp.request_id) } } /** * Sweep pending web→worker control requests. For requests unanswered past * the timeout, log the wedge and fire a recovery work re-dispatch (once * per episode — redispatchWorkForSession itself also no-ops when an open * item already exists). Called from the disconnect monitor's 60s interval. */ export function sweepUnansweredControlRequests(now = Date.now()): void { for (const [requestId, pending] of pendingControlRequests) { const ageMs = now - pending.sentAt if (ageMs <= CONTROL_RESPONSE_TIMEOUT_MS) continue if (!pending.recoveryFired) { log( `[RCS] control_request ${pending.subtype} request_id=${requestId} unanswered for ${Math.round(ageMs / 1000)}s on session=${pending.sessionId}` + ' — worker write path may be wedged, redispatching work', ) pending.recoveryFired = true void redispatchWorkForSession(pending.sessionId) } if (ageMs > PENDING_REAP_MS) { pendingControlRequests.delete(requestId) } } } /** Publish an event to a session's bus and persist it durably. */ export function publishSessionEvent( sessionId: string, type: string, payload: unknown, direction: 'inbound' | 'outbound', ) { const bus = getEventBus(sessionId) const eventId = randomUUID() // models_state is a one-shot snapshot from the worker (sent on bridge // connect, never re-sent during the worker's lifetime). Keep the latest // payload on the bus so /clear re-seeding and /history fallback can // restore the web UI's model selector even after the event log lost the // original entry. if (type === 'models_state' && payload && typeof payload === 'object') { const state = (payload as Record).models_state if (state && typeof state === 'object') { bus.modelsStateSnapshot = state as Record } } const normalized = normalizePayload(type, payload) const transient = TRANSIENT_EVENT_TYPES.has(type) // Control-response watchdog bookkeeping (see above). The raw payload is // used — normalizePayload preserves request_id/response for these types. if (direction === 'outbound' && type === 'control_request') { recordOutboundControlRequest(sessionId, payload) } else if (direction === 'inbound' && type === 'control_response') { settleControlResponse(payload) } const event = bus.publish( { id: eventId, sessionId, type, payload: normalized, direction, }, { transient }, ) if (!transient) { void persistSessionEvent(event) } return event }