{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chat-runtime",
  "type": "registry:lib",
  "title": "Chat runtime contracts and store bridge",
  "description": "Neutral conversation state and guarded commands.",
  "dependencies": [],
  "registryDependencies": [
    "https://ghost-ui.com/r/chat-model.json"
  ],
  "files": [
    {
      "path": "src/lib/chat-runtime.ts",
      "type": "registry:lib",
      "target": "@lib/chat-runtime.ts",
      "content": "import type { ChatController, ChatMessage, ComposerSubmission, InputRequestController, InputRequestPart, ToolPart } from '@/components/ui/chat-model';\n\nexport interface ChatRuntimeIdentity {\n  readonly threadId: string;\n  /** Advance when replacing the conversation/run context, including A→B→A. */\n  readonly revision: number;\n  readonly runId?: string;\n}\nexport type ChatCapability =\n  | { readonly support: 'supported'; readonly available: boolean; readonly reason?: string }\n  | { readonly support: 'unsupported' | 'unknown'; readonly reason?: string };\nexport type ChatRetryCapability =\n  | (Extract<ChatCapability, { support: 'supported' }> & { readonly target: 'latest' | 'message' })\n  | Exclude<ChatCapability, { support: 'supported' }>;\nexport interface ChatRuntimeCapabilities {\n  readonly send: ChatCapability;\n  readonly stop: ChatCapability;\n  readonly retry: ChatRetryCapability;\n  readonly edit: ChatCapability;\n  readonly attachments: ChatCapability;\n  readonly toolApproval: ChatCapability;\n  readonly clarification: ChatCapability;\n}\nexport type ChatRuntimeFeature = keyof ChatRuntimeCapabilities;\nexport interface ChatRuntimeCommandContext {\n  readonly identity: ChatRuntimeIdentity;\n  /** Check scope after asynchronous preparation, before dispatching a host effect. */\n  assertCurrent(): void;\n}\nexport interface ChatAttachmentAdapter {\n  send(submission: ComposerSubmission, context: ChatRuntimeCommandContext): void | PromiseLike<void>;\n}\nexport interface ChatRuntimeOptions {\n  readonly identity: ChatRuntimeIdentity;\n  readonly availability?: Partial<Record<ChatRuntimeFeature, boolean>>;\n  readonly attachments?: ChatAttachmentAdapter;\n  readonly inputRequests?: InputRequestController;\n}\nexport interface ChatRuntimeInput {\n  readonly identity: ChatRuntimeIdentity;\n  readonly messages: readonly ChatMessage[];\n  readonly controller: ChatController;\n  /** Omitted features remain unknown, never inferred as authorized. */\n  readonly capabilities?: Partial<ChatRuntimeCapabilities>;\n  readonly attachments?: ChatAttachmentAdapter;\n  readonly inputRequests?: InputRequestController;\n}\nexport interface ChatRuntimeSnapshot {\n  readonly identity: ChatRuntimeIdentity;\n  readonly messages: readonly ChatMessage[];\n  readonly controller: ChatController;\n  readonly capabilities: ChatRuntimeCapabilities;\n  readonly inputRequests?: InputRequestController;\n}\nexport interface ChatRuntimeSource {\n  getSnapshot(): ChatRuntimeInput;\n  subscribe(listener: () => void): () => void;\n  getServerSnapshot?(): ChatRuntimeInput;\n}\nexport interface ChatRuntimeStore {\n  getSnapshot(): ChatRuntimeSnapshot;\n  subscribe(listener: () => void): () => void;\n  getServerSnapshot?(): ChatRuntimeSnapshot;\n}\nexport interface ChatAdapter<TBinding> {\n  getSnapshot(binding: TBinding, options: ChatRuntimeOptions): ChatRuntimeInput;\n}\nexport class ChatRuntimeError extends Error {\n  constructor(readonly code: 'invalid' | 'stale' | 'unsupported' | 'unavailable' | 'duplicate', message: string) {\n    super(message);\n    this.name = 'ChatRuntimeError';\n  }\n}\nconst features: readonly ChatRuntimeFeature[] = ['send', 'stop', 'retry', 'edit', 'attachments', 'toolApproval', 'clarification'];\nconst unknown: ChatCapability = Object.freeze({ support: 'unknown' });\nconst fail = (code: ChatRuntimeError['code'], message: string): never => { throw new ChatRuntimeError(code, message); };\nfunction sameScope(a: ChatRuntimeIdentity, b: ChatRuntimeIdentity) {\n  return a.threadId === b.threadId && a.runId === b.runId && a.revision === b.revision;\n}\nfunction validate(input: ChatRuntimeInput) {\n  const id = input?.identity;\n  if (!id || typeof id.threadId !== 'string' || !id.threadId.trim() || !Number.isSafeInteger(id.revision) || id.revision < 0 || (id.runId !== undefined && (typeof id.runId !== 'string' || !id.runId.trim()))) fail('invalid', 'A stable thread identity and nonnegative revision are required.');\n  if (!Array.isArray(input.messages) || typeof input.controller?.send !== 'function') fail('invalid', 'Runtime messages and a send controller are required.');\n  if (!['ready', 'submitting', 'streaming', 'error'].includes(input.controller.status)) fail('invalid', 'Runtime status is unavailable.');\n}\nfunction capabilities(input: ChatRuntimeInput): ChatRuntimeCapabilities {\n  const handlers = { send: input.controller.send, stop: input.controller.stop, retry: input.controller.retry, edit: input.controller.editAndResubmit, attachments: input.attachments?.send, toolApproval: input.controller.respondToToolApproval, clarification: input.inputRequests?.respond };\n  const output: Partial<ChatRuntimeCapabilities> = {};\n  for (const feature of features) {\n    const value = input.capabilities?.[feature] ?? unknown;\n    if (!value || !['supported', 'unsupported', 'unknown'].includes(value.support)) fail('invalid', `Invalid ${feature} capability.`);\n    if (value.support === 'supported') {\n      if (typeof value.available !== 'boolean' || typeof handlers[feature] !== 'function') fail('invalid', `Supported ${feature} requires availability and a command.`);\n      if (feature === 'retry' && (!('target' in value) || (value.target !== 'latest' && value.target !== 'message'))) fail('invalid', 'Retry support requires a target scope.');\n    }\n    Object.assign(output, { [feature]: Object.freeze({ ...value }) });\n  }\n  return Object.freeze(output) as ChatRuntimeCapabilities;\n}\nfunction request(input: ChatRuntimeInput, id: string, revision?: number): InputRequestPart | undefined {\n  const matches = (part: InputRequestPart | undefined) => part?.id === id && (revision === undefined || part.revision === revision) ? part : undefined;\n  if (input.inputRequests?.getCurrent) return matches(input.inputRequests.getCurrent(id));\n  for (let i = input.messages.length - 1; i >= 0; i--) {\n    const parts = input.messages[i].parts;\n    for (let j = parts.length - 1; j >= 0; j--) if (parts[j].type === 'input-request' && parts[j].id === id) return matches(parts[j] as InputRequestPart);\n  }\n}\nfunction tool(input: ChatRuntimeInput, messageId: string, callId: string, approvalId: string): ToolPart | undefined {\n  for (let i = input.messages.length - 1; i >= 0; i--) {\n    const message = input.messages[i];\n    if (message.id !== messageId) continue;\n    for (let j = message.parts.length - 1; j >= 0; j--) {\n      const part = message.parts[j];\n      if (part.type === 'tool' && part.id === callId) return part.approval?.id === approvalId ? part : undefined;\n    }\n    return undefined;\n  }\n}\n\n/** Shared command projection for React snapshots and subscribed stores; it owns no messages. */\nexport function createChatRuntimeBinding(getCurrent: () => ChatRuntimeInput | undefined): (input: ChatRuntimeInput) => ChatRuntimeSnapshot {\n  type Lock = { pending: boolean; acknowledged?: (input: ChatRuntimeInput) => boolean; identity: ChatRuntimeIdentity };\n  const locks = new Map<string, Lock>();\n  return input => {\n    validate(input);\n    const identity = Object.freeze({ ...input.identity });\n    const scope = () => {\n      const current = getCurrent();\n      if (!current) return fail('stale', 'This runtime command belongs to a replaced conversation or run.');\n      validate(current);\n      if (!sameScope(identity, current.identity)) return fail('stale', 'This runtime command belongs to a replaced conversation or run.');\n      return current;\n    };\n    const available = (current: ChatRuntimeInput, feature: ChatRuntimeFeature) => {\n      const capability = capabilities(current)[feature];\n      if (capability.support !== 'supported') return fail('unsupported', capability.reason ?? `${feature} is ${capability.support}.`);\n      if (!capability.available) fail('unavailable', capability.reason ?? `${feature} is currently unavailable.`);\n    };\n    const context: ChatRuntimeCommandContext = Object.freeze({ identity, assertCurrent: () => { scope(); } });\n    const run = async (feature: ChatRuntimeFeature, target: string, operation: (current: ChatRuntimeInput) => void | PromiseLike<void>, acknowledged?: (current: ChatRuntimeInput) => boolean) => {\n      const current = scope();\n      available(current, feature);\n      for (const [key, lock] of locks) if (!lock.pending && (!sameScope(lock.identity, current.identity) || lock.acknowledged?.(current))) locks.delete(key);\n      const key = JSON.stringify([identity.threadId, identity.runId, identity.revision, feature, target]);\n      if (locks.has(key)) fail('duplicate', 'This command is already awaiting completion or acknowledgement.');\n      const lock: Lock = { pending: true, acknowledged, identity };\n      locks.set(key, lock);\n      try {\n        await operation(current);\n        lock.pending = false;\n        const next = getCurrent();\n        if (!acknowledged || !next || !sameScope(identity, next.identity) || acknowledged(next)) locks.delete(key);\n      } catch (error) {\n        locks.delete(key);\n        throw error;\n      }\n    };\n    const controller: ChatController = {\n      status: input.controller.status,\n      ...(input.controller.error ? { error: input.controller.error } : {}),\n      send: submission => run('send', '', current => {\n        if (!submission || typeof submission.text !== 'string' || !Array.isArray(submission.attachments) || (!submission.text.trim() && submission.attachments.length === 0)) fail('invalid', 'A message needs text or ready attachments.');\n        for (const file of submission.attachments) if (!file || typeof file.id !== 'string' || !file.id.trim() || typeof file.name !== 'string' || !file.name.trim() || (file.status !== undefined && file.status !== 'ready')) fail('invalid', 'Only identified, ready attachments can be sent.');\n        if (submission.attachments.length) {\n          available(current, 'attachments');\n          return current.attachments!.send({ ...submission, attachments: [...submission.attachments] }, context);\n        }\n        return current.controller.send(submission);\n      }),\n      ...(input.controller.stop ? { stop: () => run('stop', '', current => current.controller.stop!()) } : {}),\n      ...(input.controller.retry ? { retry: (messageId?: string) => run('retry', messageId ?? '', current => {\n        const capability = capabilities(current).retry;\n        if (messageId !== undefined && (capability.support !== 'supported' || capability.target !== 'message')) fail('unsupported', 'This runtime can retry only the latest response.');\n        if (messageId !== undefined && (typeof messageId !== 'string' || !messageId.trim() || !current.messages.some(message => message.id === messageId && message.actor === 'assistant'))) fail('invalid', 'The assistant retry target is unavailable.');\n        return current.controller.retry!(messageId);\n      }) } : {}),\n      ...(input.controller.editAndResubmit ? { editAndResubmit: (edit: { messageId: string; text: string }) => run('edit', edit?.messageId ?? '', current => {\n        if (typeof edit?.messageId !== 'string' || !edit.messageId.trim() || typeof edit.text !== 'string' || !edit.text.trim() || !current.messages.some(message => message.id === edit.messageId && message.actor === 'user')) fail('invalid', 'The user edit target is unavailable.');\n        return current.controller.editAndResubmit!(edit);\n      }) } : {}),\n      ...(input.controller.respondToToolApproval ? { respondToToolApproval: (decision: Parameters<NonNullable<ChatController['respondToToolApproval']>>[0]) => {\n        const pending = (current: ChatRuntimeInput) => {\n          const part = tool(current, decision.messageId, decision.toolCallId, decision.approvalId);\n          return part?.state === 'approval-required' && part.approval?.state === 'pending' && !part.approval.automatic;\n        };\n        return run('toolApproval', JSON.stringify([decision?.messageId, decision?.toolCallId, decision?.approvalId]), current => {\n          if (typeof decision?.approved !== 'boolean' || !pending(current)) fail('stale', 'This tool approval is no longer pending.');\n          return current.controller.respondToToolApproval!(decision);\n        }, current => !pending(current));\n      } } : {}),\n    };\n    const inputRequests: InputRequestController | undefined = input.inputRequests ? {\n      respond: (id, revision, response) => {\n        const pending = (current: ChatRuntimeInput) => request(current, id, revision)?.state === 'pending';\n        return run('clarification', JSON.stringify(['respond', id, revision]), current => {\n          if (!Number.isSafeInteger(revision) || revision < 0 || !pending(current)) fail('stale', 'This clarification is no longer pending.');\n          return current.inputRequests!.respond(id, revision, response);\n        }, current => !pending(current));\n      },\n      ...(input.inputRequests.cancel ? { cancel: (id: string) => run('clarification', JSON.stringify(['cancel', id]), current => {\n        const part = request(current, id);\n        if (!part || !['pending', 'submitting'].includes(part.state) || !current.inputRequests?.cancel) fail('stale', 'This clarification cannot be cancelled.');\n        return current.inputRequests!.cancel!(id);\n      }) } : {}),\n      getCurrent: id => { const current = getCurrent(); return current && sameScope(identity, current.identity) ? request(current, id) : undefined; },\n    } : undefined;\n    return Object.freeze({ identity, messages: input.messages, controller: Object.freeze(controller), capabilities: capabilities(input), ...(inputRequests ? { inputRequests: Object.freeze(inputRequests) } : {}) });\n  };\n}\n\n/** Cache projections and delegate subscriptions; the source remains the state owner. */\nexport function createChatRuntimeStore(source: ChatRuntimeSource): ChatRuntimeStore {\n  if (!source || typeof source.getSnapshot !== 'function' || typeof source.subscribe !== 'function' || (source.getServerSnapshot !== undefined && typeof source.getServerSnapshot !== 'function')) fail('invalid', 'A runtime source needs snapshot and subscription functions.');\n  const project = createChatRuntimeBinding(() => source.getSnapshot());\n  const reader = (read: () => ChatRuntimeInput) => {\n    let previous: ChatRuntimeInput | undefined;\n    let snapshot: ChatRuntimeSnapshot;\n    return () => {\n      const input = read();\n      if (input !== previous) { snapshot = project(input); previous = input; }\n      return snapshot;\n    };\n  };\n  return {\n    getSnapshot: reader(() => source.getSnapshot()),\n    subscribe: listener => source.subscribe(listener),\n    ...(source.getServerSnapshot ? { getServerSnapshot: reader(() => source.getServerSnapshot!()) } : {}),\n  };\n}\n"
    }
  ]
}
