{"version":3,"file":"sessionModel.mjs","names":[],"sources":["../../../src/web/lib/sessionModel.ts"],"sourcesContent":["import type { SessionLifecycle, TranscriptImageRef } from '@agimon-ai/po-core/sessionProtocol';\nimport { parsePoApprovalPrompt, type PoApprovalPrompt, type ToolResultView } from '@agimon-ai/po-core/web';\nimport { inlineProfileIcon } from '@agimon-ai/po-web-components/text';\n\nimport {\n  AGENT_MODEL_ENTRY_TYPE,\n  CONTEXT_ENTRY_TYPE,\n  type ContextProjection,\n  DIALOG_ANSWERED_TYPE,\n  MODE_ENTRY_TYPE,\n  type ModeProjection,\n  PROFILE_IDENTITY_ENTRY_TYPE,\n} from '../../types/hub';\nimport { parsePoNotificationEntry } from '../../types/notification';\nimport { BUILTIN_COMMANDS } from './commands';\nimport type { SessionSelectionAnswer } from './sessionSelectionApi';\nimport { summaryValueEqual } from './sessionSummary';\n\nexport type EntryKind = 'user' | 'assistant' | 'tool' | 'notice';\n\nexport interface UserImage {\n  /** Base64 bytes. Absent from an image a transcript sent by reference, until its saved entry is read. */\n  data?: string;\n  mimeType: string;\n  /** Where the saved entry keeps the bytes of an image sent by reference. */\n  ref?: TranscriptImageRef['ref'];\n}\n\n/** Who sent an input, as the host stamped it on the input's envelope. */\nexport interface InputSender {\n  kind: 'human' | 'agent' | 'system';\n  id?: string;\n  name: string;\n}\n\nexport interface UserEntry {\n  kind: 'user';\n  id: string;\n  text: string;\n  images?: UserImage[];\n  /** Present only when the host recorded who sent it; a typed prompt here has none. */\n  sender?: InputSender;\n  /** A steer the server holds in its inbox; its journal entry replaces it once the agent places it. */\n  pending?: true;\n}\n\nexport interface AssistantEntry {\n  kind: 'assistant';\n  id: string;\n  text: string;\n  thinking: string;\n  streaming: boolean;\n  /** Provider model, used with the message timestamp to reconcile repeated starts. */\n  model?: string;\n  /**\n   * The persona active when this message was written.\n   *\n   * Stamped at creation rather than read from current state, so a profile\n   * switch leaves earlier messages showing who actually wrote them. Replay\n   * reproduces it because the identity entry is folded in journal order.\n   */\n  identity?: ProfileIdentity;\n}\n\n/** Display name and avatar of the persona a message was written under. */\nexport interface ProfileIdentity {\n  profile: string;\n  name?: string;\n  icon?: string;\n}\n\nexport interface ToolEntry {\n  kind: 'tool';\n  id: string;\n  toolCallId: string;\n  name: string;\n  /** The call arguments as the frame carried them, for a plugin's own renderer. */\n  args: Record<string, unknown>;\n  argSummary: string;\n  /** The newest result, partial while running; null before the tool produced any. */\n  result: ToolResultView | null;\n  output: string;\n  isError: boolean;\n  running: boolean;\n}\n\nexport interface NoticeEntry {\n  kind: 'notice';\n  id: string;\n  text: string;\n  tone: 'info' | 'error';\n}\n\n/** A message another agent sent this session over the team intercom, named for a person to read. */\nexport interface IntercomEntry {\n  kind: 'intercom';\n  id: string;\n  /** `send` is a plain message; `ask` wants an answer; `reply` and `no_reply` close an earlier ask. */\n  intent: 'send' | 'ask' | 'reply' | 'no_reply';\n  /** The sender's first name when it has an identity (`faris-c-6` is Faris), else its member name. */\n  name: string;\n  /** The seed that keeps the sender's avatar colour fixed. */\n  seed: string;\n  /** The agent definition behind a named sender, empty when the name already is it. */\n  role: string;\n  text: string;\n}\n\nexport interface SettledEntry {\n  kind: 'settled';\n  id: string;\n  tools: number;\n  /** Canonical journal members verified by the runtime, absent in legacy history. */\n  entryIds?: readonly string[];\n}\n\nexport interface QueuedEntry {\n  kind: 'queued';\n  id: string;\n  text: string;\n  delivery?: 'steer' | 'followUp' | 'nextRun';\n  scheduling?: 'automatic' | 'held';\n  disposition?: 'pending' | 'handoff';\n  images?: UserImage[];\n}\n\nexport type TimelineEntry = (\n  | UserEntry\n  | AssistantEntry\n  | ToolEntry\n  | NoticeEntry\n  | IntercomEntry\n  | SettledEntry\n  | QueuedEntry\n) & {\n  timestamp?: number;\n  /** Runtime-verified agent run, never inferred from transcript position. */\n  turnId?: string;\n  /** Canonical journal identity, retained when a local or tool card id differs. */\n  sourceEntryId?: string;\n  /** Other canonical records represented by this card, such as its tool result. */\n  sourceEntryIds?: readonly string[];\n};\n\nexport interface SessionStats {\n  cost: number;\n  totalTokens: number;\n  contextPercent: number | null;\n  contextTokens: number | null;\n  contextWindow: number | null;\n}\n\nexport interface AgentInfo {\n  model: string;\n  /** The provider Pi resolved the model under; set_model needs both halves. */\n  provider: string;\n  thinkingLevel: string;\n  sessionId: string;\n  sessionName: string;\n  messageCount: number;\n  isStreaming: boolean;\n}\n\nexport interface CommandInfo {\n  name: string;\n  description: string;\n  source?: string;\n}\n\n/** One model the session can switch to, as get_available_models lists it. */\nexport interface ModelChoice {\n  provider: string;\n  id: string;\n  name: string;\n  reasoning: boolean;\n}\n\nexport type DialogMethod = 'select' | 'confirm' | 'input' | 'editor';\n\nexport interface DialogRequest {\n  id: string;\n  method: DialogMethod;\n  title: string;\n  message: string;\n  options: string[];\n  /** A second line per option, parallel to `options`, when the request supplies any. */\n  descriptions?: string[];\n  /** An image `data:` URL per option, parallel to `options`; empty where an option has none. */\n  icons?: string[];\n  placeholder: string;\n  prefill: string;\n  approval?: PoApprovalPrompt;\n}\n\nexport interface EditorTextRequest {\n  append?: boolean;\n  id: string;\n  text: string;\n}\n\nexport interface SessionState {\n  entries: TimelineEntry[];\n  hasNewerHistory: boolean;\n  /** Running tool frames kept outside the protocol-owned transcript so prompt plugins can claim their dialogs. */\n  activeTools: ToolEntry[];\n  /**\n   * Footer status entries keyed as the publishing extension named them, raw so\n   * the colour survives. A key that is absent means the package is not in this\n   * composition; a key holding an empty string means it is loaded but off.\n   */\n  statuses: Record<string, string>;\n  /** Widget keys the session has announced, the only signal some modes give. */\n  widgets: string[];\n  streaming: boolean;\n  settled: boolean;\n  /** Latest authoritative server execution and retained-input snapshot. */\n  lifecycle: SessionLifecycle | null;\n  stats: SessionStats | null;\n  /**\n   * Cost the assistant message now streaming has run up, on top of `stats`.\n   *\n   * Pi answers `get_session_stats` once per message at best, so without this\n   * the cost chip sits still for the length of a turn. Zero whenever no\n   * message is streaming or the provider has not reported yet.\n   */\n  liveCost: number;\n  agent: AgentInfo | null;\n  commands: CommandInfo[];\n  /** Models the session offered, empty until the picker asks. */\n  models: ModelChoice[];\n  /** Thinking levels the current model accepts, empty until the picker asks. */\n  fastMode: boolean;\n  /** True while the session's local agent is blocked from starting turns. */\n  agentLocked: boolean;\n  thinkingLevels: string[];\n  dialog: DialogRequest | null;\n  /** Latest fire-and-forget editor replacement requested by a session extension. */\n  editorTextRequest: EditorTextRequest | null;\n  /** The runtime's mode catalog as last journaled, or null before it reports. */\n  modes: ModeProjection | null;\n  /** What the session is composed of, as last journaled, or null before it reports. */\n  context: ContextProjection | null;\n  /**\n   * The persona most recently journaled, used to stamp assistant messages as\n   * they are created. Not a projection: folding it forward in journal order is\n   * what keeps a pre-switch message attributed to the persona that wrote it.\n   */\n  profileIdentity: ProfileIdentity | null;\n  /** Tool calls seen since the current run began, reported when it settles. */\n  toolsThisRun: number;\n  /**\n   * Journal entry ids already folded into the timeline. The hub re-reads the\n   * journal on every attach, so a reconnect replays entries this page already\n   * has; folding by id is what keeps a restored transcript from doubling.\n   */\n  restoredIds: string[];\n  /**\n   * Prompts this page put on screen before the journal recorded them, newest\n   * last. The cockpit shows your message the moment you send it, but the\n   * journal is what carries every message, including the ones an extension\n   * sends on your behalf. Matching a journal message against this list is what\n   * lets both appear exactly once.\n   */\n  pendingUserEntries: { id: string; text: string; images?: UserImage[] }[];\n  /**\n   * Prompts an authoritative transcript already folded into the entry this page\n   * rendered, newest last.\n   *\n   * A prompt reaches the timeline from two directions, Pi's protocol snapshot\n   * and the session journal, and whichever lands first consumes the pending\n   * record. Without this the second arrival has nothing to match and appends a\n   * second copy of the message, which is what a reader sees when transcript\n   * ownership returns to the journal mid-session.\n   */\n  reconciledUserEntries: { id: string; text: string; images?: UserImage[] }[];\n  /** Stable local ids for optimistic prompts after Pi publishes their canonical transcript entries. */\n  protocolUserEntryIds: Record<string, string>;\n  /** Verified journal ownership retained even when its protocol item has not arrived yet. */\n  transcriptTurnIds: Record<string, string>;\n  nextId: number;\n  /** In-flight steers from the server lifecycle, newest last, ids `steer:<submission id>`. */\n  pendingSteers: readonly UserEntry[];\n  /** Submission ids whose journal entry already landed, so an older lifecycle frame cannot bring them back. */\n  placedSteers: readonly string[];\n}\n\nexport const initialSessionState: SessionState = {\n  hasNewerHistory: false,\n  entries: [],\n  activeTools: [],\n  statuses: {},\n  widgets: [],\n  streaming: false,\n  settled: false,\n  lifecycle: null,\n  stats: null,\n  liveCost: 0,\n  agent: null,\n  commands: [],\n  models: [],\n  fastMode: false,\n  agentLocked: false,\n  thinkingLevels: [],\n  dialog: null,\n  editorTextRequest: null,\n  modes: null,\n  context: null,\n  profileIdentity: null,\n  toolsThisRun: 0,\n  restoredIds: [],\n  pendingUserEntries: [],\n  reconciledUserEntries: [],\n  protocolUserEntryIds: {},\n  transcriptTurnIds: {},\n  nextId: 1,\n  pendingSteers: [],\n  placedSteers: [],\n};\n\ntype Frame = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Frame {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction asString(value: unknown, fallback = ''): string {\n  return typeof value === 'string' ? value : fallback;\n}\n\nfunction asNumber(value: unknown): number | null {\n  return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\n/** Joins the text blocks of a Pi content array, ignoring non-text parts. */\nexport function textFromContent(content: unknown): string {\n  if (typeof content === 'string') return content;\n  if (!Array.isArray(content)) return '';\n  return content\n    .map((block) => (isRecord(block) && block.type === 'text' ? asString(block.text) : ''))\n    .filter(Boolean)\n    .join('');\n}\n\nconst SUPPORTED_IMAGE_MIME_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);\n\nexport function isSupportedImageMimeType(mimeType: string): boolean {\n  return SUPPORTED_IMAGE_MIME_TYPES.has(mimeType);\n}\n\n/** Keeps only image blocks the cockpit can safely render as data URLs, inline or sent by reference. */\nexport function imagesFromContent(content: unknown): UserImage[] {\n  if (!Array.isArray(content)) return [];\n  return content.flatMap((block): UserImage[] => {\n    if (!isRecord(block) || block.type !== 'image') return [];\n    const data = asString(block.data);\n    const mimeType = asString(block.mimeType);\n    if (!isSupportedImageMimeType(mimeType)) return [];\n    if (data) return [{ data, mimeType }];\n    const ref = isRecord(block.ref) ? block.ref : undefined;\n    return typeof ref?.entryId === 'string' && typeof ref.part === 'number'\n      ? [{ mimeType, ref: { entryId: ref.entryId, part: ref.part } }]\n      : [];\n  });\n}\n\n/** A one-line description of a tool call, good enough for a card header. */\nexport function summariseArgs(args: unknown): string {\n  if (!isRecord(args)) return '';\n  for (const key of ['command', 'file_path', 'filePath', 'path', 'pattern', 'query', 'url']) {\n    const value = args[key];\n    if (typeof value === 'string' && value.length > 0) return value;\n    // A command sequence, such as the bash tool's array of steps.\n    if (Array.isArray(value) && value.length > 0 && value.every((step) => typeof step === 'string'))\n      return value.join(' && ');\n  }\n  const keys = Object.keys(args);\n  return keys.length > 0 ? keys.join(', ') : '';\n}\n\nfunction withEntry(state: SessionState, entry: TimelineEntry): SessionState {\n  return { ...state, entries: [...state.entries, entry], nextId: state.nextId + 1 };\n}\n\nfunction withChronologicalEntry(state: SessionState, entry: TimelineEntry): SessionState {\n  const timestamp = entry.timestamp;\n  if (timestamp === undefined) return withEntry(state, entry);\n  const index = state.entries.findIndex(\n    (existing) => existing.timestamp !== undefined && existing.timestamp > timestamp,\n  );\n  if (index === -1) return withEntry(state, entry);\n  return {\n    ...state,\n    entries: [...state.entries.slice(0, index), entry, ...state.entries.slice(index)],\n    nextId: state.nextId + 1,\n  };\n}\n\nfunction replaceEntry(state: SessionState, id: string, next: TimelineEntry): SessionState {\n  return { ...state, entries: state.entries.map((entry) => (entry.id === id ? next : entry)) };\n}\n\nfunction openAssistant(state: SessionState): { state: SessionState; entry: AssistantEntry } {\n  const last = state.entries[state.entries.length - 1];\n  if (last && last.kind === 'assistant' && last.streaming) return { state, entry: last };\n  const entry: AssistantEntry = {\n    kind: 'assistant',\n    id: `a${state.nextId}`,\n    text: '',\n    thinking: '',\n    streaming: true,\n    ...(state.profileIdentity === null ? {} : { identity: state.profileIdentity }),\n  };\n  return { state: withEntry(state, entry), entry };\n}\n\nfunction applyAssistantDelta(state: SessionState, event: Frame): SessionState {\n  const type = asString(event.type);\n  if (type !== 'text_delta' && type !== 'thinking_delta' && type !== 'text_start' && type !== 'thinking_start') {\n    return state;\n  }\n  const opened = openAssistant(state);\n  const delta = asString(event.delta);\n  if (!delta) return opened.state;\n  const next: AssistantEntry =\n    type === 'thinking_delta'\n      ? { ...opened.entry, thinking: opened.entry.thinking + delta }\n      : { ...opened.entry, text: opened.entry.text + delta };\n  return replaceEntry(opened.state, opened.entry.id, next);\n}\n\n/** Provider error payloads can include credentials, so only render a fixed failure explanation. */\nexport function assistantFailureText(message: unknown): string {\n  return isRecord(message) && (message.stopReason === 'error' || message.status === 'error')\n    ? 'The model could not complete this response. Check the provider connection and try again.'\n    : '';\n}\n\nfunction closeAssistant(state: SessionState, message: unknown): SessionState {\n  const index = state.entries.findLastIndex((entry) => entry.kind === 'assistant' && entry.streaming);\n  if (index === -1) return state;\n  const current = state.entries[index] as AssistantEntry;\n  const content = isRecord(message) ? message.content : undefined;\n  const hasContent = typeof content === 'string' || Array.isArray(content);\n  const next: AssistantEntry = {\n    ...current,\n    ...(isRecord(message) && asNumber(message.timestamp) !== null ? { timestamp: asNumber(message.timestamp)! } : {}),\n    ...(isRecord(message) && typeof message.model === 'string' ? { model: message.model } : {}),\n    text: [hasContent ? textFromContent(content) : current.text, assistantFailureText(message)]\n      .filter(Boolean)\n      .join('\\n\\n'),\n    thinking: hasContent\n      ? thinkingFromContent(Array.isArray(content) ? content.filter(isRecord) : [])\n      : current.thinking,\n    streaming: false,\n  };\n  const entries = [...state.entries];\n  if (next.text || next.thinking) entries[index] = next;\n  else entries.splice(index, 1);\n  return { ...state, entries };\n}\n\nfunction toolEntryFromStart(frame: Frame, id: string): ToolEntry {\n  return {\n    kind: 'tool',\n    id,\n    toolCallId: asString(frame.toolCallId),\n    name: asString(frame.toolName, 'tool'),\n    args: isRecord(frame.args) ? frame.args : {},\n    argSummary: summariseArgs(frame.args),\n    result: null,\n    output: '',\n    isError: false,\n    running: true,\n  };\n}\n\nfunction applyToolStart(state: SessionState, frame: Frame): SessionState {\n  const closed = closeAssistant(state, undefined);\n  const toolCallId = asString(frame.toolCallId);\n  if (toolCallId !== '' && closed.entries.some((entry) => entry.kind === 'tool' && entry.toolCallId === toolCallId)) {\n    return { ...closed, toolsThisRun: closed.toolsThisRun + 1 };\n  }\n  const opened = withEntry(closed, toolEntryFromStart(frame, `t${state.nextId}`));\n  return { ...opened, toolsThisRun: opened.toolsThisRun + 1 };\n}\n\n/**\n * The result a tool frame carries, kept whole: the text blocks feed the\n * default card, and the content plus details reach the owning plugin's\n * renderer untouched, the way Pi hands them to a TUI renderResult.\n */\nfunction toolResult(raw: unknown): ToolResultView | null {\n  if (!isRecord(raw)) return null;\n  return { content: Array.isArray(raw.content) ? raw.content : [], details: raw.details };\n}\n\nfunction updateTool(state: SessionState, toolCallId: string, patch: Partial<ToolEntry>): SessionState {\n  const index = state.entries.findLastIndex((entry) => entry.kind === 'tool' && entry.toolCallId === toolCallId);\n  if (index === -1) return state;\n  const entries = [...state.entries];\n  entries[index] = { ...(entries[index] as ToolEntry), ...patch };\n  return { ...state, entries };\n}\n\nfunction modelChoice(value: unknown): ModelChoice | undefined {\n  if (!isRecord(value) || typeof value.id !== 'string' || typeof value.provider !== 'string') return undefined;\n  return {\n    provider: value.provider,\n    id: value.id,\n    name: asString(value.name, value.id),\n    reasoning: value.reasoning === true,\n  };\n}\n\nfunction applyResponse(state: SessionState, frame: Frame): SessionState {\n  const command = asString(frame.command);\n  if (frame.success === false && command !== 'get_state' && command !== 'get_session_stats') {\n    return withEntry(state, {\n      kind: 'notice',\n      id: `n${state.nextId}`,\n      text: asString(frame.error, `The agent refused ${command}.`),\n      tone: 'error',\n    });\n  }\n  const data = frame.data;\n  if (!isRecord(data)) return state;\n\n  if (command === 'get_state') {\n    const model = isRecord(data.model) ? asString(data.model.id ?? data.model.name, 'unknown') : 'unknown';\n    const provider = isRecord(data.model) ? asString(data.model.provider) : '';\n    // get_state is a separate RPC and can arrive after a newer replicated lifecycle snapshot.\n    const streaming =\n      state.lifecycle !== null\n        ? state.lifecycle.operation !== null\n        : data.isStreaming === undefined\n          ? state.streaming\n          : data.isStreaming === true;\n    return {\n      ...state,\n      streaming,\n      settled: !streaming,\n      fastMode: data.fastMode === true,\n      agentLocked: data.agentLocked === true,\n      agent: {\n        model,\n        provider,\n        thinkingLevel: asString(data.thinkingLevel, state.agent?.thinkingLevel ?? 'unknown'),\n        sessionId: asString(data.sessionId, state.agent?.sessionId ?? ''),\n        sessionName: asString(data.sessionName, state.agent?.sessionName ?? ''),\n        messageCount: asNumber(data.messageCount) ?? state.agent?.messageCount ?? 0,\n        isStreaming: streaming,\n      },\n    };\n  }\n\n  if (command === 'navigate_tree' && data.cancelled !== true) {\n    const editorText = asString(data.editorText);\n    return {\n      ...state,\n      editorTextRequest: {\n        id: `rewind:${asString(data.leafId, 'root')}:${String(state.nextId)}`,\n        text: editorText,\n      },\n    };\n  }\n\n  if (command === 'get_available_models') {\n    const models = Array.isArray(data.models) ? data.models.map(modelChoice).filter((m) => m !== undefined) : [];\n    return { ...state, models };\n  }\n\n  if (command === 'get_available_thinking_levels') {\n    const levels = Array.isArray(data.levels) ? data.levels.filter((level) => typeof level === 'string') : [];\n    return { ...state, thinkingLevels: levels };\n  }\n\n  // Pi echoes the model it switched to; get_state follows for the rest.\n  if (command === 'set_model' && state.agent) {\n    const chosen = modelChoice(data);\n    return chosen ? { ...state, agent: { ...state.agent, model: chosen.id, provider: chosen.provider } } : state;\n  }\n\n  if (command === 'get_session_stats') {\n    const tokens = isRecord(data.tokens) ? asNumber(data.tokens.total) : null;\n    const usage = isRecord(data.contextUsage) ? data.contextUsage : undefined;\n    return {\n      ...state,\n      stats: {\n        cost: asNumber(data.cost) ?? 0,\n        totalTokens: tokens ?? 0,\n        contextPercent: usage ? asNumber(usage.percent) : null,\n        contextTokens: usage ? asNumber(usage.tokens) : null,\n        contextWindow: usage ? asNumber(usage.contextWindow) : null,\n      },\n      // This answer already counts the message the delta was tracking, so\n      // keeping the delta would bill it twice. Clearing it here rather than at\n      // `message_end` is what stops the chip dipping while the answer is in\n      // flight.\n      liveCost: 0,\n    };\n  }\n\n  if (command === 'get_commands') {\n    const raw = Array.isArray(data.commands) ? data.commands : [];\n    const reported = raw\n      .filter(isRecord)\n      .map((entry) => ({\n        name: asString(entry.name),\n        description: asString(entry.description),\n        ...(typeof entry.source === 'string' ? { source: entry.source } : {}),\n      }))\n      .filter((entry) => entry.name.length > 0);\n    // Pi does not report its own built-ins here, so the cockpit adds the ones\n    // it can run. An extension that claims the same name keeps it: that one\n    // reaches the session through the prompt path and is what the user gets.\n    const claimed = new Set(reported.map((entry) => entry.name));\n    const commands = [...reported, ...BUILTIN_COMMANDS.filter((entry) => !claimed.has(entry.name))];\n    return { ...state, commands };\n  }\n\n  return state;\n}\n\n/**\n * Folds the streaming message's own cost into the view model.\n *\n * Pi builds `message_update.usage` from the in-progress message's usage, not\n * from a session running total, so this is added to the last figure Pi\n * reported rather than replacing it. Providers that only price a message once\n * it completes report zero here, and the chip then steps at each message\n * instead of streaming, which is the provider's granularity showing through\n * rather than a fault.\n */\nfunction applyLiveUsage(state: SessionState, frame: Frame): SessionState {\n  if (asString(frame.type) !== 'message_update') return state;\n  const usage = isRecord(frame.usage) ? frame.usage : undefined;\n  const cost = usage && isRecord(usage.cost) ? (asNumber(usage.cost.total) ?? 0) : 0;\n  if (state.liveCost === cost) return state;\n  return { ...state, liveCost: cost };\n}\n\nfunction applyStatus(state: SessionState, frame: Frame): SessionState {\n  const key = asString(frame.statusKey);\n  if (!key) return state;\n  const text = typeof frame.statusText === 'string' ? frame.statusText : '';\n  if (state.statuses[key] === text) return state;\n  return { ...state, statuses: { ...state.statuses, [key]: text } };\n}\n\nexport function selectionStatuses(selection: {\n  preset: string;\n  domains: string[];\n  profile?: string | null;\n}): Record<string, string> {\n  const profile = typeof selection.profile === 'string' ? selection.profile : '';\n  return {\n    'po-preset': [profile ? `*${profile}*` : undefined, `[${selection.preset}]`, selection.domains.join(',')]\n      .filter(Boolean)\n      .join(':'),\n    'po-domain': selection.domains.join(','),\n    'po-profile': profile,\n  };\n}\n\nexport function applySelectionAnswer(state: SessionState, answer: SessionSelectionAnswer): SessionState {\n  const next = {\n    ...state,\n    ...(answer.context === undefined ? {} : { context: answer.context }),\n    ...(answer.modes === undefined ? {} : { modes: answer.modes }),\n    ...(answer.preset && answer.domains && answer.profile\n      ? {\n          statuses: {\n            ...state.statuses,\n            ...selectionStatuses({\n              preset: answer.preset.preset,\n              domains: answer.domains.domains,\n              profile: answer.profile.profile,\n            }),\n          },\n        }\n      : {}),\n  };\n  return summaryValueEqual(state.context, next.context) &&\n    summaryValueEqual(state.modes, next.modes) &&\n    summaryValueEqual(state.statuses, next.statuses)\n    ? state\n    : next;\n}\n\nfunction applyContextSelection(state: SessionState, projection: ContextProjection): SessionState {\n  const selection = projection.selection;\n  const next = {\n    ...state,\n    context: projection,\n    ...(selection?.preset && Array.isArray(selection.domains)\n      ? { statuses: { ...state.statuses, ...selectionStatuses(selection) } }\n      : {}),\n  };\n  return summaryValueEqual(state.context, next.context) &&\n    summaryValueEqual(state.modes, next.modes) &&\n    summaryValueEqual(state.statuses, next.statuses)\n    ? state\n    : next;\n}\n\nfunction applyWidget(state: SessionState, frame: Frame): SessionState {\n  const key = asString(frame.widgetKey);\n  if (!key) return state;\n  const present = Array.isArray(frame.widgetLines) && frame.widgetLines.length > 0;\n  if (!present) {\n    if (!state.widgets.includes(key)) return state;\n    return { ...state, widgets: state.widgets.filter((widget) => widget !== key) };\n  }\n  if (state.widgets.includes(key)) return state;\n  return { ...state, widgets: [...state.widgets, key] };\n}\n\nfunction applyDialog(state: SessionState, frame: Frame): SessionState {\n  const method = asString(frame.method);\n  if (method === 'setStatus') return applyStatus(state, frame);\n  if (method === 'setWidget') return applyWidget(state, frame);\n  if (method === 'append_composer_text') {\n    if (typeof frame.text !== 'string') return state;\n    return { ...state, editorTextRequest: { id: asString(frame.id), text: frame.text, append: true } };\n  }\n  if (method === 'set_editor_text') {\n    if (typeof frame.text !== 'string') return state;\n    return { ...state, editorTextRequest: { id: asString(frame.id), text: frame.text } };\n  }\n  if (method !== 'select' && method !== 'confirm' && method !== 'input' && method !== 'editor') return state;\n  const rawOptions = Array.isArray(frame.options) ? frame.options.map((option) => asString(option)) : [];\n  const rawDescriptions = Array.isArray(frame.descriptions) ? frame.descriptions : [];\n  const kept = rawOptions.flatMap((option, index) => (option ? [index] : []));\n  const options = kept.map((index) => rawOptions[index] ?? '');\n  const descriptions = kept.map((index) => asString(rawDescriptions[index]));\n  const rawIcons = Array.isArray(frame.icons) ? frame.icons : [];\n  const icons = kept.map((index) => inlineProfileIcon(rawIcons[index]) ?? '');\n  const approval = method === 'select' ? parsePoApprovalPrompt(frame.approval) : undefined;\n  return {\n    ...state,\n    dialog: {\n      id: asString(frame.id),\n      method,\n      title: asString(frame.title, 'The agent needs an answer'),\n      message: asString(frame.message),\n      options,\n      ...(descriptions.some(Boolean) ? { descriptions } : {}),\n      ...(icons.some(Boolean) ? { icons } : {}),\n      placeholder: asString(frame.placeholder),\n      prefill: asString(frame.prefill),\n      ...(approval === undefined ? {} : { approval }),\n    },\n  };\n}\n\n/** The thinking blocks of a journalled assistant message, joined as one passage. */\nfunction thinkingFromContent(content: readonly Frame[]): string {\n  return content\n    .map((block) => (block.type === 'thinking' ? asString(block.thinking) : ''))\n    .filter(Boolean)\n    .join('');\n}\n\n/** Remembers a prompt this page rendered, so the journal's copy of it folds into the same entry. */\nfunction withPendingUser(state: SessionState, id: string, text: string, images: UserImage[] = []): SessionState {\n  const pending = { id, text, ...(images.length > 0 ? { images } : {}) };\n  return { ...state, pendingUserEntries: [...state.pendingUserEntries, pending] };\n}\n\n/**\n * Folds a journalled user message into the entry this page already rendered\n * for it, or returns undefined when no such entry exists.\n *\n * A message the cockpit sent is on screen before it reaches the journal, and a\n * queued one is on screen as queued until the run picks it up. Both are the\n * same message the journal later reports, so it settles the entry that stands\n * rather than adding a second copy of the text.\n *\n * A prompt Pi's protocol snapshot already claimed is matched here too. That\n * claim consumed the pending record, so without the second list a journalled\n * copy arriving after the run, which is what happens when transcript\n * ownership falls back to the journal, would read as a new message and be\n * appended below the settled divider.\n */\nfunction reconcilePendingUser(state: SessionState, text: string, images: UserImage[]): SessionState | undefined {\n  const index = state.pendingUserEntries.findIndex((pending) => pending.text === text);\n  const reconciledIndex = index === -1 ? state.reconciledUserEntries.findIndex((claimed) => claimed.text === text) : -1;\n  if (index === -1 && reconciledIndex === -1) return undefined;\n  const source = index === -1 ? state.reconciledUserEntries : state.pendingUserEntries;\n  const at = index === -1 ? reconciledIndex : index;\n  const pending = source[at] as { id: string; images?: UserImage[] };\n  // A pending prompt is claimed once, because a second copy of the same text is\n  // a second message. A claim already published is kept: the hub re-reads the\n  // journal at every run boundary, and each of those copies has to fold into the\n  // entry that stands rather than becoming a new one.\n  const remaining = index === -1 ? state.reconciledUserEntries : source.filter((_, position) => position !== at);\n  const entries = state.entries.map((entry) => {\n    if (entry.id !== pending.id) return entry;\n    const reconciledImages = images.length > 0 ? images : pending.images;\n    if (entry.kind === 'queued') {\n      return {\n        kind: 'user' as const,\n        id: entry.id,\n        text: entry.text,\n        ...(reconciledImages ? { images: reconciledImages } : {}),\n      };\n    }\n    return entry.kind === 'user' && images.length > 0 ? { ...entry, images } : entry;\n  });\n  return index === -1\n    ? { ...state, entries, reconciledUserEntries: remaining }\n    : { ...state, entries, pendingUserEntries: remaining };\n}\n\n/** po-core's `PO_CHILD_INPUT_CUSTOM_TYPE`: a custom message whose details carry `{ sender }`. */\nconst ATTRIBUTED_INPUT_TYPE = 'po-input';\nconst INPUT_SENDER_KINDS: ReadonlySet<string> = new Set(['human', 'agent', 'system']);\n\n/** po-team's `TEAM_MESSAGE_CUSTOM_TYPE`; its details carry `{ kind, from, message }`. */\nconst INTERCOM_MESSAGE_TYPE = 'intercom_message';\nconst INTERCOM_INTENTS: ReadonlySet<string> = new Set(['send', 'ask', 'reply', 'no_reply']);\n\n/** `faris-c-6` is Faris with `po-developer` as its role; a member without an agent keeps its own name. */\nfunction intercomSender(details: unknown): Pick<IntercomEntry, 'name' | 'seed' | 'role'> | undefined {\n  const from = isRecord(details) && isRecord(details.from) ? details.from : undefined;\n  const member = from ? asString(from.name).trim() : '';\n  if (!from || !member) return undefined;\n  const agent = asString(from.agent).trim();\n  const first = member.split('-')[0] ?? '';\n  if (!agent || agent === member || !first) return { name: member, seed: member, role: '' };\n  return { name: first.charAt(0).toUpperCase() + first.slice(1), seed: member, role: agent };\n}\n\n/** The journal is data, not a contract this page trusts: a sender counts only in its exact recorded shape. */\nfunction inputSender(details: unknown): InputSender | undefined {\n  const sender = isRecord(details) ? details.sender : undefined;\n  if (!isRecord(sender) || !INPUT_SENDER_KINDS.has(asString(sender.kind))) return undefined;\n  const name = asString(sender.name).trim();\n  if (!name) return undefined;\n  return {\n    kind: sender.kind as InputSender['kind'],\n    name,\n    ...(typeof sender.id === 'string' && sender.id ? { id: sender.id } : {}),\n  };\n}\n/**\n * Folds one journalled message into the timeline.\n *\n * The journal is the session's own record, so its shape is not the live frame\n * shape: a tool call is a block inside an assistant message (`id`,\n * `arguments`) rather than a tool_execution_start frame, and its result is a\n * message of its own. Mapping them here is what lets a transcript written\n * before this page existed read exactly like one it watched arrive.\n */\nfunction applyJournalMessage(state: SessionState, message: Frame, entryId?: string, timestamp?: number): SessionState {\n  const role = asString(message.role);\n  const content =\n    typeof message.content === 'string'\n      ? [{ type: 'text', text: message.content }]\n      : Array.isArray(message.content)\n        ? message.content.filter(isRecord)\n        : [];\n\n  // A host input whose sender was recorded: the model read it as a user turn, so it is one here too.\n  if (role === 'custom' && message.customType === ATTRIBUTED_INPUT_TYPE) {\n    const text = textFromContent(content);\n    const images = imagesFromContent(content);\n    if (!text && images.length === 0) return state;\n    const sender = inputSender(message.details);\n    return withEntry(state, {\n      kind: 'user',\n      id: entryId ?? `u${state.nextId}`,\n      text,\n      ...(timestamp === undefined ? {} : { timestamp }),\n      ...(sender ? { sender } : {}),\n      ...(images.length > 0 ? { images } : {}),\n    });\n  }\n\n  // Another agent speaking over the team intercom: shown as that agent's message, not as the person's turn.\n  if (role === 'custom' && message.customType === INTERCOM_MESSAGE_TYPE) {\n    const sender = intercomSender(message.details);\n    const details = isRecord(message.details) ? message.details : {};\n    const intent = asString(details.kind);\n    const text = asString(details.message).trim();\n    if (!sender || !INTERCOM_INTENTS.has(intent) || !text) return state;\n    return withEntry(state, {\n      kind: 'intercom',\n      id: entryId ?? `i${state.nextId}`,\n      intent: intent as IntercomEntry['intent'],\n      ...sender,\n      text,\n      ...(timestamp === undefined ? {} : { timestamp }),\n    });\n  }\n\n  // Detached exec returns just a job ID. Show its pictures at completion, even if the launch is on an older page.\n  if (role === 'custom' && message.customType === 'po-codemode-finished' && message.display === true && entryId) {\n    const details = isRecord(message.details) ? message.details : undefined;\n    const result = toolResult(details?.result);\n    if (\n      result?.content.some(\n        (block) =>\n          isRecord(block) &&\n          block.type === 'image' &&\n          isSupportedImageMimeType(asString(block.mimeType)) &&\n          (asString(block.data) !== '' || (isRecord(block.ref) && typeof block.ref.entryId === 'string')),\n      )\n    ) {\n      return withEntry(state, {\n        ...toolEntryFromStart({ toolCallId: `background-exec:${entryId}`, toolName: 'exec' }, entryId),\n        ...(timestamp === undefined ? {} : { timestamp }),\n        // The same images are also recorded in nested calls. Draw the emitted output once.\n        result: { content: result.content, details: null },\n        output: textFromContent(result.content),\n        isError: details?.status !== 'completed',\n        running: false,\n      });\n    }\n  }\n  // A host event the model reads as input but the person did not write, such as a\n  // background runner's exit. Only a message that names its own one-line notice\n  // is shown; other custom messages stay the model's alone.\n  if (role === 'custom' && isRecord(message.details) && typeof message.details.notice === 'string') {\n    const text = message.details.notice.trim();\n    if (!text) return state;\n    return withEntry(state, {\n      kind: 'notice',\n      id: entryId ?? `n${state.nextId}`,\n      text,\n      tone: 'info',\n      ...(timestamp === undefined ? {} : { timestamp }),\n    });\n  }\n  if (role === 'user') {\n    const text = textFromContent(content);\n    const images = imagesFromContent(content);\n    if (!text && images.length === 0) return state;\n    return (\n      reconcilePendingUser(state, text, images) ??\n      withEntry(state, {\n        kind: 'user',\n        id: entryId ?? `u${state.nextId}`,\n        text,\n        ...(timestamp === undefined ? {} : { timestamp }),\n        ...(images.length > 0 ? { images } : {}),\n      })\n    );\n  }\n\n  if (role === 'assistant') {\n    timestamp ??= asNumber(message.timestamp) ?? undefined;\n    const model = typeof message.model === 'string' ? message.model : undefined;\n    const text = [textFromContent(content), assistantFailureText(message)].filter(Boolean).join('\\n\\n');\n    const thinking = thinkingFromContent(content);\n    const completedFailure =\n      assistantFailureText(message) && timestamp !== undefined\n        ? state.entries.findLast(\n            (item) =>\n              item.kind === 'assistant' &&\n              !item.streaming &&\n              item.timestamp === timestamp &&\n              item.model === model &&\n              item.text === text,\n          )\n        : undefined;\n    if (completedFailure && entryId)\n      return {\n        ...state,\n        entries: state.entries.map((item) => (item.id === completedFailure.id ? { ...item, id: entryId } : item)),\n      };\n    const draft = state.entries.findLast((item) => item.kind === 'assistant' && item.streaming);\n    if (draft && entryId && !state.entries.some((item) => item.id === entryId)) {\n      state = closeAssistant(state, message);\n      state = {\n        ...state,\n        entries: state.entries.map((item) =>\n          item.id === draft.id\n            ? {\n                ...item,\n                id: entryId,\n                ...(timestamp === undefined ? {} : { timestamp }),\n                ...(model === undefined ? {} : { model }),\n              }\n            : item,\n        ),\n      };\n    }\n    let next =\n      (text || thinking) && !state.entries.some((item) => item.id === entryId)\n        ? withEntry(state, {\n            kind: 'assistant',\n            id: entryId ?? `a${state.nextId}`,\n            ...(timestamp === undefined ? {} : { timestamp }),\n            ...(model === undefined ? {} : { model }),\n            text,\n            thinking,\n            streaming: false,\n            ...(state.profileIdentity === null ? {} : { identity: state.profileIdentity }),\n          })\n        : state;\n    for (const block of content) {\n      if (block.type !== 'toolCall') continue;\n      if (next.entries.some((item) => item.kind === 'tool' && item.toolCallId === asString(block.id))) continue;\n      // The result is a later entry, so the card starts as running and the\n      // result that follows settles it, exactly as a live run does.\n      next = withEntry(next, {\n        kind: 'tool',\n        id: entryId ? `tool:${asString(block.id)}` : `t${next.nextId}`,\n        ...(timestamp === undefined ? {} : { timestamp }),\n        toolCallId: asString(block.id),\n        name: asString(block.name, 'tool'),\n        args: isRecord(block.arguments) ? block.arguments : {},\n        argSummary: summariseArgs(block.arguments),\n        result: null,\n        output: '',\n        isError: false,\n        running: true,\n      });\n    }\n    return next;\n  }\n\n  if (role === 'toolResult') {\n    return updateTool(state, asString(message.toolCallId), {\n      result: { content, details: message.details },\n      output: textFromContent(content),\n      isError: message.isError === true,\n      running: false,\n    });\n  }\n\n  return state;\n}\n\n/**\n * Folds one journal entry, once. Entries without an id are the runtime's own\n * bookkeeping and are left alone; a message already folded is skipped, which\n * is what makes a re-attach idempotent.\n */\nfunction applyJournalEntry(state: SessionState, entry: Frame): SessionState {\n  if (entry.type !== 'message' || !isRecord(entry.message)) return state;\n  const id = asString(entry.id);\n  if (id === '') return state;\n  if (state.restoredIds.includes(id)) return rememberJournalEntry(state, entry);\n  const message = entry.message;\n  const next = applyJournalMessage(state, message, id, asNumber(entry.timestamp) ?? undefined);\n  const turnId = asString(entry.turnId);\n  const text = message.role === 'user' ? textFromContent(message.content) : undefined;\n  const localUserId =\n    text === undefined\n      ? undefined\n      : [...state.pendingUserEntries, ...state.reconciledUserEntries].find((pending) => pending.text === text)?.id;\n  const entries = next.entries.map((item) => {\n    const ownsTool =\n      item.kind === 'tool' &&\n      Array.isArray(message.content) &&\n      message.content.some(\n        (block: unknown) => isRecord(block) && block.type === 'toolCall' && block.id === item.toolCallId,\n      );\n    const isResult = item.kind === 'tool' && message.role === 'toolResult' && message.toolCallId === item.toolCallId;\n    if (isResult) return { ...item, sourceEntryIds: [...new Set([...(item.sourceEntryIds ?? []), id])] };\n    if (item.id !== id && item.id !== localUserId && !ownsTool) return item;\n    return {\n      ...item,\n      ...(item.id === id ? {} : { sourceEntryId: item.sourceEntryId ?? id }),\n      ...(turnId ? { turnId } : {}),\n    };\n  });\n  return {\n    ...next,\n    entries,\n    transcriptTurnIds: turnId ? { ...next.transcriptTurnIds, [id]: turnId } : next.transcriptTurnIds,\n    restoredIds: [...next.restoredIds, id],\n  };\n}\n\n/**\n * Records a journal entry the protocol already publishes, without folding it.\n *\n * The hub re-reads the journal at every run boundary and re-publishes user\n * messages, because no live frame carries one. Dropping those copies without a\n * trace left the page with no memory of them, so a copy arriving after protocol\n * ownership lapsed read as a new prompt and landed below the settled divider.\n * Keeping the id is what makes the drop idempotent.\n */\nfunction rememberJournalEntry(state: SessionState, entry: Frame): SessionState {\n  if (entry.type !== 'message' || !isRecord(entry.message)) return state;\n  const id = asString(entry.id);\n  if (id === '' || (state.restoredIds.includes(id) && !asString(entry.turnId))) return state;\n  const turnId = asString(entry.turnId);\n  const message = entry.message;\n  const content = message.content;\n  const entries = state.entries.map((item) => {\n    const ownsTool =\n      item.kind === 'tool' &&\n      Array.isArray(content) &&\n      content.some((block: unknown) => isRecord(block) && block.type === 'toolCall' && block.id === item.toolCallId);\n    const isResult = item.kind === 'tool' && message.role === 'toolResult' && message.toolCallId === item.toolCallId;\n    if (isResult) return { ...item, sourceEntryIds: [...new Set([...(item.sourceEntryIds ?? []), id])] };\n    if (item.id !== id && item.sourceEntryId !== id && state.protocolUserEntryIds[id] !== item.id && !ownsTool)\n      return item;\n    return {\n      ...item,\n      ...(item.id === id ? {} : { sourceEntryId: item.sourceEntryId ?? id }),\n      ...(turnId ? { turnId } : {}),\n    };\n  });\n  return {\n    ...state,\n    entries,\n    transcriptTurnIds: turnId ? { ...state.transcriptTurnIds, [id]: turnId } : state.transcriptTurnIds,\n    restoredIds: state.restoredIds.includes(id) ? state.restoredIds : [...state.restoredIds, id],\n  };\n}\n\n/**\n * Folds an older window of transcript above what the page already holds.\n *\n * The reducer is append-only by design: it builds the timeline as the session\n * produces it. Paging backwards is the one case that runs the other way, so\n * the window is reduced on its own and the result is prepended, rather than\n * teaching every case in the reducer about a second direction.\n *\n * Entry ids are positional, so a window reduced from scratch would collide\n * with the live entries. Prefixing by page keeps every key unique and stable\n * across re-renders, which is what a virtualised list needs to keep its\n * measurements.\n */\nexport function prependHistory(state: SessionState, frames: readonly Frame[], page: number): SessionState {\n  // Wrapped: reduce would otherwise pass the index as the options argument.\n  const older = frames.reduce((carried, frame) => reduceSession(carried, frame), initialSessionState);\n  const known = new Set(state.restoredIds);\n  const restored = older.restoredIds.filter((id) => !known.has(id));\n  if (restored.length === 0) return state;\n  const prefix = `h${page}-`;\n  const entries = older.entries\n    .filter((entry) => entry.kind !== 'notice')\n    .map(\n      (entry) =>\n        ({ ...entry, sourceEntryId: entry.sourceEntryId ?? entry.id, id: `${prefix}${entry.id}` }) as TimelineEntry,\n    );\n  return {\n    ...state,\n    entries: [...entries, ...state.entries],\n    transcriptTurnIds: { ...older.transcriptTurnIds, ...state.transcriptTurnIds },\n    restoredIds: [...restored, ...state.restoredIds],\n  };\n}\n\n/**\n * Folds one agent frame into the view model.\n *\n * Pure and total: an unrecognised frame returns the state unchanged, so a Pi\n * protocol addition cannot break the cockpit, it just is not rendered yet.\n */\n/** Frames whose only product is a timeline entry the protocol now publishes. */\nconst TRANSCRIPT_FRAMES = new Set([\n  'message_start',\n  'message_update',\n  'message_end',\n  'tool_execution_start',\n  'tool_execution_update',\n  'tool_execution_end',\n]);\n\nexport interface ReduceSessionOptions {\n  /**\n   * The protocol supplies the transcript, so this reducer must not build one.\n   *\n   * Both would otherwise write the same timeline from different sources: the\n   * snapshot replaces it wholesale while these frames append to it, and the\n   * result flickers between the two. The frames still reach here for\n   * everything else they carry, which is why this is a filter rather than a\n   * missing subscription.\n   */\n  transcriptFromProtocol?: boolean;\n}\n\nexport function reduceSession(state: SessionState, frame: Frame, options: ReduceSessionOptions = {}): SessionState {\n  // Usage is read before the transcript filter below because a session whose\n  // transcript the protocol owns still bills for its messages.\n  return reduceFrame(applyLiveUsage(state, frame), frame, options);\n}\n\nfunction reduceFrame(state: SessionState, frame: Frame, options: ReduceSessionOptions): SessionState {\n  const type = asString(frame.type);\n  if (options.transcriptFromProtocol && TRANSCRIPT_FRAMES.has(type)) {\n    if (type === 'tool_execution_start') {\n      const active = toolEntryFromStart(frame, `active:${asString(frame.toolCallId)}`);\n      const activeTools = [...state.activeTools.filter((entry) => entry.toolCallId !== active.toolCallId), active];\n      return { ...state, activeTools, toolsThisRun: state.toolsThisRun + 1 };\n    }\n    if (type === 'tool_execution_end') {\n      const toolCallId = asString(frame.toolCallId);\n      return { ...state, activeTools: state.activeTools.filter((entry) => entry.toolCallId !== toolCallId) };\n    }\n    return state;\n  }\n\n  switch (type) {\n    case 'replay':\n      return isRecord(frame.frame) ? reduceSession(state, frame.frame, options) : state;\n\n    case 'agent_start':\n      return {\n        ...state,\n        activeTools: [],\n        streaming: state.lifecycle === null ? true : state.lifecycle.operation !== null,\n        settled: false,\n        toolsThisRun: 0,\n      };\n\n    case 'message_start':\n    case 'message_update': {\n      const event = isRecord(frame.assistantMessageEvent) ? frame.assistantMessageEvent : undefined;\n      const message = isRecord(frame.message)\n        ? frame.message\n        : event?.type === 'start' && isRecord(event.partial)\n          ? event.partial\n          : undefined;\n      if (message?.role !== undefined && message.role !== 'assistant') return state;\n      const timestamp = asNumber(message?.timestamp);\n      const model = typeof message?.model === 'string' ? message.model : undefined;\n      if (type === 'message_start' && timestamp !== null) {\n        const previous = state.entries.findLast((entry) => entry.kind === 'assistant' && entry.timestamp !== undefined);\n        if (previous?.kind === 'assistant' && previous.timestamp !== undefined) {\n          if (\n            previous.timestamp > timestamp ||\n            (previous.timestamp === timestamp && (!model || !previous.model || previous.model === model))\n          )\n            return state;\n          // A newer start belongs to a new bubble, even if completion was delayed.\n          if (previous.streaming && previous.timestamp < timestamp) state = closeAssistant(state, undefined);\n        }\n      }\n      if (message && (typeof message.content === 'string' || Array.isArray(message.content))) {\n        const opened = openAssistant(state);\n        return replaceEntry(opened.state, opened.entry.id, {\n          ...opened.entry,\n          ...(timestamp === null ? {} : { timestamp }),\n          ...(model === undefined ? {} : { model }),\n          text: textFromContent(message.content),\n          thinking: thinkingFromContent(Array.isArray(message.content) ? message.content.filter(isRecord) : []),\n        });\n      }\n      return isRecord(frame.assistantMessageEvent) ? applyAssistantDelta(state, frame.assistantMessageEvent) : state;\n    }\n\n    case 'message_end': {\n      if (isRecord(frame.message) && frame.message.role !== undefined && frame.message.role !== 'assistant')\n        return state;\n      const id = asString(frame.entryId);\n      if (id && state.entries.some((item) => item.id === id)) return state;\n      const failedTimestamp =\n        isRecord(frame.message) && assistantFailureText(frame.message) ? asNumber(frame.message.timestamp) : null;\n      if (\n        !id &&\n        failedTimestamp !== null &&\n        state.entries.some((item) => item.kind === 'assistant' && !item.streaming && item.timestamp === failedTimestamp)\n      )\n        return state;\n      if (\n        !state.entries.some((item) => item.kind === 'assistant' && item.streaming) &&\n        assistantFailureText(frame.message)\n      )\n        state = openAssistant(state).state;\n      const draft = state.entries.findLast((item) => item.kind === 'assistant' && item.streaming);\n      const closed = closeAssistant(state, frame.message);\n      if (!id || !draft) return closed;\n      return { ...closed, entries: closed.entries.map((item) => (item.id === draft.id ? { ...item, id } : item)) };\n    }\n\n    case 'tool_execution_start':\n      return applyToolStart(state, frame);\n\n    case 'tool_execution_update':\n      return updateTool(state, asString(frame.toolCallId), {\n        result: toolResult(frame.partialResult),\n        output: textFromContent(isRecord(frame.partialResult) ? frame.partialResult.content : undefined),\n      });\n\n    case 'tool_execution_end':\n      return updateTool(state, asString(frame.toolCallId), {\n        result: toolResult(frame.result),\n        output: textFromContent(isRecord(frame.result) ? frame.result.content : undefined),\n        isError: frame.isError === true,\n        running: false,\n      });\n\n    case 'agent_settled': {\n      const closed = options.transcriptFromProtocol ? state : closeAssistant(state, undefined);\n      const timestamp = asNumber(frame.timestamp) ?? undefined;\n      const id = typeof frame.runId === 'string' ? `settled:${frame.runId}` : `s${closed.nextId}`;\n      const marked = closed.entries.some((entry) => entry.id === id)\n        ? closed\n        : withChronologicalEntry(closed, {\n            kind: 'settled',\n            id,\n            tools: closed.toolsThisRun,\n            ...(typeof frame.runId === 'string' && frame.runId ? { turnId: frame.runId } : {}),\n            ...(Array.isArray(frame.entryIds)\n              ? { entryIds: frame.entryIds.filter((id): id is string => typeof id === 'string') }\n              : {}),\n            ...(timestamp === undefined ? {} : { timestamp }),\n          });\n      return {\n        ...marked,\n        activeTools: [],\n        dialog: null,\n        streaming: state.lifecycle === null ? false : state.lifecycle.operation !== null,\n        settled: state.lifecycle === null ? true : state.lifecycle.operation === null,\n      };\n    }\n\n    case 'queue_update': {\n      if (state.lifecycle !== null) return state;\n      const steering = Array.isArray(frame.steering) ? frame.steering : [];\n      const followUp = Array.isArray(frame.followUp) ? frame.followUp : [];\n      const queue = [\n        ...steering.map((entry) => ({ text: asString(entry), delivery: 'steer' as const })),\n        ...followUp.map((entry) => ({ text: asString(entry), delivery: 'followUp' as const })),\n      ]\n        .map((entry, index) => ({ kind: 'queued' as const, id: `queue-${index}`, ...entry }))\n        .filter((entry) => entry.text.length > 0);\n      return replaceQueuedEntries(state, queue);\n    }\n\n    case 'extension_ui_request': {\n      // Agent notifications carry the outcome a TUI user would see (a mode\n      // switch pending a relaunch, a refused action); dropping them reads as\n      // the agent doing nothing.\n      if (frame.method === 'notify') {\n        const text = asString(frame.message, '');\n        if (text === '') return state;\n        return withEntry(state, {\n          kind: 'notice',\n          id: `n${state.nextId}`,\n          text,\n          tone: frame.notifyType === 'error' ? 'error' : 'info',\n        });\n      }\n      return applyDialog(state, frame);\n    }\n\n    // Hub-synthesized when any tab answers a dialog: closes it on other live\n    // tabs, and on backlog replays keeps an answered request from reopening.\n    case DIALOG_ANSWERED_TYPE:\n      return state.dialog && state.dialog.id === asString(frame.id) ? { ...state, dialog: null } : state;\n\n    // Pi announces a thinking level it switched on its own behalf: plan mode\n    // applying its configured effort, or the /effort command. state.agent is\n    // otherwise written only by a get_state this page asked for, so without\n    // this the chip keeps whatever the last request reported.\n    case 'fast_mode_changed':\n      return typeof frame.enabled === 'boolean' ? { ...state, fastMode: frame.enabled } : state;\n\n    case 'agent_lock_changed':\n      return typeof frame.locked === 'boolean' ? { ...state, agentLocked: frame.locked } : state;\n\n    case 'thinking_level_changed': {\n      if (state.agent === null) return state;\n      const level = asString(frame.level, state.agent.thinkingLevel);\n      return { ...state, agent: { ...state.agent, thinkingLevel: level } };\n    }\n\n    // Journaled composition and notifications apply independently of protocol-owned messages.\n    case 'entry_appended': {\n      const entry = isRecord(frame.entry) ? frame.entry : undefined;\n      if (!entry) return state;\n      const notification = parsePoNotificationEntry(frame);\n      if (notification) {\n        if (state.restoredIds.includes(notification.entryId)) return state;\n        const timestamp = asNumber(entry.timestamp) ?? undefined;\n        const next = withChronologicalEntry(state, {\n          kind: 'notice',\n          id: `n${state.nextId}`,\n          text: notification.data.body,\n          tone: notification.data.level === 'error' ? 'error' : 'info',\n          ...(timestamp === undefined ? {} : { timestamp }),\n        });\n        return { ...next, restoredIds: [...next.restoredIds, notification.entryId] };\n      }\n      if (entry.type === 'custom' && entry.customType === MODE_ENTRY_TYPE) {\n        const data = isRecord(entry.data) ? entry.data : undefined;\n        if (!data || !Array.isArray(data.modes)) return state;\n        return { ...state, modes: data as unknown as ModeProjection };\n      }\n      if (entry.type === 'custom' && entry.customType === CONTEXT_ENTRY_TYPE) {\n        const data = isRecord(entry.data) ? entry.data : undefined;\n        if (!data || !Array.isArray(data.groups)) return state;\n        return applyContextSelection(state, data as unknown as ContextProjection);\n      }\n      // Pi has no wire event for a model an extension chose, so the runtime\n      // journals one. Guarded on agent because a get_state has to have named\n      // the rest of the facts before a model can be swapped into them.\n      if (entry.type === 'custom' && entry.customType === AGENT_MODEL_ENTRY_TYPE) {\n        const data = isRecord(entry.data) ? entry.data : undefined;\n        if (!data || state.agent === null) return state;\n        const id = asString(data.id, '');\n        const provider = asString(data.provider, '');\n        if (id === '' || provider === '') return state;\n        return { ...state, agent: { ...state.agent, model: id, provider } };\n      }\n      // Folded in journal order, never collapsed: assistant messages are stamped\n      // with whatever was current when they were created, so a switch leaves the\n      // messages before it attributed to the persona that wrote them.\n      if (entry.type === 'custom' && entry.customType === PROFILE_IDENTITY_ENTRY_TYPE) {\n        const data = isRecord(entry.data) ? entry.data : undefined;\n        if (data?.profile === null) return { ...state, profileIdentity: null };\n        const profile = asString(data?.profile, '');\n        if (profile === '') return state;\n        const name = asString(data?.name, '');\n        const icon = asString(data?.icon, '');\n        return {\n          ...state,\n          profileIdentity: {\n            profile,\n            ...(name === '' ? {} : { name }),\n            ...(icon === '' ? {} : { icon }),\n          },\n        };\n      }\n      if (entry.type === 'custom' && entry.customType === 'po.agent-settled') {\n        const data = isRecord(entry.data) ? entry.data : {};\n        const id = `settled:${asString(data.runId)}`;\n        const entryIds = Array.isArray(data.entryIds)\n          ? data.entryIds.filter((id): id is string => typeof id === 'string')\n          : undefined;\n        if (state.entries.some((item) => item.id === id)) {\n          return entryIds === undefined\n            ? state\n            : {\n                ...state,\n                entries: state.entries.map((item) =>\n                  item.id === id && item.kind === 'settled'\n                    ? { ...item, entryIds, turnId: asString(data.runId) }\n                    : item,\n                ),\n              };\n        }\n        return withChronologicalEntry(state, {\n          kind: 'settled',\n          id,\n          tools: asNumber(data.tools) ?? 0,\n          ...(asString(data.runId) ? { turnId: asString(data.runId) } : {}),\n          ...(Array.isArray(data.entryIds)\n            ? { entryIds: data.entryIds.filter((id): id is string => typeof id === 'string') }\n            : {}),\n          timestamp: asNumber(data.timestamp) ?? asNumber(entry.timestamp) ?? undefined,\n        });\n      }\n      // A journalled user message is a transcript entry the protocol already\n      // publishes; the catalog above is Po's own and always applies.\n      const next = options.transcriptFromProtocol\n        ? rememberJournalEntry(state, entry)\n        : applyJournalEntry(state, entry);\n      // The placed steer and its pending row swap in this one step, so the message never shows twice or not at all.\n      return typeof entry.submissionId === 'string' ? placeSteer(next, entry.submissionId) : next;\n    }\n\n    case 'response':\n      return applyResponse(state, frame);\n\n    case 'error':\n    case 'extension_error':\n      return withEntry(state, {\n        kind: 'notice',\n        id: `n${state.nextId}`,\n        text: asString(frame.message ?? frame.error, 'The agent reported an error.'),\n        tone: 'error',\n      });\n\n    default:\n      return state;\n  }\n}\n\n/** Records the prompt locally, because Pi does not echo it back as an event. */\nexport function appendUserPrompt(state: SessionState, text: string, images: UserImage[] = []): SessionState {\n  const id = `u${state.nextId}`;\n  const entry: UserEntry = { kind: 'user', id, text, ...(images.length > 0 ? { images } : {}) };\n  return withPendingUser(withEntry(state, entry), id, text, images);\n}\n\n/** A follow-up waits for the current run, so it is marked rather than shown as sent. */\nexport function appendQueued(state: SessionState, text: string, images: UserImage[] = []): SessionState {\n  const id = `q${state.nextId}`;\n  const entry: QueuedEntry = {\n    kind: 'queued',\n    id,\n    text,\n    delivery: 'followUp',\n    ...(images.length > 0 ? { images } : {}),\n  };\n  return withPendingUser(withEntry(state, entry), id, text, images);\n}\n\n// ponytail: remembers the last 32 placed steers; an older lifecycle frame than that could resurrect one.\nconst PLACED_STEER_MEMORY = 32;\n\n/** Drops a steer's pending row once its journal entry lands, and remembers it against older lifecycle frames. */\nfunction placeSteer(state: SessionState, submissionId: string): SessionState {\n  if (state.placedSteers.includes(submissionId)) return state;\n  return {\n    ...state,\n    pendingSteers: state.pendingSteers.filter((entry) => entry.id !== `steer:${submissionId}`),\n    placedSteers: [...state.placedSteers, submissionId].slice(-PLACED_STEER_MEMORY),\n  };\n}\n\n/** Uses server IDs as-is: equal text or a snapshot revision is not an item identity. */\nexport function replaceQueuedEntries(state: SessionState, queue: readonly QueuedEntry[]): SessionState {\n  return {\n    ...state,\n    entries: [...state.entries.filter((entry) => entry.kind !== 'queued'), ...queue],\n  };\n}\n\n/** Removes queued rows and their reconciliation records after Pi clears the queue. */\nexport function clearQueuedEntries(state: SessionState): SessionState {\n  const queuedIds = new Set(state.entries.filter((entry) => entry.kind === 'queued').map((entry) => entry.id));\n  return {\n    ...state,\n    entries: state.entries.filter((entry) => entry.kind !== 'queued'),\n    pendingUserEntries: state.pendingUserEntries.filter((entry) => !queuedIds.has(entry.id)),\n  };\n}\n\n/** Removes one queued row and the optimistic reconciliation record tied to it. */\nexport function removeQueuedEntry(state: SessionState, id: string): SessionState {\n  return {\n    ...state,\n    entries: state.entries.filter((entry) => entry.kind !== 'queued' || entry.id !== id),\n    pendingUserEntries: state.pendingUserEntries.filter((entry) => entry.id !== id),\n  };\n}\nexport function clearDialog(state: SessionState): SessionState {\n  return { ...state, dialog: null };\n}\n"],"mappings":";;;;;;;AA8RA,MAAa,sBAAoC;CAC/C,iBAAiB;CACjB,SAAS,CAAC;CACV,aAAa,CAAC;CACd,UAAU,CAAC;CACX,SAAS,CAAC;CACV,WAAW;CACX,SAAS;CACT,WAAW;CACX,OAAO;CACP,UAAU;CACV,OAAO;CACP,UAAU,CAAC;CACX,QAAQ,CAAC;CACT,UAAU;CACV,aAAa;CACb,gBAAgB,CAAC;CACjB,QAAQ;CACR,mBAAmB;CACnB,OAAO;CACP,SAAS;CACT,iBAAiB;CACjB,cAAc;CACd,aAAa,CAAC;CACd,oBAAoB,CAAC;CACrB,uBAAuB,CAAC;CACxB,sBAAsB,CAAC;CACvB,mBAAmB,CAAC;CACpB,QAAQ;CACR,eAAe,CAAC;CAChB,cAAc,CAAC;AACjB;AAIA,SAAS,SAAS,OAAgC;CAChD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAgB,WAAW,IAAY;CACvD,OAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEA,SAAS,SAAS,OAA+B;CAC/C,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;;AAGA,SAAgB,gBAAgB,SAA0B;CACxD,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO;CACpC,OAAO,QACJ,KAA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