{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chat-normalizers",
  "type": "registry:lib",
  "title": "Native chat format projections",
  "description": "Native chat format projections. No native SDK runtime dependency.",
  "dependencies": [],
  "registryDependencies": [
    "https://ghost-ui.com/r/chat-model.json",
    "https://ghost-ui.com/r/chat-runtime.json"
  ],
  "files": [
    {
      "path": "src/lib/chat-adapters/normalize.ts",
      "type": "registry:lib",
      "target": "@lib/chat-adapters/normalize.ts",
      "content": "import type { ChatActor, ChatMessage, ChatPart, ToolPart } from '@/components/ui/chat-model';\nimport { isRecord, readString, mediaPart } from './shared';\n\ntype RecordValue = Record<string, unknown>;\nexport interface ChatNormalizeOptions {\n  /** Supply stable application IDs only when the upstream record has none. */\n  getId?(record: unknown): string;\n  /** null deliberately omits a part; undefined uses the default mapping. */\n  mapPart?(part: unknown, message: unknown): ChatPart | null | undefined;\n  /** Raw reasoning is withheld unless the application explicitly classifies it. */\n  classifyReasoning?(part: unknown): 'provider-summary' | 'application-summary' | 'drop';\n}\nconst record = (value: unknown): RecordValue => isRecord(value) ? value : {};\nconst list = (value: unknown): readonly unknown[] => Array.isArray(value) ? value : [];\nfunction identity(value: unknown, options: ChatNormalizeOptions, field = 'id'): string {\n  const id = readString(record(value)[field]) ?? options.getId?.(value);\n  if (!id?.trim()) throw new TypeError('A stable upstream or application record ID is required.');\n  return id;\n}\nfunction unknown(value: unknown, type?: string): ChatPart {\n  return { type: 'unknown', originalType: type ?? readString(record(value).type) ?? 'unrecognized', value };\n}\nfunction nativeMetadata(value: RecordValue) {\n  const { content: _content, parts: _parts, ...native } = value;\n  const nativeParts = list(value.parts ?? record(value.content).parts ?? value.content).filter(part => record(part).type !== 'reasoning' && record(part).thought !== true);\n  return { native, ...(nativeParts.length ? { nativeParts } : {}) };\n}\nfunction message(id: string, actor: ChatActor, parts: readonly ChatPart[], value: RecordValue): ChatMessage {\n  return { id, actor, parts, metadata: nativeMetadata(value) };\n}\nfunction part(value: unknown, parent: unknown, fallbackId: string, options: ChatNormalizeOptions): ChatPart | undefined {\n  const mapped = options.mapPart?.(value, parent);\n  if (mapped !== undefined) return mapped ?? undefined;\n  const raw = record(value); const type = readString(raw.type);\n  if (type === 'reasoning' || raw.thought === true) {\n    const classification = options.classifyReasoning?.(value) ?? 'drop';\n    return classification !== 'drop' && typeof raw.text === 'string' ? { type: 'reasoning-summary', id: readString(raw.id) ?? fallbackId, text: raw.text, source: classification } : undefined;\n  }\n  if ((type === 'text' || type === 'output_text' || type === 'input_text' || type === 'summary_text') && typeof raw.text === 'string') return { type: 'text', id: readString(raw.id) ?? fallbackId, text: raw.text };\n  if (type === 'file' || type === 'image_url' || type === 'image') return mediaPart(raw, fallbackId);\n  return unknown(value);\n}\nfunction content(value: unknown, parent: unknown, id: string, options: ChatNormalizeOptions): ChatPart[] {\n  if (typeof value === 'string') return [{ type: 'text', id: `${id}:text`, text: value }];\n  return list(value).flatMap((value, index) => { const mapped = part(value, parent, `${id}:part:${index}`, options); return mapped ? [mapped] : []; });\n}\nfunction tool(id: string, name: string, state: ToolPart['state'], input?: unknown, output?: unknown): ToolPart {\n  return { type: 'tool', id, name, state, ...(input !== undefined ? { input } : {}), ...(output !== undefined ? { output } : {}) };\n}\n/** Replace repeated item IDs without moving their first position. No transcript state is retained. */\nexport function replaceChatRecordsById<T>(records: readonly T[], getId: (record: T) => string): readonly T[] {\n  const entries = new Map<string, T>();\n  for (const value of records) { const id = getId(value); if (!id?.trim()) throw new TypeError('A stable record ID is required.'); entries.set(id, value); }\n  return [...entries.values()];\n}\n\n/** Serialized LangChain messages from useStream or LangGraph SDK state. */\nexport function normalizeLangChainMessages(values: readonly unknown[], options: ChatNormalizeOptions = {}): readonly ChatMessage[] {\n  const messages = new Map<string, ChatMessage>();\n  for (const value of values) {\n    const original = record(value);\n    const kind = typeof original.getType === 'function' ? original.getType.call(value) : original.type;\n    const raw: RecordValue = { ...original, type: kind }; const id = identity(value, options);\n    if (raw.type === 'remove') { if (id === '__remove_all__') messages.clear(); else messages.delete(id); continue; }\n    const actor: ChatActor = raw.type === 'human' ? 'user' : raw.type === 'system' ? 'system' : 'assistant';\n    const parts = content(raw.content, value, id, options);\n    if (raw.type === 'tool') {\n      const callId = readString(raw.tool_call_id);\n      messages.set(id, message(id, actor, [callId ? tool(callId, readString(raw.name) ?? 'Tool', raw.status === 'error' ? 'error' : 'output-ready', undefined, raw.content) : unknown(value, 'tool-result-without-id')], raw));\n      continue;\n    }\n    for (const call of list(raw.tool_calls)) {\n      const data = record(call); const callId = readString(data.id);\n      parts.push(callId ? tool(callId, readString(data.name) ?? 'Tool', 'input-ready', data.args) : unknown(call, 'tool-call-without-id'));\n    }\n    for (const invalid of list(raw.invalid_tool_calls)) parts.push(unknown(invalid, 'invalid-tool-call'));\n    if (!['human', 'ai', 'system', 'function'].includes(String(raw.type))) parts.push(unknown(value, 'langchain-message'));\n    messages.set(id, message(id, actor, parts, raw));\n  }\n  return [...messages.values()];\n}\n\n/** Snapshot messages owned and reconstructed by @ag-ui/client. */\nexport function normalizeAgUiMessages(values: readonly unknown[], options: ChatNormalizeOptions = {}): readonly ChatMessage[] {\n  return replaceChatRecordsById(values, value => identity(value, options)).map(value => {\n    const raw = record(value); const id = identity(value, options);\n    const actor: ChatActor = raw.role === 'user' ? 'user' : raw.role === 'system' || raw.role === 'developer' ? 'system' : 'assistant';\n    if (raw.role === 'tool') {\n      const callId = readString(raw.toolCallId);\n      return message(id, actor, [callId ? tool(callId, readString(raw.name) ?? 'Tool', 'output-ready', undefined, raw.content) : unknown(value, 'tool-result-without-id')], raw);\n    }\n    const parts = content(raw.content, value, id, options);\n    for (const call of list(raw.toolCalls)) {\n      const data = record(call); const fn = record(data.function); const callId = readString(data.id);\n      parts.push(callId ? tool(callId, readString(fn.name) ?? 'Tool', 'input-ready', fn.arguments) : unknown(call, 'tool-call-without-id'));\n    }\n    return message(id, actor, parts, raw);\n  });\n}\n\n/** OpenRouter items are replacement snapshots, never text deltas. */\nexport function normalizeOpenRouterItems(values: readonly unknown[], options: ChatNormalizeOptions = {}): readonly ChatMessage[] {\n  return replaceChatRecordsById(values, value => identity(value, options)).map(value => {\n    const raw = record(value); const id = identity(value, options); const callId = readString(raw.callId) ?? readString(raw.call_id);\n    let parts: ChatPart[];\n    if (raw.type === 'message') parts = content(raw.content, value, id, options);\n    else if (raw.type === 'function_call') parts = [callId ? tool(callId, readString(raw.name) ?? 'Tool', raw.status === 'in_progress' ? 'input-streaming' : 'input-ready', raw.arguments) : unknown(value, 'tool-call-without-id')];\n    else if (raw.type === 'function_call_output') parts = [callId ? tool(callId, readString(raw.name) ?? 'Tool', raw.isError === true || raw.is_error === true ? 'error' : 'output-ready', undefined, raw.output) : unknown(value, 'tool-result-without-id')];\n    else if (raw.type === 'reasoning') parts = list(raw.summary).flatMap((summary, index) => {\n      const classified = options.classifyReasoning?.(summary) ?? 'drop'; const text = record(summary).text;\n      return classified !== 'drop' && typeof text === 'string' ? [{ type: 'reasoning-summary' as const, id: `${id}:summary:${index}`, text, source: classified }] : [];\n    });\n    else parts = [unknown(value)];\n    return message(id, raw.role === 'user' ? 'user' : raw.role === 'system' ? 'system' : 'assistant', parts, raw);\n  });\n}\n\n/** OpenCode SDK session.messages records; the SDK/application owns its event subscription. */\nexport function normalizeOpenCodeMessages(values: readonly unknown[], options: ChatNormalizeOptions = {}): readonly ChatMessage[] {\n  return replaceChatRecordsById(values, value => identity(record(value).info, options)).map(value => {\n    const raw = record(value); const info = record(raw.info); const id = identity(info, options);\n    const parts = list(raw.parts).flatMap((value, index) => {\n      const data = record(value); const mapped = options.mapPart?.(value, raw);\n      if (mapped !== undefined) return mapped ? [mapped] : [];\n      if (data.type === 'tool') {\n        const state = record(data.state); const callId = readString(data.callID);\n        const status = { pending: 'input-ready', running: 'running', completed: 'output-ready', error: 'error' }[String(state.status)] as ToolPart['state'] | undefined;\n        if (!callId || !status) return [unknown(value)];\n        return [{ ...tool(callId, readString(data.tool) ?? 'Tool', status, state.input, state.output), ...(typeof state.error === 'string' ? { error: state.error } : {}) }];\n      }\n      const mappedPart = part(value, raw, `${id}:part:${index}`, { ...options, mapPart: undefined });\n      return mappedPart ? [mappedPart] : [];\n    });\n    return { ...message(id, info.role === 'user' ? 'user' : 'assistant', parts, info), ...(info.error ? { status: 'error' as const } : {}) };\n  });\n}\n\n/** Eve's hook already projects the authoritative event log; reuse that projection. */\nexport function normalizeEveMessages(values: readonly unknown[], options: ChatNormalizeOptions = {}): readonly ChatMessage[] {\n  return replaceChatRecordsById(values, value => identity(value, options)).map(value => {\n    const raw = record(value); const id = identity(value, options);\n    const parts = list(raw.parts).flatMap((value, index) => {\n      const data = record(value); const mapped = options.mapPart?.(value, raw);\n      if (mapped !== undefined) return mapped ? [mapped] : [];\n      if (data.type === 'tool') {\n        const callId = readString(data.callId);\n        const state = { streaming: 'input-streaming', requested: 'input-ready', approval: 'input-ready', blocked: 'input-ready', running: 'running', completed: 'output-ready', failed: 'error', rejected: 'cancelled', cancelled: 'cancelled' }[String(data.state)] as ToolPart['state'] | undefined;\n        if (!callId || !state) return [unknown(value)];\n        const result: ChatPart[] = [tool(callId, readString(data.name) ?? 'Tool', state, data.input ?? data.inputText, data.output)];\n        if (data.interaction) result.push({ type: 'data', id: `${callId}:interaction`, name: 'eve-interaction', data: data.interaction });\n        return result;\n      }\n      if (data.type === 'interaction') return [{ type: 'data' as const, id: readString(data.id) ?? `${id}:interaction:${index}`, name: 'eve-interaction', data: value }];\n      const mappedPart = part(value, raw, `${id}:part:${index}`, { ...options, mapPart: undefined });\n      return mappedPart ? [mappedPart] : [];\n    });\n    const state = record(raw.metadata).status;\n    return { ...message(id, raw.role === 'user' ? 'user' : 'assistant', parts, raw), ...(state === 'streaming' ? { status: 'streaming' as const } : state === 'failed' ? { status: 'error' as const } : {}) };\n  });\n}\n\n/** SDK v1 protobuf and JSON representations preserve task/context metadata. */\nexport function normalizeA2aMessages(values: readonly unknown[], options: ChatNormalizeOptions = {}): readonly ChatMessage[] {\n  return replaceChatRecordsById(values, value => identity(value, options, 'messageId')).map(value => {\n    const raw = record(value); const id = identity(value, options, 'messageId');\n    const parts = list(raw.parts).map((value, index) => {\n      const mapped = options.mapPart?.(value, raw); if (mapped !== undefined) return mapped;\n      const data = record(value); const payload = record(data.content); const kind = payload.$case;\n      if (kind === 'text' && typeof payload.value === 'string') return { type: 'text' as const, id: `${id}:part:${index}`, text: payload.value };\n      if (typeof data.text === 'string') return { type: 'text' as const, id: `${id}:part:${index}`, text: data.text };\n      if (kind === 'data' || data.data !== undefined) return { type: 'data' as const, id: `${id}:part:${index}`, name: 'a2a-data', data: kind === 'data' ? payload.value : data.data };\n      return unknown(value, 'a2a-part');\n    }).filter((value): value is ChatPart => value !== null);\n    return message(id, raw.role === 1 || raw.role === 'ROLE_USER' || raw.role === 'user' ? 'user' : 'assistant', parts, raw);\n  });\n}\n\n/** Google ADK event snapshots. Partial previews are replaced by the authoritative event. */\nexport function normalizeAdkEvents(values: readonly unknown[], options: ChatNormalizeOptions = {}): readonly ChatMessage[] {\n  const output = new Map<string, ChatMessage>();\n  const previews = new Map<string, string>();\n  for (const value of replaceChatRecordsById(values, value => identity(value, options))) {\n    const raw = record(value); const id = identity(value, options);\n    const invocation = readString(raw.invocationId ?? raw.invocation_id);\n    const scope = invocation && readString(raw.author) ? JSON.stringify([invocation, raw.author, raw.branch]) : id;\n    const previewId = previews.get(scope);\n    if (!raw.partial && previewId) { output.delete(previewId); previews.delete(scope); }\n    const body = record(raw.content);\n    const parts = list(body.parts).flatMap((value, index) => {\n      const mapped = options.mapPart?.(value, raw); if (mapped !== undefined) return mapped ? [mapped] : [];\n      const data = record(value); const call = record(data.functionCall ?? data.function_call); const response = record(data.functionResponse ?? data.function_response);\n      if (data.functionCall || data.function_call) return [readString(call.id) ? tool(String(call.id), readString(call.name) ?? 'Tool', 'input-ready', call.args) : unknown(value, 'function-call-without-id')];\n      if (data.functionResponse || data.function_response) return [readString(response.id) ? tool(String(response.id), readString(response.name) ?? 'Tool', 'output-ready', undefined, response.response) : unknown(value, 'function-response-without-id')];\n      const mappedPart = part(typeof data.text === 'string' ? { ...data, type: 'text' } : value, raw, `${id}:part:${index}`, { ...options, mapPart: undefined });\n      return mappedPart ? [mappedPart] : [];\n    });\n    const actions = raw.actions;\n    if (actions && Object.keys(record(actions)).length) parts.push({ type: 'data', id: `${id}:actions`, name: 'adk-actions', data: actions });\n    if (raw.groundingMetadata || raw.grounding_metadata) parts.push({ type: 'data', id: `${id}:grounding`, name: 'adk-grounding', data: raw.groundingMetadata ?? raw.grounding_metadata });\n    const errorCode = readString(raw.errorCode ?? raw.error_code);\n    const error = readString(raw.errorMessage ?? raw.error_message) ?? (errorCode ? `ADK error: ${errorCode}` : undefined);\n    if (error) parts.push({ type: 'error', id: `${id}:error`, message: error });\n    if (raw.partial && previewId) {\n      const previous = output.get(previewId)!;\n      const merged = [...previous.parts];\n      for (const next of parts) {\n        const last = merged.at(-1);\n        if (last?.type === 'text' && next.type === 'text') merged[merged.length - 1] = { ...last, text: last.text + next.text };\n        else merged.push(next);\n      }\n      output.set(previewId, { ...previous, parts: merged, metadata: { ...previous.metadata, nativeEvents: [...list(previous.metadata?.nativeEvents), value] } });\n    } else {\n      if (raw.partial) previews.set(scope, id);\n      output.set(id, { ...message(id, raw.author === 'user' || body.role === 'user' ? 'user' : 'assistant', parts, raw), ...(readString(raw.author) ? { author: { name: String(raw.author), kind: raw.author === 'user' ? 'human' : 'agent' } as const } : {}), ...(error ? { status: 'error' as const } : raw.partial ? { status: 'streaming' as const } : {}) });\n    }\n  }\n  return [...output.values()];\n}\n\n/** Buffered Managed Agents facts are authoritative; replay and live tails use this same projection. */\nexport function normalizeManagedAgentEvents(values: readonly unknown[], options: ChatNormalizeOptions = {}): readonly ChatMessage[] {\n  const events = replaceChatRecordsById(values, value => identity(value, options));\n  const output = new Map<string, ChatMessage>();\n  const tools = new Map<string, { messageId: string; part: ToolPart; kind: string }>();\n  const updateTool = (id: string, update: (value: ToolPart) => ToolPart, fact?: unknown) => {\n    const current = tools.get(id); if (!current) return false;\n    const next = update(current.part); current.part = next;\n    const owner = output.get(current.messageId)!;\n    output.set(owner.id, { ...owner, parts: owner.parts.map(part => part.type === 'tool' && part.id === id ? next : part), metadata: { ...owner.metadata, nativeEvents: [...list(owner.metadata?.nativeEvents), ...(fact ? [fact] : [])] } });\n    return true;\n  };\n  for (const value of events) {\n    const raw = record(value); const id = identity(value, options); const type = String(raw.type);\n    if (type === 'agent.message' || type === 'user.message') {\n      output.set(id, message(id, type === 'user.message' ? 'user' : 'assistant', content(raw.content, raw, id, options), raw)); continue;\n    }\n    if (['agent.tool_use', 'agent.mcp_tool_use', 'agent.custom_tool_use'].includes(type)) {\n      const permission = type === 'agent.custom_tool_use' ? undefined : raw.evaluated_permission;\n      const data = tool(id, readString(raw.name) ?? 'Tool', permission === 'deny' ? 'cancelled' : permission === 'ask' ? 'approval-required' : 'input-ready', raw.input);\n      if (permission === 'ask') data.approval = { id, state: 'pending' };\n      tools.set(id, { messageId: id, part: data, kind: type }); output.set(id, message(id, 'assistant', [data], raw)); continue;\n    }\n    if (type === 'session.status_idle' && record(raw.stop_reason).type === 'requires_action') {\n      let unmatched = false;\n      for (const blocked of list(record(raw.stop_reason).event_ids)) {\n        if (typeof blocked !== 'string') continue;\n        if (!tools.has(blocked)) { unmatched = true; continue; }\n        if (tools.get(blocked)?.kind === 'agent.custom_tool_use') {\n          const owner = output.get(blocked)!;\n          output.set(blocked, { ...owner, parts: [...owner.parts, { type: 'data', id: `${blocked}:result-request`, name: 'managed-client-tool-request', data: value }] });\n        } else updateTool(blocked, current => ({ ...current, state: 'approval-required', approval: { id: blocked, state: 'pending' } }), value);\n      }\n      if (unmatched) output.set(id, message(id, 'assistant', [{ type: 'data', id, name: 'managed-agent-event', data: value }], raw));\n    } else if (type === 'user.tool_confirmation') {\n      if (!updateTool(String(raw.tool_use_id), current => ({ ...current, state: raw.result === 'deny' ? 'cancelled' : 'approval-resolved', approval: { id: current.id, state: raw.result === 'deny' ? 'denied' : 'approved' } }), value)) output.set(id, message(id, 'assistant', [unknown(value, 'unmatched-tool-confirmation')], raw));\n    } else if (['agent.tool_result', 'agent.mcp_tool_result', 'user.custom_tool_result'].includes(type)) {\n      if (!updateTool(String(raw.tool_use_id ?? raw.mcp_tool_use_id ?? raw.custom_tool_use_id), current => ({ ...current, state: raw.is_error ? 'error' : 'output-ready', output: raw.content }), value)) output.set(id, message(id, 'assistant', [unknown(value, 'unmatched-tool-result')], raw));\n    } else if (type === 'agent.thinking') {\n      output.set(id, message(id, 'assistant', [{ type: 'data', id, name: 'agent-progress', data: { thinking: true } }], raw));\n    } else if (type === 'event_start' || type === 'event_delta') {\n      // Previews are optional and can be dropped by the server; buffered facts remain authoritative.\n      const targetId = readString(raw.event_id) ?? readString(record(raw.event).id);\n      if (targetId && events.some(event => record(event).id === targetId && record(event).type === 'agent.message')) continue;\n      output.set(id, message(id, 'assistant', [{ type: 'data', id, name: 'managed-agent-preview', data: value }], raw));\n    } else {\n      output.set(id, message(id, 'assistant', [{ type: 'data', id, name: 'managed-agent-event', data: value }], raw));\n    }\n  }\n  return [...output.values()];\n}\n\n/** Messages assembled by assistant-stream's maintained accumulators, including legacy data streams. */\nexport function normalizeAssistantStreamMessage(id: string, value: unknown, options: ChatNormalizeOptions = {}): ChatMessage {\n  if (!id?.trim()) throw new TypeError('An application-owned assistant message ID is required.');\n  const raw = record(value);\n  const parts = list(raw.content).flatMap((value, index) => {\n    const mapped = options.mapPart?.(value, raw); if (mapped !== undefined) return mapped ? [mapped] : [];\n    const data = record(value);\n    if (data.type === 'tool-call') {\n      const callId = readString(data.toolCallId);\n      if (!callId) return [unknown(value, 'tool-call-without-id')];\n      const complete = data.state === 'result' && data.isPreliminary !== true;\n      const result: ChatPart[] = [tool(callId, readString(data.toolName) ?? 'Tool', complete ? data.isError ? 'error' : 'output-ready' : data.state === 'partial-call' ? 'input-streaming' : 'input-ready', data.args, complete ? data.result : undefined)];\n      if (data.isPreliminary === true) result.push({ type: 'data', id: `${callId}:preliminary`, name: 'preliminary-tool-result', data: data.result });\n      return result;\n    }\n    if (data.type === 'data') return [{ type: 'data' as const, id: `${id}:part:${index}`, name: readString(data.name) ?? 'stream-data', data: data.data }];\n    const mappedPart = part(value, raw, `${id}:part:${index}`, { ...options, mapPart: undefined });\n    return mappedPart ? [mappedPart] : [];\n  });\n  const status = record(raw.status);\n  return { ...message(id, 'assistant', parts, raw), ...(status.type === 'running' ? { status: 'streaming' as const } : status.type === 'incomplete' ? { status: status.reason === 'cancelled' ? 'stopped' as const : 'error' as const } : status.type === 'complete' && status.reason !== 'unknown' ? { status: 'complete' as const } : {}) };\n}\n\n/** A2A task status/artifacts stay explicit; input/auth requirements are not tool approvals. */\nexport function normalizeA2aTask(value: unknown, options: ChatNormalizeOptions = {}): readonly ChatMessage[] {\n  const task = record(value); const id = identity(value, options); const status = record(task.status);\n  const messages = [...normalizeA2aMessages([...list(task.history), ...(status.message ? [status.message] : [])], options)];\n  const taskPart: ChatPart = { type: 'data', id: `a2a-task:${id}`, name: 'a2a-task', data: { id, contextId: task.contextId, status: task.status, artifacts: task.artifacts, metadata: task.metadata } };\n  const last = messages.at(-1);\n  if (last?.actor === 'assistant') messages[messages.length - 1] = { ...last, parts: [...last.parts, taskPart] };\n  else messages.push({ id: `a2a-task:${id}`, actor: 'assistant', parts: [taskPart], metadata: { nativeTask: task } });\n  return messages;\n}\n"
    },
    {
      "path": "src/lib/chat-adapters/shared.ts",
      "type": "registry:lib",
      "target": "@lib/chat-adapters/shared.ts",
      "content": "import type {\n  ActivityEvent,\n  ChatController,\n  ChatMessage,\n  ChatAuthor,\n  ChatDelivery,\n  ChatPart,\n  ComposerSubmission,\n  InputRequestPart,\n  InputRequestController,\n  QuestionnaireResponse,\n  SourceRecord,\n  ToolPart,\n} from \"@/components/ui/chat-model\";\nimport type { ChatCapability, ChatRuntimeFeature, ChatRuntimeInput, ChatRuntimeOptions } from \"../chat-runtime\";\n\n/** A synchronous or asynchronous command supplied by the host application. */\nexport type AdapterCommand<TArgs extends readonly unknown[] = readonly []> = (\n  ...args: TArgs\n) => void | Promise<void>;\n\nexport type AdapterStatus = ChatController[\"status\"];\n\n/** Each command is bound to one application request and revision. */\nexport interface ClarificationBinding {\n  readonly requestId: string;\n  readonly revision: number;\n  readonly getCurrent: (requestId: string) => InputRequestPart | undefined;\n}\n\nexport function bindCurrentClarification(\n  binding: ClarificationBinding,\n  invoke: (response: QuestionnaireResponse) => void | PromiseLike<void>,\n): InputRequestController[\"respond\"] {\n  // A caller can render the same pending request more than once while the\n  // provider is reconciling a response. Keep one command in flight for the\n  // exact request revision. The application remains responsible for the\n  // acknowledgement state; a successful command that is still pending stays\n  // locked until a later call observes the terminal/replacement snapshot.\n  const inFlight = new Set<string>();\n  const current = (requestId: string, revision: number) => {\n    if (!binding.getCurrent || requestId !== binding.requestId || revision !== binding.revision || !Number.isSafeInteger(revision) || revision < 0) return undefined;\n    const request = binding.getCurrent(requestId);\n    return request?.id === requestId && request.revision === revision && request.kind === \"clarification\" ? request : undefined;\n  };\n  return async (requestId, revision, response) => {\n    const key = `${requestId}:${revision}`;\n    const request = current(requestId, revision);\n    if (request?.state !== \"pending\" || inFlight.has(key)) throw new Error(\"This question is no longer available for an answer.\");\n    inFlight.add(key);\n    try {\n      await invoke(response);\n    } catch (error) {\n      // A late failure belongs to the old request, never its replacement or\n      // an application-acknowledged terminal record.\n      if (current(requestId, revision)?.state !== \"pending\") {\n        inFlight.delete(key);\n        return;\n      }\n      inFlight.delete(key);\n      throw error;\n    }\n    // Only the application can acknowledge/resolve a request. Re-read the\n    // identity without turning command fulfillment into a resolved state.\n    if (current(requestId, revision)?.state !== \"pending\") inFlight.delete(key);\n  };\n}\n\nexport function validEditTarget(\n  messages: readonly unknown[],\n  messageId: string,\n  text: string,\n  status: unknown,\n  getMessage: (value: unknown) => { id?: unknown; actor?: unknown } | undefined,\n): boolean {\n  if (!messageId.trim() || !text.trim() || status === \"streaming\" || status === \"submitted\" || status === \"submitting\") return false;\n  return messages.some((value) => {\n    const message = getMessage(value);\n    return message?.id === messageId && message.actor === \"user\";\n  });\n}\n\nexport interface AdapterControllerInput {\n  readonly status?: unknown;\n  readonly error?: unknown;\n  readonly send?: AdapterCommand<[ComposerSubmission]>;\n  readonly stop?: AdapterCommand;\n  readonly retry?: AdapterCommand<[string?]>;\n  readonly editAndResubmit?: ChatController[\"editAndResubmit\"];\n}\n\n/**\n * Bind caller-owned transport commands without creating a second state\n * machine. Optional commands stay absent so a UI cannot advertise a dead\n * action. The canonical send command is required by ChatController.\n */\nexport function bindController(input: AdapterControllerInput & { send: AdapterCommand<[ComposerSubmission]> }): ChatController {\n  const status = normalizeAdapterStatus(input.status);\n  const error = toError(input.error);\n  return {\n    status,\n    ...(error ? { error } : {}),\n    send: input.send,\n    ...(input.stop ? { stop: input.stop } : {}),\n    ...(input.retry ? { retry: input.retry } : {}),\n    ...(input.editAndResubmit ? { editAndResubmit: input.editAndResubmit } : {}),\n  };\n}\n\n/** SDK-specific conversion stays at the edge; command availability is shared. */\nexport function sdkRuntimeSnapshot(messages: readonly ChatMessage[], controller: ChatController, options: ChatRuntimeOptions, retryTarget: \"latest\" | \"message\", nativeStatus: unknown, nativeAvailability: Partial<Record<ChatRuntimeFeature, boolean>> = {}): ChatRuntimeInput {\n  const known = typeof nativeStatus === \"string\" && [\"ready\", \"submitted\", \"submitting\", \"streaming\", \"error\"].includes(nativeStatus);\n  const busy = controller.status === \"submitting\" || controller.status === \"streaming\";\n  const capability = (feature: ChatRuntimeFeature, bound: boolean, available = true): ChatCapability => !known\n    ? { support: \"unknown\", reason: \"SDK status is unavailable.\" }\n    : !bound ? { support: \"unsupported\", reason: `No ${feature} integration is bound.` }\n    : { support: \"supported\", available: (nativeAvailability[feature] ?? available) && options.availability?.[feature] !== false };\n  const retry = capability(\"retry\", Boolean(controller.retry), !busy);\n  return {\n    identity: options.identity,\n    messages,\n    controller: known ? controller : { ...controller, status: \"error\", error: new Error(\"SDK status is unavailable.\") },\n    capabilities: {\n      send: capability(\"send\", true, !busy),\n      stop: capability(\"stop\", Boolean(controller.stop), busy),\n      retry: retry.support === \"supported\" ? { ...retry, target: retryTarget } : retry,\n      edit: capability(\"edit\", Boolean(controller.editAndResubmit), !busy),\n      attachments: capability(\"attachments\", Boolean(options.attachments), !busy),\n      toolApproval: capability(\"toolApproval\", Boolean(controller.respondToToolApproval)),\n      clarification: capability(\"clarification\", Boolean(options.inputRequests)),\n    },\n    ...(options.attachments ? { attachments: options.attachments } : {}),\n    ...(options.inputRequests ? { inputRequests: options.inputRequests } : {}),\n  };\n}\n\nexport function normalizeAdapterStatus(value: unknown): AdapterStatus {\n  switch (value) {\n    case \"submitted\":\n    case \"submitting\":\n      return \"submitting\";\n    case \"streaming\":\n      return \"streaming\";\n    case \"error\":\n      return \"error\";\n    case \"ready\":\n    default:\n      return \"ready\";\n  }\n}\n\nexport function toError(value: unknown): Error | undefined {\n  if (value instanceof Error) return value;\n  if (typeof value === \"string\" && value.trim()) return new Error(value);\n  return undefined;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function readString(value: unknown): string | undefined {\n  return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nexport function readFiniteNumber(value: unknown): number | undefined {\n  return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/** Only links a caller can safely hand to an anchor. No fetch or media load occurs. */\nexport function safeUrl(value: unknown): string | undefined {\n  if (typeof value !== \"string\" || !value.trim()) return undefined;\n  try {\n    const url = new URL(value);\n    return (url.protocol === \"https:\" || url.protocol === \"http:\") && url.username === \"\" && url.password === \"\" ? url.toString() : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nexport function safeFileName(value: unknown, fallback = \"Unnamed file\"): string {\n  if (typeof value !== \"string\" || !value.trim()) return fallback;\n  return value.replace(/[\\u0000-\\u001f\\u007f]/g, \"\").trim() || fallback;\n}\n\n/**\n * Stable ids use provider identities or semantic content. They never use an\n * array index, so inserting a streamed part does not move an interactive id.\n */\nexport function stableId(prefix: string, value: unknown, fallback = \"unknown\"): string {\n  const input = typeof value === \"string\" && value.trim() ? value.trim() : fallback;\n  const token = input\n    .normalize(\"NFKC\")\n    .replace(/[^a-zA-Z0-9._:-]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\")\n    .slice(0, 96);\n  return `${prefix}-${token || fallback}`;\n}\n\n/** shortcut: anonymous part IDs assume append order within their category; supply durable IDs for inserted/reordered parts. */\nexport function partIdentity(messageId: string, category: \"text\" | \"reasoning\" = \"text\"): (id: unknown) => string {\n  let count = 0;\n  return (id) => {\n    count += 1;\n    return readString(id) ?? `${stableId(category, messageId)}${count === 1 ? \"\" : `-${count}`}`;\n  };\n}\n\nexport function normalizeActor(value: unknown): ChatMessage[\"actor\"] {\n  return value === \"user\" || value === \"system\" || value === \"assistant\" ? value : \"assistant\";\n}\n\nexport function normalizeMessageId(value: unknown): { id: string; invalid: boolean } {\n  const id = readString(value);\n  return id ? { id, invalid: false } : { id: \"invalid-message\", invalid: true };\n}\n\nexport function validationPart(message: string, id = \"invalid-message\") : ChatPart {\n  return { type: \"error\", id: stableId(\"error\", id), message };\n}\n\nexport function unknownPart(originalType: string, message?: string): ChatPart {\n  return {\n    type: \"unknown\",\n    id: stableId(\"unknown\", originalType),\n    originalType,\n    ...(message ? { value: message } : {}),\n  };\n}\n\nexport function sourceRecordFrom(value: unknown, fallbackId: string): SourceRecord | undefined {\n  if (!isRecord(value)) return undefined;\n  const title = readString(value.title) ?? readString(value.name) ?? \"Untitled source\";\n  const id = readString(value.id) ?? readString(value.sourceId) ?? fallbackId;\n  const url = safeUrl(value.url);\n  const type = value.type === \"document\" || value.document ? \"document\" : \"url\";\n  const document = isRecord(value.document)\n    ? {\n        name: safeFileName(value.document.name ?? value.name),\n        ...(readFiniteNumber(value.document.page) !== undefined\n          ? { page: readFiniteNumber(value.document.page) }\n          : {}),\n        ...(readString(value.document.location) ? { location: readString(value.document.location) } : {}),\n      }\n    : type === \"document\"\n      ? { name: safeFileName(value.name ?? title) }\n      : undefined;\n  return {\n    id,\n    type,\n    title,\n    ...(url ? { url } : {}),\n    ...(readString(value.domain) ? { domain: readString(value.domain) } : {}),\n    ...(readString(value.snippet) ? { snippet: readString(value.snippet) } : {}),\n    ...(readString(value.author) ? { author: readString(value.author) } : {}),\n    ...(readString(value.publishedAt) ? { publishedAt: readString(value.publishedAt) } : {}),\n    ...(document ? { document } : {}),\n  };\n}\n\nexport function mediaPart(\n  value: Record<string, unknown>,\n  fallbackId: string,\n): ChatPart {\n  const source = value.source;\n  const sourceRecord = isRecord(source) ? source : undefined;\n  const metadata = isRecord(value.metadata) ? value.metadata : undefined;\n  const url = safeUrl(\n    value.url ??\n      (sourceRecord?.type === \"url\" ? sourceRecord.value : undefined),\n  );\n  const name = safeFileName(value.name ?? value.filename ?? value.fileName ?? value.title ?? metadata?.name ?? metadata?.filename);\n  const mediaType = readString(value.mediaType) ?? readString(value.mimeType) ?? readString(sourceRecord?.mimeType) ?? readString(metadata?.mediaType) ?? readString(metadata?.mimeType);\n  const id = readString(value.id) ?? stableId(\"file\", `${fallbackId}-${name}`);\n  return {\n    type: \"file\",\n    id,\n    name,\n    ...(mediaType ? { mediaType } : {}),\n    ...(readFiniteNumber(value.size) !== undefined ? { size: readFiniteNumber(value.size) } : {}),\n    ...(url ? { url } : {}),\n  };\n}\n\nexport type ToolMergeEntry =\n  | { kind: \"call\"; part: ToolPart }\n  | { kind: \"result\"; callId: string; output?: unknown; hasOutput: boolean; error?: string; state?: \"complete\" | \"error\" | \"streaming\"; outcome?: \"cancelled\" | \"denied\" };\n\nexport function isToolMergeEntry(value: ToolMergeEntry | ChatPart): value is ToolMergeEntry {\n  return isRecord(value) && \"kind\" in value && (value.kind === \"call\" || value.kind === \"result\");\n}\n\n/** Merge a tool result into the first matching call while retaining all other order. */\nexport function mergeToolParts(entries: readonly (ToolMergeEntry | ChatPart)[]): ChatPart[] {\n  const output: ChatPart[] = [];\n  const calls = new Map<string, ToolPart>();\n  const requests = new Map<string, InputRequestPart>();\n  for (const entry of entries) {\n    if (!isToolMergeEntry(entry)) {\n      if (entry.type === \"input-request\") {\n        const key = `${entry.id}:${entry.revision}`;\n        const existing = requests.get(key);\n        if (existing) Object.assign(existing, entry);\n        else { const copy = { ...entry }; requests.set(key, copy); output.push(copy); }\n      } else output.push(entry);\n      continue;\n    }\n    if (entry.kind === \"call\") {\n      const copy: ToolPart = { ...entry.part };\n      const existing = calls.get(copy.id);\n      if (existing) Object.assign(existing, copy);\n      else {\n        output.push(copy);\n        calls.set(copy.id, copy);\n      }\n      continue;\n    }\n    const call = calls.get(entry.callId);\n    if (!call) {\n      output.push(unknownPart(\"tool-result\", `Tool result unavailable for ${entry.callId || \"unknown call\"}.`));\n      continue;\n    }\n    if (entry.error) {\n      call.state = entry.outcome ? \"cancelled\" : \"error\";\n      call.error = entry.error;\n      if (entry.outcome === \"denied\" && call.approval) call.approval = { ...call.approval, state: \"denied\" };\n      delete call.output;\n    } else if (!entry.hasOutput && entry.state !== \"streaming\") {\n      output.push(unknownPart(\"tool-result\", `Tool result output unavailable for ${entry.callId}.`));\n    } else {\n      call.state = entry.state === \"streaming\" ? \"running\" : \"output-ready\";\n      delete call.error;\n      if (entry.hasOutput) call.output = entry.output;\n    }\n  }\n  return output;\n}\n\nexport function mapToolState(value: unknown): ToolPart[\"state\"] | undefined {\n  switch (value) {\n    case \"awaiting-input\":\n    case \"input-streaming\":\n      return value === \"awaiting-input\" ? \"input-streaming\" : \"input-streaming\";\n    case \"input-complete\":\n      return \"input-ready\";\n    case \"approval-requested\":\n      return \"approval-required\";\n    case \"approval-responded\":\n      return \"input-ready\";\n    case \"complete\":\n    case \"output-available\":\n      return \"output-ready\";\n    case \"error\":\n    case \"output-error\":\n      return \"error\";\n    case \"cancelled\":\n      return \"cancelled\";\n    case \"running\":\n    case \"input-available\":\n      return \"running\";\n    default:\n      return undefined;\n  }\n}\n\nexport function activityFromSideChannel(events: readonly ActivityEvent[] | undefined): ChatPart[] {\n  return events?.map((event) => ({ type: \"activity\", id: event.id, event })) ?? [];\n}\n\nexport interface NormalizedMessageResult {\n  readonly message: ChatMessage;\n  readonly activityGap?: string;\n}\n\nexport function finalizeMessage(\n  idValue: unknown,\n  actorValue: unknown,\n  parts: readonly ChatPart[],\n  createdAt: unknown,\n  metadata: unknown,\n  author?: ChatAuthor,\n  delivery?: ChatDelivery,\n): NormalizedMessageResult {\n  const identity = normalizeMessageId(idValue);\n  const actorIsKnown = actorValue === \"user\" || actorValue === \"assistant\" || actorValue === \"system\";\n  const inertParts = identity.invalid\n    ? parts.map((part) =>\n        part.type === \"tool\" || part.type === \"input-request\"\n          ? unknownPart(part.type, \"Interactive content is unavailable without a message identity.\")\n          : part,\n      )\n    : parts;\n  const diagnostics: ChatPart[] = [];\n  if (identity.invalid) diagnostics.push(validationPart(\"Message identity is unavailable; this record is read-only.\", identity.id));\n  if (!actorIsKnown) diagnostics.push(validationPart(\"Message role is unavailable; this record is shown as assistant content.\", identity.id));\n  const summaryIds = new Set<string>();\n  const identifiedParts = inertParts.map((part, index) => {\n    if (part.type !== \"reasoning-summary\" || !part.id) return part;\n    if (summaryIds.has(part.id)) return { ...unknownPart(\"reasoning-summary\", \"Summary identity is duplicated.\"), id: `${stableId(\"invalid-summary\", identity.id)}-${index}` };\n    summaryIds.add(part.id);\n    return part;\n  });\n  const finalParts = diagnostics.length > 0 ? [...diagnostics, ...identifiedParts] : identifiedParts;\n  const date = createdAt instanceof Date || typeof createdAt === \"string\" ? createdAt : undefined;\n  return {\n    message: {\n      id: identity.id,\n      actor: normalizeActor(actorValue),\n      ...(date ? { createdAt: date } : {}),\n      ...(author ? { author } : {}),\n      ...(delivery ? { delivery } : {}),\n      parts: finalParts,\n      ...(isRecord(metadata) ? { metadata } : {}),\n    },\n  };\n}\n"
    }
  ]
}
