import { BUTTON_KIND, BUTTON_SIZE } from '@carbon/web-components/es/components/button/defs.js'; import { CHAT_BUTTON_KIND, CHAT_BUTTON_SIZE } from '@carbon/ai-chat-components/es/react/chat-button.js'; import { ChainOfThoughtStepStatus } from '@carbon/ai-chat-components/es/components/chain-of-thought/defs.js'; import { ToolbarAction } from '@carbon/ai-chat-components/es/react/toolbar.js'; import { MarkdownItPlugin as MarkdownItPlugin$1, MarkdownRendererTableArgs as MarkdownRendererTableArgs$1, MarkdownRendererCodeBlockArgs as MarkdownRendererCodeBlockArgs$1, MarkdownCustomRenderers as MarkdownCustomRenderers$1, MarkdownRendererCodeBlockData as MarkdownRendererCodeBlockData$1, MarkdownRendererTableData as MarkdownRendererTableData$1, TokenTree as TokenTree$1 } from '@carbon/ai-chat-components/es/components/markdown/index.js'; import { ReactNode } from 'react'; import * as lit_html from 'lit-html'; import * as lit from 'lit'; import { LitElement, PropertyValues, PropertyDeclarations } from 'lit'; import { Root } from 'react-dom/client'; /** * An enum of all of our data-testid we use. For some elements (like INPUT) they can appear in multiple "panels" * (e.g. on the home screen and in the main chat window). There are provided testids for "panels" as well so you * can first select a panel and then select the correct child. * * This extends the base PageObjectId from @carbon/ai-chat-components to include application-level test IDs. * * @category Testing * * @experimental */ declare enum PageObjectId { /** * Chat header container element (from @carbon/ai-chat-components). */ CHAT_HEADER = "chat_header", /** * Header title element (from @carbon/ai-chat-components). */ HEADER_TITLE = "header_title", /** * Header name element (from @carbon/ai-chat-components). */ HEADER_NAME = "header_name", /** * The root chat widget container (for scoping tests/accessibility checks). */ CHAT_WIDGET = "chat_widget", /** * Minimize chat button in header. */ CLOSE_CHAT = "close_chat", /** * The launcher button to open the chat. This id is maintained across desktop and mobile launchers. */ LAUNCHER = "launcher_open_chat", /** * Input field. */ INPUT = "input_field", /** * Input send button. */ INPUT_SEND = "input_send", /** * The main chat messages list. */ MAIN_PANEL = "main_panel", /** * Disclaimer panel. */ DISCLAIMER_PANEL = "disclaimer_panel", /** * Disclaimer accept button. */ DISCLAIMER_ACCEPT_BUTTON = "disclaimer_accept_button", /** * Homescreen Panel. */ HOME_SCREEN_PANEL = "home_screen_panel", /** * Hydration/loading state panel. */ HYDRATING_PANEL = "hydrating_panel", /** * Catastrophic error panel. */ CATASTROPHIC_PANEL = "catastrophic_panel", /** * Iframe panel. */ IFRAME_PANEL = "iframe_panel", /** * Conversational search panel. */ CONVERSATIONAL_SEARCH_CITATION_PANEL = "conversational_search_citation_panel", /** * Custom panel. */ CUSTOM_PANEL = "custom_panel", /** * A panel that opens from a button response. */ BUTTON_RESPONSE_PANEL = "button_response_panel" } /** * Ids used for data-testid. * * @category Testing * * @experimental */ type TestId = PageObjectId; /** * Whether a particular Carbon AI Chat view is visible or not. * * @category Instance */ interface ViewState { /** * Whether the launcher is visible or not. */ launcher: boolean; /** * Whether the main window is visible or not. */ mainWindow: boolean; } /** * The different views that can be shown by Carbon AI Chat. * * @category Instance */ declare enum ViewType { /** * The launcher view is used to open the main window. */ LAUNCHER = "launcher", /** * The main window view is used to ask WA questions and converse with an agent, as well as many other things. The * string value is kept camel case to align with the viewState mainWindow property. */ MAIN_WINDOW = "mainWindow" } /** * Describes the different panel types that Carbon AI Chat supports. * * @category Instance */ declare enum PanelType { /** * Opens the panel so that it overlays the main chat content. */ DEFAULT = "default", /** * Opens the panel in the Workspace layout. * * On large screens, the panel is placed at the `preferredLocation` (`start` or `end`) * and pushes the chat content. * * On small screens, the panel behaves like `DEFAULT`. * * @experimental */ WORKSPACE = "workspace", /** * Opens the history panel. * * The history panel only appears in the chat panel when * config.history.isMobile is true. * * @experimental */ HISTORY = "history" } /** * This manager handles fetching an instance for manipulating the custom panel. * * @category Instance */ interface CustomPanels { /** * Gets a custom panel instance. */ getPanel: (panel?: PanelType) => CustomPanelInstance; } /** * The custom panel instance for controlling and manipulating a custom panel in Carbon AI Chat. * * @category Instance */ interface CustomPanelInstance { /** * The custom panel hostElement. */ hostElement?: HTMLDivElement | undefined; /** * Opens the custom panel. * * @param options Custom panel options. */ open: (options?: CustomPanelOpenOptions) => Promise; /** * Closes the custom panel. */ close: () => Promise; } /** * Options that change how the custom panel looks. When a header is shown, it inherits styling and behavior from the * configured {@link HeaderConfig} (title, assistant name, AI slug, minimize button style, overflow menu, etc.) unless * explicitly overridden below. * * @category Instance * * @deprecated Use {@link DefaultCustomPanelConfigOptions} for default panels. * */ interface CustomPanelConfigOptions { /** * The panel title displayed in the custom panel header. Left blank by default which causes the configured chat header * title/name to be shown instead. When a back button is visible the inherited header stays on screen above the panel * so this title acts like a breadcrumb; when the back button is hidden, the header fills the panel chrome and this * title becomes the primary heading within the overlay. */ title?: string; /** * Indicates if the close/minimize button in the custom panel should be hidden. * * @deprecated Use {@link DefaultCustomPanelConfigOptions} for default panels. */ hideCloseButton?: boolean; /** * Indicates if the panel header should be hidden. Hiding the header removes the inherited title, AI slug, minimize * button, and back button chrome entirely. Leave this undefined to animate the panel in with the standard header; set * it to true when you need a chrome-free experience (for example, when the panel content provides its own close * controls or you want the panel to cover the chat header without animating the header into view). * * @deprecated Use {@link DefaultCustomPanelConfigOptions} for default panels. */ hidePanelHeader?: boolean; /** * Indicates if the back button in the custom panel should be hidden. When {@link hidePanelHeader} is true, the back * button is hidden automatically. When the back button is visible the panel opens beneath the chat header so users * can always access the assistant-level header controls while the panel is active. */ hideBackButton?: boolean; /** * Called when the header's close/minimize button is clicked. By default Carbon AI Chat will run its normal close * behavior (which collapses the experience) before this callback fires; set {@link disableDefaultCloseAction} to true * if you plan to intercept the event and manage closing yourself. The callback still fires even when the default * action is disabled. * * @deprecated Use {@link DefaultCustomPanelConfigOptions} for default panels. */ onClickClose?: () => void; /** * Called when the restart button in the header is clicked. Use this to trigger a conversation reset or your own * telemetry when the restart control is surfaced. * * @deprecated Use {@link DefaultCustomPanelConfigOptions} for default panels. */ onClickRestart?: () => void; /** * Called after the header's back button is clicked. The panel automatically closes before this callback is invoked, * so you can safely run follow-up logic or analytics once the panel has been dismissed. * * @deprecated Use {@link DefaultCustomPanelConfigOptions} for default panels. */ onClickBack?: () => void; /** * Determines if the panel open/close animation should be turned off. */ disableAnimation?: boolean; /** * Disables the default action that is taken when the close button is clicked. Normally clicking the close/minimize * button will run Carbon AI Chat's standard close routine (after verifying no view change is in progress). Set this * to true when you want to keep the experience open or handle closing asynchronously; you'll need to perform the * desired close work inside {@link onClickClose}. * * @deprecated Use {@link DefaultCustomPanelConfigOptions} for default panels. */ disableDefaultCloseAction?: boolean; } /** * Options supported by the default custom panel implementation. * * When {@link hideBackButton} is set to true, any {@link title} value defined here will override the title/name in * the main chat header. * * @category Instance */ interface DefaultCustomPanelConfigOptions { /** * The panel title displayed in the custom panel header. When a back button is visible the inherited header remains * on screen above the panel so this title acts like a breadcrumb; when the back button is hidden, the header fills * the panel chrome and this title becomes the primary heading within the overlay. */ title?: string; /** * Determines if the panel open/close animation should be turned off. By default, the panel will animate up from the * bottom of the chat window. */ disableAnimation?: boolean; /** * Indicates if the back button in the custom panel should be hidden. */ hideBackButton?: boolean; /** * Controls the icon used for the back button. Use "minimize" to indicate the * panel can be returned to, or "close" to indicate the panel will not return. */ backButtonType?: "minimize" | "close"; /** * Shows the AI gradient background on your panel. Can be used with in concert with showFrame. */ aiEnabled?: boolean; /** * Show a frame with the chat shell background instead of the gradient background for your panel content. */ showFrame?: boolean; /** * By default, the panel will render at the width of the messages list. If you want to be able to render to a full screen * width slot, set fullWidth to true. */ fullWidth?: boolean; } /** * Options supported by the workspace custom panel implementation. * * @category Instance */ interface WorkspaceCustomPanelConfigOptions { /** * The title of the workspace. Used for accessibility announcements. */ title?: string; /** * Where the chat will attempt to render the workspace in logical terms. For a ltr layout "start" will render on the left and "end" will render on the right. If there is not enough room to render the workspace, it will be rendered as a panel overlaying the content with a back button. */ preferredLocation?: "start" | "end"; /** * The ID of the workspace being opened. This will be included in WORKSPACE_PRE_CLOSE and WORKSPACE_CLOSE events. */ workspaceId?: string; /** * Additional metadata associated with the workspace. This will be included in WORKSPACE_PRE_CLOSE and WORKSPACE_CLOSE events. */ additionalData?: unknown; } /** * Options accepted by {@link CustomPanelInstance.open}. Legacy consumers may continue to pass * {@link CustomPanelConfigOptions} until the next major release. * * @category Instance */ type CustomPanelOpenOptions = CustomPanelConfigOptions | DefaultCustomPanelConfigOptions | WorkspaceCustomPanelConfigOptions; /* * Copyright IBM Corp. 2025 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * @license */ /** * Utility type that makes all properties in T optional recursively. * * This type is useful for configuration objects where you want to allow * partial updates to nested object structures. It recursively applies * the optional modifier (?) to all properties, including nested objects. * * @template T - The type to make deeply partial * * @example * ```typescript * interface Config { * server: { * host: string; * port: number; * }; * database: { * url: string; * timeout: number; * }; * } * * // All properties become optional, including nested ones * const partialConfig: DeepPartial = { * server: { * host: "localhost" // port is optional * } * // database is optional entirely * }; * ``` * * @category Utilities */ type DeepPartial = { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P]; }; /** * The different type of error states a given message can be in. * * @category Messaging */ declare enum MessageErrorState { /** * No errors. */ NONE = 1, /** * The message failed to be sent and no more attempts will be made. */ FAILED = 2, /** * The message failed while streaming. */ FAILED_WHILE_STREAMING = 3, /** * There was an error sending the message but the system is retrying the message. */ RETRYING = 4, /** * Indicates that the previous message has entered the retrying state and that this message is waiting for it to * finish or fail. This message will remain in the waiting state until it finishes successfully or it enters a * retrying state itself. */ WAITING = 5 } /** * Constants for the Carbon FileStatus type because they weren't kind enough to include their own enum. * * @category Service desk */ declare enum FileStatusValue { COMPLETE = "complete", EDIT = "edit", UPLOADING = "uploading", SUCCESS = "success" } /** * An interface that represents a file to upload and its current upload status. * * @category Service desk */ interface FileUpload { /** * A unique ID for the file. */ id: string; /** * The file to upload. */ file: File; /** * The current upload status. */ status: FileStatusValue; /** * Indicates if the file contains an error or failed to upload. */ isError?: boolean; /** * If the file failed to upload, this is an optional error message to display. */ errorMessage?: string; } /** * The section of the public config that contains configuration options for service desk integrations. * * @category Service desk */ interface ServiceDeskPublicConfig { /** * The timeout value in seconds to use when determining agent availability. When a connect_to_agent response is * received, the system will ask the service desk if any agents are available. If no response is received within * the timeout window, the system will return "false" to indicate no agents are available. */ availabilityTimeoutSeconds?: number; /** * Indicates if Carbon AI Chat should auto-connect to an agent whenever it receives a connect_to_agent response and * agents are available. This essentially mimics the user clicking the "Request agent" button on the card. The * card is still displayed to the user. */ skipConnectHumanAgentCard?: boolean; /** * The timeout value is seconds to use when waiting for an agent to join the chat after an agent has been * requested. If no agent joins after this time, the chat will be ended and an error message will be displayed to * the user. By default, there is no timeout. */ agentJoinTimeoutSeconds?: number; /** * Indicates if Carbon AI Chat should automatically attempt to reconnect the user to a human agent when it is loaded. This * only works if the service desk integration being used supports reconnecting. This value defaults to true. */ allowReconnect?: boolean; } /** * Represents the different states for the availability of a human agent from a service desk. * * @category Service desk */ declare enum HumanAgentsOnlineStatus { /** * Indicates that agents are online. */ ONLINE = "online", /** * Indicates that no agents are online. */ OFFLINE = "offline", /** * Indicates that it is unknown whether any agents are available. This may be because the service desk being used * doesn't support the ability to determine this information. */ UNKNOWN = "unknown" } /** * The parameters that are passed to a service desk factory. * * @category Service desk */ interface ServiceDeskFactoryParameters { /** * The callback used by the service desk to communicate with the widget. */ callback: ServiceDeskCallback; /** * The instance of Carbon AI Chat. */ instance: ChatInstance; /** * Any state that was stored for the service desk. This value may be undefined if no state has been stored. */ persistedState: unknown; } /** * This interface represents the operations that a service desk integration can call on Carbon AI Chat when it wants web * chat to do something. When a service desk integration instance is created, Carbon AI Chat will provide an * implementation of this interface to the integration for it to use. * * @category Service desk */ interface ServiceDeskCallback { /** * Updates Carbon AI Chat with the capabilities supported by the service desk. Some of these capabilities may support * being changed dynamically and can be updated at any time. * * @param capabilities The set of capabilities to update. Only properties that need to be changed need to be included. */ updateCapabilities(capabilities: Partial): void; /** * Sends updated availability information to the chat widget for a user who is waiting to be connected to an * agent (e.g. the user is number 2 in line). This may be called at any point while waiting for the connection to * provide newer information. * * Note: Of the fields in the AgentAvailability object, only one of positionInQueue and estimatedWaitTime can be * rendered in the widget. If both fields are provided, estimatedWaitTime will take priority and the * positionInQueue field will be ignored. * * @param availability The availability information to display to the user. */ updateAgentAvailability(availability: AgentAvailability): Promise; /** * Informs the chat widget that an agent has joined the chat. */ agentJoined(profile: ResponseUserProfile): Promise; /** * Informs the chat widget that the agent has read all the messages that have been sent to the service desk. */ agentReadMessages(): Promise; /** * Tells the chat widget if an agent has started or stopped typing. * * @param isTyping If true, indicates that the agent is typing. False indicates the agent has stopped typing. */ agentTyping(isTyping: boolean): Promise; /** * Sends a message to the chat widget from an agent. * * Note: The text response type from the standard Watson API is supported in addition to the Carbon AI Chat specific * MessageResponseTypes.INLINE_ERROR response type. * * @param message The message to display to the user. Note, the ability to pass a string for the message was added in * Carbon AI Chat 6.7.0. Earlier versions of Carbon AI Chat will not work if you pass just a string. * @param agentID The ID of the agent who is sending the message. If this is not provided, then the ID of the last * agent who joined the conversation will be used. */ sendMessageToUser(message: MessageResponse | string, agentID?: string): Promise; /** * Informs the chat widget that a transfer to another agent is in progress. The agent profile information is * optional if the service desk doesn't have the information available. This message simply tells the chat widget * that the transfer has started. The service desk should inform the widget when the transfer is complete by * sending a {@link agentJoined} message later. */ beginTransferToAnotherAgent(profile?: ResponseUserProfile): Promise; /** * Informs the chat widget that the agent has left the conversation. This does not end the conversation itself, * rather the only action that occurs is the visitor receives the agent left status message. If the user sends * another message, it is up to the service desk to decide what to do with it. */ agentLeftChat(): Promise; /** * Informs the chat widget that the agent has ended the conversation. */ agentEndedChat(): Promise; /** * Sets the state of the given error type. * * @param errorInfo Details for the error whose state is being set. */ setErrorStatus(errorInfo: ServiceDeskErrorInfo): Promise; /** * Updates the status of a file upload. The upload may either be successful or an error may have occurred. The * location of a file upload may be in one of two places. The first occurs when the user has selected a file to be * uploaded but has not yet sent the file. In this case, the file appears inside the Carbon AI Chat input area. If an * error is indicated on the file, the error message will be displayed along with the file and the user must * remove the file from the input area before a message can be sent. * * The second occurs after the user has sent the file and the service desk has begun to upload the file. In this * case, the file no longer appears in the input area but appears as a sent message in the message list. If an * error occurs during this time, an icon will appear next to the message to indicate an error occurred and an * error message will be added to the message list. * * @param fileID The ID of the file upload to update. * @param isError Indicates that the upload has an error or failed to upload. * @param errorMessage An error message to display along with a file in error. */ setFileUploadStatus(fileID: string, isError?: boolean, errorMessage?: string): Promise; /** * Requests that the user share their screen with the agent. This will present a modal dialog to the user who must * respond before continuing the conversation. This method returns a Promise that resolves when the user has * responded to the request or the request times out. * * @returns Returns a Promise that will resolve with the state the of the request. This Promise will reject if no * chat with an agent is currently running. */ screenShareRequest(): Promise; /** * Informs Carbon AI Chat that a screen sharing session has ended or been cancelled. This may occur while waiting for a * screen sharing request to be accepted or while screen sharing is in progress. */ screenShareEnded(): Promise; /** * Returns the persisted agent state from the store. This is the current state as updated by * {@link updatePersistedState}. The object returned here is frozen and may not be modified. */ persistedState(): TPersistedStateType; /** * Allows the service desk to store state that may be retrieved when Carbon AI Chat is reloaded on a page. This information * is stored in browser session storage which has a total limit of 5MB per origin so the storage should be used * sparingly. Also, the value provided here must be JSON serializable. * * When Carbon AI Chat is reloaded, the data provided here will be returned to the service desk via the * ServiceDeskFactoryParameters.persistedState property. This data may also be retrieved by using the * {@link persistedState} method. * * @param state The state to update. * @param mergeWithCurrent Indicates if the new state should be merged into the existing state. If false, then the * existing state will be fully replaced with the new state. Merging with existing state expects the state to be * an object. This argument is true by default. */ updatePersistedState(state: DeepPartial, mergeWithCurrent?: boolean): void; } /** * The set of capabilities and parameters that are supported by the service desk. * * @category Service desk */ type ServiceDeskCapabilities = FileUploadCapabilities; /** * The possible state changes for a screen sharing request. * * @category Service desk */ declare enum ScreenShareState { /** * Indicates the screen sharing was accepted by the user. */ ACCEPTED = "accepted", /** * Indicates the screen sharing was declined by the user. */ DECLINED = "declined", /** * Indicates the screen sharing request was cancelled. */ CANCELLED = "cancelled", /** * Indicates that screen sharing has ended. */ ENDED = "ended" } /** * Information about the current availability of an agent while a user is waiting to be connected. If these are not set * the Carbon AI Chat will provide generic messaging letting the user know that a request for an agent has been sent. * * Note that only one of these fields will be used by Carbon AI Chat if more than one has been assigned a value. Priority * first goes to estimatedWaitTime, then positionInQueue, and then message. * * @category Service desk */ interface AgentAvailability { /** * The current position of the user in a queue. E.g. "You are number 2 in line." */ positionInQueue?: number; /** * The estimated wait time for the user in minutes. E.g. "Current wait time is 2 minutes." */ estimatedWaitTime?: number; /** * A custom message to display to the user containing the updated status. This may contain markdown. */ message?: string; } /** * The possible events that may have some form of error status. * * @category Service desk */ declare enum ErrorType { /** * This error is meant to be displayed while the user is attempting to connect to a service desk and before an * agent has joined. If this error is generated by the service desk, it is expected that the service desk will * treat the chat as having ended (or never started). */ CONNECTING = 1, /** * This is used to indicate the state of errors that can happen any time during a chat where the service desk * implementation has lost a connection to the back-end. If this error occurs while the user is waiting for an * agent to join, it will be treated as a {@link ErrorType.CONNECTING} error instead. */ DISCONNECTED = 2, /** * This error is used to report when there was an error sending a message to the agent. */ USER_MESSAGE = 3 } /** * This is the parent interface for the information passed to {@link ServiceDeskCallback#setErrorStatus}. It is used * as a discriminating union where the {@link #type} property is the discriminating value that determines which * child interface is to be used. * * @category Service desk */ interface BaseErrorInfo { /** * An optional value that will be logged to the console as an error. */ logInfo?: unknown; } /** * This error is meant to be displayed while the user is attempting to connect to a service desk and before an * agent has joined. If this error is generated by the service desk, it is expected that the service desk will * treat the chat as having ended (or never started). * * @category Service desk */ interface ConnectingErrorInfo extends BaseErrorInfo { /** * The discriminating value for this type. */ type: ErrorType.CONNECTING; /** * An optional message that is displayed to the user in the assistant view. If this value is not provided, a default * message will be shown instead. * * Note that support for this field was added in Carbon AI Chat 6.7.0. It will be ignored in earlier versions. */ messageToUser?: string; } /** * This is used to indicate the state of errors that can happen any time during a chat where the service desk * implementation has lost a connection to the back-end. If this error occurs while the user is waiting for an * agent to join, it will be treated as a {@link ErrorType.CONNECTING} error instead. * * @category Service desk */ interface DisconnectedErrorInfo extends BaseErrorInfo { /** * The discriminating value for this type. */ type: ErrorType.DISCONNECTED; /** * Indicates if the service desk has become disconnected. A value of true can be passed that will indicate that a * previous disconnection is over and the service desk is now connected again. */ isDisconnected: boolean; } /** * This error is used to report when there was an error sending a message to the agent. * * @category Service desk */ interface UserMessageErrorInfo extends BaseErrorInfo { /** * The discriminating value for this type. */ type: ErrorType.USER_MESSAGE; /** * The ID of the message that is in error. */ messageID: string; } /** * The type for the information passed to {@link ServiceDeskCallback#setErrorStatus}. It is a discriminating union * where the type property is the discriminating value that determines which child interface is to be used. * * @category Service desk */ type ServiceDeskErrorInfo = ConnectingErrorInfo | DisconnectedErrorInfo | UserMessageErrorInfo; /** * Additional options that may be passed to the service desk when a chat is started. * * @category Service desk */ interface StartChatOptions { /** * Some arbitrary payload of data that was provided as part of the "human_agent:pre:startChat" event. */ preStartChatPayload: TPayloadType; } /** * Additional info that may be provided when a chat is ended. * * @category Service desk */ interface EndChatInfo { /** * Before a chat is ended, a {@link BusEventType.HUMAN_AGENT_PRE_END_CHAT} is fired. The payload value assigned to this * event by a listener is provided here. */ preEndChatPayload: TPayloadType; /** * Indicates if the chat was ended by the agent (or by the service desk integration). If false, indicates the chat * was ended by the user or by Carbon AI Chat. */ endedByHumanAgent: boolean; } /** * This is a set of additional data that may be included when the user sends a message to an agent. * * @category Service desk */ interface AdditionalDataToAgent { /** * A set of files that user has selected to upload to an agent. This value may be undefined if there are no files * to upload. */ filesToUpload?: FileUpload[]; } /** * This is the public interface for a human agent service desk integration. This is the interface between the chat * widget and the implementation of the human agent interface with one of the various supported service desks. * * @category Service desk */ interface ServiceDesk { /** * Returns a name for this service desk integration. This value should reflect the service desk that is being * integrated to (e.g. "genesys web messenger"). This information will be reported to IBM and may be used to gauge * interest in various service desks for the possibility of creating fully supported out-of-the-box implementations. * * This value is required for custom service desks and may have a maximum of 40 characters. */ getName?: () => string; /** * Instructs the service desk to start a new chat. This will be called when a user requests to connect to an agent * and Carbon AI Chat initiates the process (typically when the user clicks the button on the "Connect to Agent" card). * It will make the appropriate calls to the service desk to start the chat and will make use of the callback to * inform Carbon AI Chat when an agent joins or messages are received. * * This may be called multiple times by Carbon AI Chat. If a user begins a chat with an agent, ends the chat and then * begins a new chat with an agent, this function will be called again. * * If the integration is unable to start a chat (such as if the service desk is down or no agents are available) * then this function should throw an error to let Carbon AI Chat know that the chat could not be started. * * The {@link areAnyAgentsOnline} function is called before this function is called and is called as soon as a * "connect_to_agent" message has been received from the assistant. This determines if the "Connect to Agent" card * should be displayed to the user or if the "no agents are available" message configured in the skill should be * shown instead. * * @param connectMessage The original server message response that caused the connection to an agent. It will * contain specific information to send to the service desk as part of the connection. This can include things * like a message to display to a human agent. * @param startChatOptions Additional configuration for startChat. * @returns Returns a Promise that resolves when the service desk has successfully started a new chat. This does * not necessarily mean that an agent has joined the conversation or has read any messages sent by the user. */ startChat: (connectMessage: MessageResponse, startChatOptions: StartChatOptions) => Promise; /** * Tells the service desk to terminate the chat. * * @param info Additional info that may be provided as part of ending the chat. * @returns Returns a Promise that resolves when the service desk has successfully handled the call. */ endChat: (info: EndChatInfo) => Promise; /** * Sends a message to the agent in the service desk. Note that the message text may be empty if the user has * selected files to upload and has not chosen to include a message to go along with the files. * * @param message The message from the user. * @param messageID The unique ID of the message assigned by the widget. * @param additionalData Additional data to include in the message to the agent. * @returns Returns a Promise that resolves when the service desk has successfully handled the call. */ sendMessageToAgent: (message: MessageRequest, messageID: string, additionalData: AdditionalDataToAgent) => Promise; /** * Tells the service desk if a user has started or stopped typing. * * @param isTyping If true, indicates that the user is typing. False indicates the user has stopped typing. * @returns Returns a Promise that resolves when the service desk has successfully handled the call. * @since 5.1.1 */ userTyping?: (isTyping: boolean) => Promise; /** * Informs the service desk that the user has read all the messages that have been sent by the service desk. * * @returns Returns a Promise that resolves when the service desk has successfully handled the call. */ userReadMessages?: () => Promise; /** * Checks if any agents are online and can connect to a user when they become available. This does not necessarily * mean that an agent is immediately available; when a chat is started, the user may still have to wait for an * agent to become available. The callback function {@link ServiceDeskCallback.updateAgentAvailability} is used to * give the user more up-to-date information while they are waiting for an agent to become available. * * @param connectMessage The message that contains the transfer_info object that may be used by the service desk, * so it can perform a more specific check. * @returns True if some agents are available or false if no agents are available. This may also return null which * means the availability status of agents is unknown or the service desk doesn't support this information. */ areAnyAgentsOnline?: (connectMessage: MessageResponse) => Promise; /** * Indicates that the user has selected some files to be uploaded but that the user has not yet chosen to send * them to the agent. This method can use this as an opportunity to perform any early validation of the files in * order to display an error to the user. It should not actually upload the files at this point. If the user * chooses to send the files to the agent, they will be included later when {@link ServiceDesk#sendMessageToAgent} is called. * * This method may be called multiple times before a user sends the files. * * If there are errors in the files, this method should use {@link ServiceDeskCallback#setFileUploadStatus} to update * the status with an error message. The user will not be able to upload any files until any files in error are * removed. */ filesSelectedForUpload?: (uploads: FileUpload[]) => void; /** * Tells the service desk that the user has requested to stop sharing their screen. */ screenShareStop?: () => Promise; /** * This will be called when the service desk is first initialized and it is determined that the user was previously * connected to an agent. This function should perform whatever steps are necessary to reconnect the user. Web chat * will assume the user is permitted to send messages and is connected to the same agent when this function resolves. * * @returns true to indicate that the reconnect was successful. */ reconnect?: () => Promise; } /** * This file contains the generic types for the API between a general chat widget and a chat back-end. It is * intended to provide base types for a standalone widget and should not contain any imports of other types. */ /** * This is the main interface that represents a request from a user sent to an assistant. * * @category Messaging */ interface MessageRequest { /** * The unique identifier for this request object. This value may be assigned by the client when a request is * made but should be assigned by the service if one is not provided. */ id?: string; /** * The history information to store as part of this request. This includes extra information that was provided to * the user and about the user that was used in making the request. */ history?: MessageRequestHistory; /** * The input data to the back-end to make in this request. */ input: TInputType; /** * Optional context which is added from external resources. */ context?: unknown; /** * The ID of the thread this request belongs to. This is here to prepare for input message editing and regenerating * responses. */ thread_id?: string; /** * The parent ID of the thread this request belongs to. This is here to prepare for input message editing and regenerating * responses. */ parent_thread_id?: string; } /** * The set of possible message input types in a request. * * @category Messaging */ declare enum MessageInputType { /** * Represents a simple text message. */ TEXT = "text", /** * Represents an event message that can be used to send control, updates, or action information to the back-end. */ EVENT = "event" } /** * @category Messaging */ interface BaseMessageInput { /** * The type of user input. */ message_type?: MessageInputType; } /** * Base interface for an event message that can be used to send control, updates, or action information to the back-end. * * @category Messaging */ interface EventInput extends BaseMessageInput { /** * Event messages have this as their input type. */ message_type: MessageInputType.EVENT; /** * The type of the event. */ event: TEventInputType; } /** * Input for an event. The name of the event is mandatory. Additional fields depend on the event. * * @template TNameType The type of the name property for the event. This can just be a string or it can be a * specific string in order to create type safety ensuring each event has the right name (e.g. "typeof MY_EVENT_NAME"). * * @category Messaging */ interface EventInputData { /** * The name of the event. */ name: TNameType; } /** * The type of a structured field. * * @experimental * @category Messaging */ type StructuredFieldType = "text" | "textarea" | "number" | "boolean" | "select" | "multi_select" | "date" | "datetime" | "file" | "unknown"; /** * Represents an inline file — the actual File object to be uploaded. * Use this when the file needs to be uploaded as part of the message send. * The widget passes this through to customSendMessage unchanged; actual upload * handling is the responsibility of the customSendMessage implementation. * * @experimental * @category Messaging */ interface InlineFile { /** * Type discriminator. */ type: "inline"; /** * The actual File object. */ file: File; /** * Optional unique ID for tracking. */ id?: string; /** * Optional upload status (for UI feedback). */ status?: FileStatusValue; /** * Optional error information. */ error?: { message: string; }; } /** * Represents an external file reference — a file already uploaded elsewhere. * Use this when files are uploaded separately and you just need to reference them. * * @experimental * @category Messaging */ interface ExternalFileReference { /** * Type discriminator. */ type: "reference"; /** * File identifier (could be a database ID, UUID, etc.). */ id: string; /** * Optional URL to the file. */ url?: string; /** * Optional filename for display. */ name?: string; /** * Optional MIME type. */ mime_type?: string; /** * Optional file size in bytes. */ size?: number; } /** * Represents a file value in a structured field. Can be either an inline File * object or a reference to an already-uploaded file. * * @experimental * @category Messaging */ type FileFieldValue = InlineFile | ExternalFileReference; /** * The value of a structured field. The actual type depends on the field's * {@link StructuredFieldType}. * * @experimental * @category Messaging */ type StructuredFieldValue = string | number | boolean | string[] | FileFieldValue | FileFieldValue[] | any; /** * A single typed field within a {@link StructuredData} payload. * * @experimental * @category Messaging */ interface StructuredField { /** * Unique identifier for this field. */ id: string; /** * Human-readable label (optional). */ label?: string; /** * The type of field. */ type?: StructuredFieldType; /** * The value of the field. */ value: StructuredFieldValue; } /** * Structured data that can be sent alongside or instead of plain text input. * Supports typed fields for common input patterns (text, select, multi-select, * file, etc.) as well as an escape hatch for arbitrary user-defined data. * * @experimental * @category Messaging */ interface StructuredData { /** * Typed fields with known structures (recommended for most use cases). */ fields?: StructuredField[]; /** * Escape hatch: arbitrary key-value data for user-defined implementations. */ user_defined?: Record; } /** * The default interface for message input that is sent to an assistant in a message request. This represents basic text * input. * * @category Messaging */ interface MessageInput extends BaseMessageInput { /** * The text of the user input to send to the back-end. */ text?: string; /** * For messages that are sent between the user and a human agent, we assign an agent type to the message to distinguish what type it is. */ agent_message_type?: HumanAgentMessageType; /** * Structured data that can be sent alongside or instead of plain text input. * Supports typed fields (text, select, multi-select, file, etc.) and an * escape hatch for arbitrary user-defined data. * * @experimental */ structured_data?: StructuredData; } /** * This interface represents the main response content that is received by a client from an assistant. It is generally * in response to a previous message request. * * @category Messaging */ interface MessageResponse { /** * A unique identifier for this response object. */ id?: string; /** * The id of the request that this is the response of. */ request_id?: string; /** * The output from the back-end to be rendered or processed by the client. */ output: MessageOutput; /** * The context information returned by the back-end. */ context?: unknown; /** * The ID of the thread this request belongs to. This is here to prepare for input message editing and regenerating * responses. */ thread_id?: string; /** * The history information to store as part of this request. */ history?: MessageResponseHistory; /** * Options for the {@link MessageResponse}. This includes metadata about the user or assistant sending this response. */ message_options?: MessageResponseOptions; } /** * The output context for a message response from an assistant. * * @category Messaging */ interface MessageOutput { /** * Responses intended to be processed by a generic channel. This will be an array of message response items. */ generic?: TGenericType; } /** * The set of possible message types in a response. * * @category Messaging */ declare enum MessageResponseTypes { /** * Represents a basic text response. The given text may contain rich content such as markdown. */ TEXT = "text", /** * A response that requests the user choose an option from a list. The list of options may be presented as a list * of buttons or it may be from a drop-down. */ OPTION = "option", /** * Indicates that the conversation should be escalated to a human agent and offers that opportunity to the user. */ CONNECT_TO_HUMAN_AGENT = "connect_to_agent", /** * Displays an image to the user. */ IMAGE = "image", /** * Indicates that the chat should display a pause at this point in the conversation before displaying additional * items. */ PAUSE = "pause", /** * A user defined response will be displayed according to custom logic in the client. */ USER_DEFINED = "user_defined", /** * Displays the contents of an iframe to the user. */ IFRAME = "iframe", /** * Displays a video to the user using a video player. */ VIDEO = "video", /** * Displays an audio clip to the user using an audio player. */ AUDIO = "audio", /** * Asks the user to provide a date. This may result in a date picker being presented to the user. */ DATE = "date", /** * Displays a general error message to the user and include developer info to be logged and to debug. */ INLINE_ERROR = "inline_error", /** * Displays a card that can contain other response types. */ CARD = "card", /** * Displays a carousel of cards that can contain other response types. */ CAROUSEL = "carousel", /** * Displays a button that can either send a message back to the backend, open a url, or throw a client side event. */ BUTTON = "button", /** * Ability to layout response types inside a grid. */ GRID = "grid", /** * Ability to show citations on your RAG result. */ CONVERSATIONAL_SEARCH = "conversational_search", /** * Displays a preview card that can take the user flow to a workspace view. */ PREVIEW_CARD = "preview_card", /** * Displays a system message to the user. System messages appear centered between other messages * and are styled differently to indicate they are not from the user or assistant. * * If a response contains ONLY system messages, they render standalone (no avatar, no bubble). * If mixed with other response types, system messages render inline within the message bubble. * * @example * ```typescript * // Standalone system message * { * output: { * generic: [{ * response_type: "system", * text: "Processing your request...", * }] * } * } * * // Inline system message (mixed with other content) * { * output: { * generic: [ * { response_type: "text", text: "Starting analysis..." }, * { response_type: "system", text: "Processing 1000 records" }, * { response_type: "text", text: "Analysis complete!" } * ] * } * } * ``` */ SYSTEM = "system" } /** * These are the human agent specific message types. * * @category Service desk */ declare enum HumanAgentMessageType { /** * There was an error in a message. */ INLINE_ERROR = "inline_error", /** * The agent sent a message. */ FROM_HUMAN_AGENT = "from_agent", /** * The user sent a message. */ FROM_USER = "from_user", /** * The agent left the chat. */ HUMAN_AGENT_LEFT_CHAT = "agent_left_chat", /** * The agent ended the conversation. */ HUMAN_AGENT_ENDED_CHAT = "agent_ended_chat", /** * The agent joined the conversation. */ HUMAN_AGENT_JOINED = "agent_joined", /** * A disconnection warning was emitted. */ RELOAD_WARNING = "user_connected_warning", /** * The conversation was transferred to another agent. */ TRANSFER_TO_HUMAN_AGENT = "transfer_to_agent", /** * The end user ended the conversation with the agent. */ USER_ENDED_CHAT = "user_ended_chat", /** * The conversation was ended. */ CHAT_WAS_ENDED = "chat_was_ended", /** * The conversation was disconnected. */ DISCONNECTED = "disconnected", /** * The conversation was re-connected. */ RECONNECTED = "reconnected", /** * Screen sharing requested. */ SHARING_REQUESTED = "sharing_requested", /** * Screen sharing accepted. */ SHARING_ACCEPTED = "sharing_accepted", /** * Screen sharing declined. */ SHARING_DECLINED = "sharing_declined", /** * Screen sharing cancelled. */ SHARING_CANCELLED = "sharing_cancelled", /** * Screen sharing ended. */ SHARING_ENDED = "sharing_ended", /** * A system message. */ SYSTEM = "system" } /** * A general type to indicate any message. * * @category Messaging */ type Message = MessageRequest | MessageRequest | MessageResponse; /** * @category Messaging */ interface ItemStreamingMetadata { /** * An identifier for this item within the full message response. This ID is used to correlate a partial or * complete item chunk with other chunks that represent the same item. This ID is only unique for a given message * response. */ id: string; /** * When included on a partial_item, indicates if the stream can be cancelled. * If so, a "stop streaming" button will display in the UI. */ cancellable?: boolean; /** * Indicates if the stream has stopped which will trigger the UI to respond with appropriate a11y states * and messaging. */ stream_stopped?: boolean; } /** * A chain of thought step is meant to show tool calls and other steps made by your agent * to reach its final answer. * * @category Messaging */ interface ChainOfThoughtStep { /** * The plain text name of the step. */ title?: string; /** * An optional human readable description of what the tool does. * * Accepts markdown formatted text. */ description?: string; /** * The plain text name of the tool called. */ tool_name?: string; /** * Optional request metadata sent to a tool. */ request?: { /** * Arguments sent to the tool. If this is properly formed JSON, it will be shown as a code block. */ args?: unknown; }; /** * Optional response from a tool. */ response?: { /** * Content returned by the tool. If this is properly formed JSON, it will be shown as a code block. * * You can also return markdown compatible text here. */ content: unknown; }; /** * Optionally, share the status of this step. An icon will appear in the view showing the status. If no status is * shared, the UI will assume success. */ status?: ChainOfThoughtStepStatus; } /** * Options that control additional features available for a message item. * * @category Messaging */ interface GenericItemMessageOptions { /** * Controls the display of feedback options (thumbs up/down) for a message item. */ feedback?: GenericItemMessageFeedbackOptions; /** * Optional configuration for a custom footer slot. This allows you to add custom content to the footer of a message. */ custom_footer_slot?: GenericItemCustomFooterSlotOptions; } /** * If you want to have different categories for positive and negative feedback, you can provide two different arrays. * * You may not provide one of the arrays. e.g. you want negative categories but don't care about positive categories. * * @category Messaging */ interface GenericItemMessageFeedbackCategories { /** * List of strings for positive feedback categories. */ positive?: string[]; /** * List of strings for negative feedback categories. */ negative?: string[]; } /** * Controls the display of a feedback options (thumbs up/down) for a message item. * * @category Messaging */ interface GenericItemMessageFeedbackOptions { /** * Indicates if a request for feedback should be displayed. */ is_on?: boolean; /** * A unique identifier for this feedback. This is required for the feedback to be recorded in message history. */ id?: string; /** * The maximum number of characters allowed in the feedback text area. * defaults to 1000. */ max_length?: number; /** * Indicates if the user should be asked for additional detailed information when providing positive feedback. This * defaults to true. */ show_positive_details?: boolean; /** * Indicates if the user should be asked for additional detailed information when providing negative feedback. This * defaults to true. */ show_negative_details?: boolean; /** * Indicates whether the text area should be shown. This defaults to true. */ show_text_area?: boolean; /** * Indicates whether the prompt line should be shown. This defaults to true. */ show_prompt?: boolean; /** * The title to display in the popup. A default value will be used if no value is provided here. */ title?: string; /** * The prompt text to display to the user. A default value will be used if no value is provided here. */ prompt?: string; /** * An optional set of categories to allow the user to choose from. This can either be an array of strings for * both positive and negative feedback or a {@link GenericItemMessageFeedbackCategories} object to make different * configuration for both. */ categories?: string[] | GenericItemMessageFeedbackCategories; /** * The placeholder to show in the text area. A default value will be used if no value is provided here. */ placeholder?: string; /** * The legal disclaimer text to show at the bottom of the popup. This text may contain rich markdown content. If this * value is not provided, no text will be shown. */ disclaimer?: string; /** * The label text to display with the legal disclaimer checkbox. If this value is not provided, no disclaimer checkbox * or label text will be displayed. */ disclaimerCheckbox?: string; } /** * Options that control the custom content in a message footer. * * @category Messaging */ interface GenericItemCustomFooterSlotOptions { /** * Unique identifier for this footer slot. Used to match with the render function. */ slot_name: string; /** * Indicates whether to show the custom footer slot. This defaults to true. */ is_on?: boolean; /** * Optional additional data to pass to the render function. This can contain * any custom metadata that the frontend needs to render the footer appropriately. */ additional_data?: Record; } /** * @category Messaging */ type PartialOrCompleteItemChunk = PartialItemChunk | CompleteItemChunk; /** * The base interface that all message response items must implement. Contains common properties * shared by all item types. * * @category Messaging */ interface BaseGenericItem> { /** * The response type of this message item. */ response_type: MessageResponseTypes; /** * Metadata used to identify a generic item within the context of a stream in order to correlate any updates meant * for a specific item. */ streaming_metadata?: ItemStreamingMetadata; /** * An optional buckets of additional user defined properties for this item. */ user_defined?: TUserDefinedType; /** * For messages that are sent between the user and a human agent, we assign an agent type to the message to distinguish what type it is. */ agent_message_type?: HumanAgentMessageType; /** * Options that control additional features available for a message item. */ message_item_options?: GenericItemMessageOptions; } /** * The basic class for items returned from an assistant as part of a message response. These are the items contained * in the {@link MessageOutput.generic} array. * * @category Messaging */ type GenericItem> = TextItem | OptionItem | ConnectToHumanAgentItem | ImageItem | PauseItem | UserDefinedItem | IFrameItem | VideoItem | AudioItem | DateItem | InlineErrorItem | CardItem | CarouselItem | ButtonItem | GridItem | ConversationalSearchItem | PreviewCardItem | SystemMessageItem; /** * A user defined item returned in a message response from an assistant. * * @category Messaging */ interface UserDefinedItem> extends BaseGenericItem { /** * If the user_defined response type should be rendered as full width and ignore margin on the "start". */ full_width?: boolean; } /** * This message item represents a preview card that can trigger a workflow view. * * @category Messaging */ interface PreviewCardItem> extends BaseGenericItem { /** * The id of the workspace that is attached to this card. */ workspace_id: string; /** * The title of the preview card. */ title?: string; /** * The subtitle of the preview card. */ subtitle?: string; /** * Options for opening the workspace. */ workspace_options?: WorkspaceCustomPanelConfigOptions; /** * Additional data to be passed to workspace. */ additional_data?: unknown; } /** * A text item returned in a message response from an assistant. * * The Carbon AI Chat supports basic styling inside text responses to match the theme of your Carbon AI Chat, * both with Markdown or HTML content returned from your assistant. Using Markdown and `user_defined` * ({@link UserDefinedItem}) responses instead of HTML in your text responses is the recommendation. It allows * adding channels that do not support HTML (such as Facebook, Slack, or WhatsApp) without having to rewrite * your content. * * ## Markdown * * The Carbon AI Chat supports the following Markdown syntax in the text response type: * * **Text formatting:** * * - `**bold text**` or `__bold text__` * - `*italic text*` or `_italic text_` * - `~~strikethrough~~` * - `==highlighted text==` * - `^superscript^` * - `~subscript~` * * **Code:** * * - `` `inline code` `` or fenced code blocks with syntax highlighting. * * **Headers:** * * - `# H1`, `## H2`, `### H3`, `#### H4`, `##### H5`, `###### H6` * * **Lists:** * * - Unordered lists using `*`, `+`, or `-` * - Ordered lists using `1.`, `2.`, etc. * - Nested lists are supported * * **Links and images:** * * - `[link text](URL)` for links (opens in new tab by default) * - `![alt text](image URL)` for images * * **Other elements:** * * - `> blockquote text` for blockquotes * - Tables using pipe syntax with automatic pagination and sorting * - Horizontal rules using `---` or `***` * - Line breaks are preserved (breaks: true) * - Automatic URL detection and conversion to links * * **Attributes:** * * - Custom attributes using `{{class="my-class" id="my-id"}}` syntax * - Supported attributes: `target`, `rel`, `class`, `id` * * **HTML support:** * * - Raw HTML is supported when enabled * - Custom elements and web components are allowed * - Content is sanitized for security when sanitization is enabled * * The Carbon AI Chat follows CommonMark rules with these extensions and enhancements. * * ## HTML content * * If you include HTML (including `style` and `script` tags) in your text response from your assistant, the * Carbon AI Chat renders those elements as provided, unless you set {@link PublicConfig.shouldSanitizeHTML} * to `true`. A better approach is to use a `user_defined` response instead of adding HTML directly to your * responses to make adding support for channels that do not support HTML easier. * * @category Messaging */ interface TextItem> extends BaseGenericItem { /** * The text of the response. */ text?: string; } /** * Visual layout for a {@link SystemMessageItem}. * * @category Messaging */ type SystemMessageVariant = "default" | "date" | "agent"; /** * A system message item that can be returned in a message response. System messages are used for * status updates, progress indicators, or informational notices. * * If a response contains ONLY system messages, they render standalone (centered, no avatar, no bubble). * If mixed with other response types, system messages render inline within the message bubble. * * @category Messaging */ interface SystemMessageItem> extends BaseGenericItem { /** * The response type is always "system" for system messages. */ response_type: MessageResponseTypes.SYSTEM; /** * The title text to display in the system message. */ title: string; /** * How the system line is presented when the message renders as a **standalone** system line * (response contains only system items): default helper text, date separator with rules, or * agent with a rule above and helper text. When system items render **inline** inside a * bubble, `variant` is ignored and the default inline style is used. * @default 'default' */ variant?: SystemMessageVariant; } /** * A "connect to agent" item returned in a message response from an assistant. This is used when the back-end * indicates that a user's conversation should be escalated to a human agent. * * @category Messaging */ interface ConnectToHumanAgentItem> extends BaseGenericItem { /** * A message to be sent to the human agent who will be taking over the conversation. */ message_to_human_agent?: string; /** * Contains the message to be rendered if there are agents available. */ agent_available?: { message: string; }; /** * Contains the message to be rendered if there are no agents available. */ agent_unavailable?: { message: string; }; /** * When a conversation is escalated to an agent additional information is needed to fulfill the request. This * additional information typically is added by the channel integration and cannot be deduced from the dialog * itself. */ transfer_info?: ConnectToHumanAgentItemTransferInfo; } /** * Additional information as part of a {@link ConnectToHumanAgentItem} that may be needed to perform a transfer to an agent. * * @category Messaging */ interface ConnectToHumanAgentItemTransferInfo { /** * Each service desk may require different information to start the connection. It can be account details or * security information. This is a bucket of all the service desk specific properties. */ additional_data?: { [key: string]: string; }; /** * An initial set of message items to send to the agent. */ summary_message_to_agent?: TextItem[]; } /** * A pause item returned in a message response from an assistant. This indicates that the client should pause before * displaying additional response items. * * @category Messaging */ interface PauseItem> extends BaseGenericItem { /** * How long to pause, in milliseconds. */ time?: number; /** * Whether to display an "is typing" indicator during the pause. */ typing?: boolean; } /** * An option item returned in a message response from an assistant. This response type is used when displaying a list * of options to the user. How the options are displayed is up to the client but is often displayed in either a * drop-down or as a list of buttons. * * @category Messaging */ interface OptionItem> extends BaseGenericItem { /** * An array of objects describing the options from which the user can choose. */ options: SingleOption[]; /** * An optional title to be shown alongside the options. */ title?: string; /** * An optional description to be shown alongside the options. */ description?: string; /** * The preferred type of control to display (e.g. button or dropdown). */ preference?: OptionItemPreference; } /** * The set of possible response preferences for an options response. * * @category Messaging */ declare enum OptionItemPreference { /** * Indicates the options should be displayed as a drop-down. */ DROPDOWN = "dropdown", /** * Indicates the options should be displayed as buttons. */ BUTTON = "button" } /** * Represents an individual option that is part of an "options" response. * * @category Messaging */ interface SingleOption { /** * The user-facing label for the option or disambiguation suggestion. This label is taken from the user_label property * of the corresponding dialog node. */ label: string; value: { /** * An input object that should be sent back to the assistant when this option is chosen by a user. */ input: MessageInput; }; } /** * @category Messaging */ interface IFrameItem> extends BaseGenericItem { /** * The source URL to an embeddable page */ source: string; /** * The preview image of the source URL. This property is unfurled from the source URL at runtime. It is used when * IFrameItemDisplayOption is set to 'panel' for the preview card to open the panel. */ image_url?: string; /** * The title of the source URL. This property is unfurled from the source URL at runtime. It is used when * IFrameItemDisplayOption is set to 'panel' for the preview card to open the panel. */ title?: string; /** * The description of the source URL. This property is unfurled from the source URL at runtime. It is used when * IFrameItemDisplayOption is set to 'panel' for the preview card to open the panel. */ description?: string; /** * How the iframe should be displayed. */ display?: IFrameItemDisplayOption; } /** * Dimension information for displaying a media item. * * @category Messaging */ interface MediaItemDimensions { /** * This property's value is used to calculate a responsive height for Carbon AI Chat's media player so that its aspect * ratio is the same between different screen widths. This is set to a reasonable default depending on the response type * and other details like what service you are pulling the content from (e.g. Youtube or SoundCloud). */ base_height?: number; } /** * Represents a single subtitle/caption track for video content. * Uses WebVTT format for accessibility. Rendered as native HTML5 track elements. * * @category Messaging */ interface MediaSubtitleTrack { /** * URL pointing to the WebVTT subtitle file. */ src: string; /** * The language code (e.g., "en", "es", "fr"). * Used for the track's srclang attribute. */ language: string; /** * Human-readable label for the track (e.g., "English", "Spanish"). * Displayed in the browser's subtitle menu. */ label: string; /** * The kind of text track. * - "subtitles": Translation of dialogue (default) * - "captions": Transcription including sound effects * - "descriptions": Audio descriptions for visually impaired */ kind?: "subtitles" | "captions" | "descriptions"; /** * Whether this track should be enabled by default. * Only one track should be default. */ default?: boolean; } /** * Represents a text transcript for audio content. * Displayed as readable text below the audio player for accessibility. * * @category Messaging */ interface MediaTranscript { /** * Full text transcript of the audio content. * Supports markdown for formatting. */ text: string; /** * Language of the transcript (e.g., "en", "es", "fr"). */ language?: string; /** * Optional label for the transcript (e.g., "English Transcript"). */ label?: string; } /** * Accessibility features for raw media files (not embedded platforms). * These features only apply when using direct file URLs (e.g., .mp4, .mp3). * * For embedded platforms (YouTube, Vimeo, SoundCloud, etc.), * rely on the platform's built-in accessibility features instead. * * @category Messaging */ interface MediaFileAccessibility { /** * Subtitle/caption tracks for video files. * Supports WebVTT format rendered as native HTML5 track elements. */ subtitle_tracks?: MediaSubtitleTrack[]; /** * Text transcript for audio files. * Displayed as expandable text below the audio player. */ transcript?: MediaTranscript; } /** * The different ways an iframe item may be displayed. * * @category Messaging */ declare enum IFrameItemDisplayOption { /** * The iframe is displayed inline in the main message list. */ INLINE = "inline", /** * The iframe is displayed in a separate panel after showing a card in the main message list. */ PANEL = "panel" } /** * A reusable media object that may need to display a title and description with an alt_text to label the item for * accessibility purposes. This is used by the Audio, Video and Image response types. * * @category Messaging */ interface MediaItem> extends BaseGenericItem { /** * The url pointing to a media source, whether audio, video, or image. * * For video this can be a file like an .mp4 or a YouTube, Facebook, Vimeo, Twitch, Streamable, Wistia, or Vidyard url. * * For audio this can be a file like an .mp3 or a SoundCloud url. */ source: string; /** * The title for the item. */ title?: string; /** * The description for the item. */ description?: string; /** * The alt text for labeling the item. Screen readers will announce this text when the user's virtual cursor * is focused on the item. */ alt_text?: string; /** * Settings that control the dimensions for the media item. */ dimensions?: MediaItemDimensions; /** * Accessibility features for raw media files. * Only applies to direct file URLs (e.g., .mp4, .mp3), not embedded platforms. */ file_accessibility?: MediaFileAccessibility; } /** * Citations for text generated by an AI to provide the user with relevant source information and context. * * @category Messaging */ interface ConversationalSearchItemCitation { /** * Optional url of the citation. May not be a valid URL. */ url?: string; /** * Optional explanation text for the citation. */ text?: string; /** * Optional title of the citation URL. */ title?: string; /** * Optional array of ranges indicating where in `text` the citation is located. */ ranges?: { start: number; end: number; }[]; /** * In some implementations, the content searched isn't in an accessible URL. For instance, it could be from Milvus or * ElasticSearch. In that scenario, you may populate "search_results". This field will allow you define which index in * the search_results array matches with this citation. The end user can then drill into the larger search result to * view it rather than clicking on a URL to actually see the content. */ search_result_idx?: number; } /** * A text response generated by AI with an optional list of citations for where the information came from. * * @category Messaging */ interface ConversationalSearchItem> extends BaseGenericItem { /** * The returned conversational text. Any HTML/Markdown will be ignored. */ text: string; /** * Citations are used to connect specific text within a conversational search response with the relevant documents * returned by the backend. */ citations?: ConversationalSearchItemCitation[]; /** * In some implementations, the content searched isn't in an accessible URL. For instance, it could be from Milvus or * ElasticSearch. In that scenario, you may populate "search_results". Combine this with * {@link ConversationalSearchItemCitation.search_result_idx}. */ search_results?: SearchResult[]; } /** * An inline error response generated by a conversational skill provider with a user-friendly text and developer debug info. * * @category Messaging */ interface InlineErrorItem> extends BaseGenericItem { /** * Some end user friendly text describing the error and what they should do next. * * If no specific text is passed, the client is responsible for fallback generic error message text. */ text?: string; /** * Relevant debug info intended to be passed on to developers. * * This information should not include anything sensitive that might reveal details about our back-end environment that should not be public. */ debug?: { /** * The error code of any underlying error, despite the service returning 200. */ statusCode?: number; /** * Developer-friendly error text. */ text?: string; /** * Any additional key-value pairs for debugging. */ info?: Record; }; } /** * The image response type definition. This is currently the same as {@link MediaItem}. * * @category Messaging */ type ImageItem> = MediaItem; /** * The video response type definition for future reuse. This is currently the same as {@link MediaItem}. * * @category Messaging */ type VideoItem> = MediaItem; /** * The audio response type definition for future reuse. This is currently the same as {@link MediaItem}. * * @category Messaging */ type AudioItem> = MediaItem; /** * @category Messaging */ declare enum ButtonItemType { /** * A button that sends its value back to the backend. */ POST_BACK = "post_back", /** * A button that throws an event for your UI to respond to. */ CUSTOM_EVENT = "custom_event", /** * A button that shows a panel. */ SHOW_PANEL = "show_panel", /** * A button that opens a URL. */ URL = "url" } /** * @category Messaging */ declare enum WidthOptions { /** * Width the size of the floating chat for smaller content. */ SMALL = "small", /** * Max width of 438px, 2/3rd of the width of chat in fullscreen view with hasContentMaxWidth: true. */ MEDIUM = "medium", /** * Max width of 585px, the full with of chat in fullscreen view with hasContentMaxWidth: true. */ LARGE = "large" } /** * @category Messaging */ interface WithWidthOptions { /** * Sets an optional max width of the component. Options are small, medium and large. * By default, the component will be 100% width of the container. */ max_width?: WidthOptions; } /** * @category Messaging */ interface WithBodyAndFooter { /** * A list of message items to render in a Carbon AI Chat panel. */ body?: GenericItem[]; /** * A list of button items that are rendered under the panel body. */ footer?: ButtonItem[]; } /** * @category Messaging */ interface MessageItemPanelInfo extends WithBodyAndFooter { /** * The title to give the panel in Carbon AI Chat. */ title?: string; /** * Determines if the panel header should not be visible or not. * * Defaults to true. */ show_header?: boolean; /** * Determines if the panel close and open animations should be enabled or not. * * Defaults to true. */ show_animations?: boolean; /** * Shows the AI gradient background on your panel. Can be used with in concert with showFrame. * * Defaults to {@link PublicConfig.aiEnabled} value. */ ai_enabled?: boolean; /** * Show a frame with the chat shell background instead of the gradient background for your panel content. * * Defaults to true. */ show_frame?: boolean; /** * By default, the panel will render at the width of the messages list. If you want to be able to render to a full screen * width slot, set full_width to true. * * Defaults to false. */ full_width?: boolean; } /** * @category Messaging */ declare enum ButtonItemKind { /** * Default Carbon button. */ DEFAULT = "default", /** * Secondary Carbon button. */ SECONDARY = "secondary", /** * Tertiary Carbon button. */ TERTIARY = "tertiary", /** * Danger Carbon button. */ DANGER = "danger", /** * Ghost Carbon button. */ GHOST = "ghost", /** * Button displayed like a link. */ LINK = "link" } /** * This message item represents a button that can perform various actions such as sending messages, opening URLs, or showing panels. * * @category Messaging */ interface ButtonItem> extends BaseGenericItem { /** * The style of button to display. */ kind?: BUTTON_KIND | CHAT_BUTTON_KIND | "LINK"; /** * The button size. */ size?: BUTTON_SIZE | CHAT_BUTTON_SIZE; /** * The type of button. */ button_type: ButtonItemType; /** * The URL for the user to visit when the button is clicked. */ url?: string; /** * Where to open the link. The default value is _self. */ target?: string; /** * The display text for the link. */ label?: string; /** * A custom event that can be listened to by Carbon AI Chat when the button item is clicked. */ custom_event_name?: string; value?: { /** * An input object that should be sent back to the assistant when this option is chosen by a user. */ input: MessageInput; }; /** * When true (post_back buttons only), the request generated by clicking this button is sent to * `customSendMessage` but not added to the visible chat transcript. Use this when the button's * `value.input.text` is a machine-readable trigger string that you don't want the user to see. * * @default false */ silent?: boolean; /** * The panel options to display in a panel when the "show_panel" button type is clicked. */ panel?: MessageItemPanelInfo; /** * The URL pointing to an image. */ image_url?: string; /** * The alt text for labeling the item. Screen readers will announce this text when the user's virtual cursor * is focused on the item. */ alt_text?: string; } /** * @category Messaging */ type CardItem> = BaseGenericItem & WithBodyAndFooter & WithWidthOptions; /** * @category Messaging */ interface CarouselItem> extends BaseGenericItem { items: GenericItem[]; } /** * Horizontal alignment values for items in a grid response. * * @category Messaging */ type HorizontalCellAlignment = "left" | "center" | "right"; /** * Vertical alignment values for items in a grid response. * * @category Messaging */ type VerticalCellAlignment = "top" | "center" | "bottom"; /** * @category Messaging */ interface GridItem> extends BaseGenericItem, WithWidthOptions { /** * Determines the horizontal alignment of all items in the grid. */ horizontal_alignment?: HorizontalCellAlignment; /** * Determines the vertical alignment of all items in the grid. */ vertical_alignment?: VerticalCellAlignment; /** * The list of column specifications. This will determine the maximum number of columns that can be rendered. */ columns: { width: string; }[]; /** * A list of rows to render. */ rows: { /** * A list of cells to render in a row. */ cells: { /** * Determines the horizontal alignment of items in the individual cell. */ horizontal_alignment?: HorizontalCellAlignment; /** * Determines the vertical alignment of items in the individual cell. */ vertical_alignment?: VerticalCellAlignment; /** * Message items to render in the cell. */ items: GenericItem[]; }[]; }[]; } /** * This is the response item that represents a request for a date which should prompt the client to use a date picker or * similar control to provide a date. There are currently no additional properties of the response. * * @category Messaging */ type DateItem> = BaseGenericItem; /** * @category Messaging */ interface Chunk { /** * Additional metadata associated with the stream. */ streaming_metadata?: { /** * The ID of the complete message response object. This ID will be the ID of the full message that is received * in the final chunk of the stream. */ response_id: string; }; } /** * If the reasoning step is open, closed, or is controlled by Carbon AI Chat. * * If a user elects to open/close the user action will override what is provided here. * * @category Messaging */ declare enum ReasoningStepOpenState { OPEN = "open", CLOSE = "close", DEFAULT = "default" } /** * An individual reasoning step. * * @category Messaging */ interface ReasoningStep { /** * The title of the reasoning step. */ title: string; /** * Marks if this individual step is open. Only use this if you don't want the default behavior. * * If the step has content, by default the reasoning step will automatically open and will close when the * next step(s) have content or the first {@link GenericItem} is returned with something to display. * * No matter what you choose, if the user manually marks something open/closed they retain control. */ open_state?: ReasoningStepOpenState; /** * Optional markdown content (string) or a list of {@link GenericItem} response items to render inside this * reasoning step. When an array is supplied, each item is rendered through the standard message renderer. * * GenericItem variants that render purely from their own item data (TextItem, ImageItem, UserDefinedItem, * ButtonItem, InlineErrorItem, etc.) are fully supported. Variants whose renderers rely on nested-body * hydration (Card, Carousel, Grid bodies) will not hydrate those nested children when used here. */ content?: string | GenericItem[]; } /** * The interface describing how to pass reasoning steps to the UI. * * @category Messaging */ interface ReasoningSteps { /** * Marks if the reasoning step interface is open. Only use this if you don't want the default behavior. * * By default the reasoning step interface will automatically open and will then close when the first * {@link GenericItem} is returned with something to display. * * No matter what you choose, if the user manually marks something open/closed they retain control. */ open_state?: ReasoningStepOpenState; /** * The array of reasoning steps for this message. */ steps?: ReasoningStep[]; /** * Optional markdown content (string) or a list of {@link GenericItem} response items to render as a preamble * above the reasoning steps. When an array is supplied, each item is rendered through the standard message * renderer. * * GenericItem variants that render purely from their own item data (TextItem, ImageItem, UserDefinedItem, * ButtonItem, InlineErrorItem, etc.) are fully supported. Variants whose renderers rely on nested-body * hydration (Card, Carousel, Grid bodies) will not hydrate those nested children when used here. */ content?: string | GenericItem[]; } /** * This interface contains options for a {@link MessageResponse}. * * @category Messaging */ interface MessageResponseOptions { /** * This is the profile for the human or assistant who sent or triggered this message. */ response_user_profile?: ResponseUserProfile; /** * Controls the display of the reasoning steps component. * * Most people should use reasoning steps instead of chain of thought. * * Chain of thought it meant more for technical "called X API and got Y result back". * * Reasoning steps can include that kind of detail depending on your use case, but is meant more for user friendly * content than debugging technical internal content. */ reasoning?: ReasoningSteps; /** * Controls the display of the chain of thought component. * * Most people should use reasoning steps instead of chain of thought. * * Chain of thought it meant more for technical "called X API and got Y result back". * * Reasoning steps can include that kind of detail depending on your use case, but is meant more for user friendly * content than debugging technical internal content. */ chain_of_thought?: ChainOfThoughtStep[]; } /** * This interface contains information about the history of a given {@link MessageResponse}. This information should be * saved your history store. * * @category Messaging */ interface MessageResponseHistory { /** * The time at which this message occurred. */ timestamp?: number; /** * Indicates if this is a "silent" message. These messages are sent to or received from the assistant but should * not be displayed to the user. */ silent?: boolean; /** * The error state of this message. */ error_state?: MessageErrorState; /** * The state of feedback provided on the items in this message. */ feedback?: { [feedbackID: string]: MessageHistoryFeedback; }; } /** * This interface contains information about the history of a given {@link MessageRequest}. This information should be * saved your history store. * * @category Messaging */ interface MessageRequestHistory { /** * The time at which this message occurred. */ timestamp?: number; /** * The user-friendly label that was associated with this message. This is used on messages that were sent by the * user to the assistant to request a response. This is the user displayed text that was entered or selected by * the user when that request was made. Most commonly used to make sure a {@link OptionItem} shows the correct button * selected when loading history. */ label?: string; /** * If the message was a welcome node request. */ is_welcome_request?: boolean; /** * If this message is related to another message, this is the ID of that other message. This is used when a user * choices an option and it includes the ID of the message response that presented the options to the user so we * can associate the user's request with that earlier response and display the appropriate selected state. */ related_message_id?: string; /** * Indicates if this is a "silent" message. These messages are sent to or received from the assistant but should * not be displayed to the user. */ silent?: boolean; /** * The error state of this message. */ error_state?: MessageErrorState; } /** * @category Messaging */ interface MessageHistoryFeedback { /** * Indicates if positive feedback was provided. */ is_positive: boolean; /** * The feedback text provided by the user. */ text?: string; /** * When submitting feedback details, this is the list of categories the user selected (if visible). */ categories?: string[]; } /** * @category Messaging */ interface PartialResponse { /** * This contains the history of this response. */ message_options?: DeepPartial; } /** * The interface for a chunk that represents a partial update (or first time chunk) to a message item. * * @category Messaging */ interface PartialItemChunk extends Chunk { /** * The partial details of the item. The client will decide what rules to follow for merging this in with any * existing data for the same item (which is identified using the {@link ItemStreamingMetadata.id} property). */ partial_item: DeepPartial; /** * Change the agent display name and other items on the full response. */ partial_response?: PartialResponse; } /** * A stricter partial item chunk type for streaming implementations that want compile-time enforcement of * {@link ItemStreamingMetadata.id}. This is optional and not required for compatibility. * * @category Messaging */ type PartialItemChunkWithId = Omit & { partial_item: DeepPartial & { streaming_metadata: ItemStreamingMetadata; }; }; /** * Completes a single streamed item before the full response is ready. * * Use this to replace a streamed item with its final, corrected version while other * items are still streaming. The complete item should include all data needed to * render the item (including anything from partial chunks). Include * {@link ItemStreamingMetadata.id} to correlate with prior partial chunks and preserve * identity. If you are only streaming a single item, you can skip this and send a * {@link FinalResponseChunk} instead. * * @category Messaging */ interface CompleteItemChunk extends Chunk { /** * A complete message item. If this item was streamed via partial chunks, * you should include {@link ItemStreamingMetadata.id} so the UI can preserve identity. */ complete_item: GenericItem; /** * Change the agent display name and other items on the full response. */ partial_response?: PartialResponse; } /** * Finalizes the full response and ends streaming. * * This provides the authoritative final state of the full message response. It should * include all items that were streamed (and any corrections). For any item that was * streamed, include {@link ItemStreamingMetadata.id} to preserve identity and avoid * remounts. The message ID should match streaming_metadata.response_id. * * @category Messaging */ interface FinalResponseChunk { /** * The final message response. If this response contains items that were streamed, * those items should include {@link ItemStreamingMetadata.id} to avoid remounts. */ final_response: MessageResponse; } /** * @category Messaging */ type StreamChunk = PartialItemChunk | CompleteItemChunk | FinalResponseChunk; /** * Types of users we accept messages from. * * @category Messaging */ declare enum UserType { /** * A message from a human. */ HUMAN = "human", /** * A message from a non-watsonx assistant, used for interacting with assistants that are not backed by watsonx. * * Official guidance is to not use this for IBM products without explicit exception. */ BOT = "bot", /** * A message from watsonx. */ WATSONX = "watsonx" } /** * Profile information about a specific agent that can be used to display information to the user. This may * represent a human agent or a virtual assistant agent. * * @category Messaging */ interface ResponseUserProfile { /** * A unique identifier for this agent. */ id: string; /** * The visible name for the response author. Can be the full name or just a first name for a human. */ nickname: string; /** * The type of user. If its a "human" there is more protection against code injection attacks, where as assistant responses * are trusted by default unless {@link PublicConfig.shouldSanitizeHTML} is set to true. */ user_type: UserType; /** * A URL pointing to an avatar for the response author. This image should be a square. */ profile_picture_url?: string; } /** * A single search result. * * @category Messaging */ interface SearchResult { /** * The search result. This can be drilled into and viewed in a larger and scrollable format. */ body?: string; } /** * The types here describe the history structure. * This is used currently for session history and is planned to be reused by the history. */ /** * A single interaction in the Session History. * * @category Messaging */ interface HistoryItem { /** * The message represented by this history item. */ message: MessageRequest | MessageResponse; /** * Time this message occurred. ISO Format (e.g. 2020-03-15T08:59:56.952Z). */ time: string; } /** * Lifecycle state passed to {@link ChatInstanceMessaging.upsertMessage} to describe the * message's state after the upsert completes. Carbon AI Chat tracks this state internally; * it is never written onto a {@link MessageResponse}. * * `addMessage`, `addMessageChunk`, and `upsertMessage` may all target the same message * id without producing duplicate `pre:receive` / `receive` events — Carbon AI Chat tracks * the recorded state per id and fires those events only on the first transition to * {@link COMPLETE}. * * @category Messaging * @experimental */ declare enum MessageState { /** * The message is still being constructed and further updates are expected. The * "stop streaming" affordance remains available while a message is in this state if * any item carries `streaming_metadata.cancellable: true`. */ STREAMING = "streaming", /** * The message has reached its final shape. Carbon AI Chat fires * {@link BusEventType.PRE_RECEIVE} and {@link BusEventType.RECEIVE} when a message * transitions into this state from any other state, including the case where no * message with this ID previously existed. */ COMPLETE = "complete", /** * The message terminated in an error condition. The chat displays the message as-is * and does not fire {@link BusEventType.PRE_RECEIVE} or {@link BusEventType.RECEIVE} * when a message transitions into this state. Treat `ERROR` as terminal — subsequent * upserts targeting the same id are still accepted but should be rare. */ ERROR = "error" } /** * The updater function passed to {@link ChatInstanceMessaging.upsertMessage}. Receives the * message currently stored under the target ID (or `undefined` when no message with that * ID is in the store) and returns the {@link MessageResponse} that should replace it. May * be synchronous or asynchronous. * * @param previous The message currently stored under the target id, or `undefined` on the * first upsert of a new id. * @returns The {@link MessageResponse} to store, optionally as a Promise. * @category Messaging * @experimental */ type UpsertMessageUpdater = (previous: MessageResponse | undefined) => Promise | MessageResponse; /** * Reasons why a message request was cancelled via the abort signal. * * @category Messaging */ declare enum CancellationReason { /** * User clicked the "stop streaming" button during message streaming. */ STOP_STREAMING = "Stop streaming", /** * User restarted or cleared the conversation. */ CONVERSATION_RESTARTED = "Conversation restarted", /** * Message request exceeded the configured timeout duration. */ TIMEOUT = "Request timeout" } /** * Messaging actions for a chat instance. * * @category Messaging */ interface ChatInstanceMessaging { /** * Instructs the widget to process the given message as an incoming message received from the assistant. This will * fire a "pre:receive" event immediately and a "receive" event after the event has been processed by the widget. * * @param message A {@link MessageResponse} object. */ addMessage: (message: MessageResponse) => Promise; /** * Adds a streaming message chunk to the chat widget. */ addMessageChunk: (chunk: StreamChunk) => Promise; /** * Inserts or updates a single message identified by `messageID`. The `updater` receives * the {@link MessageResponse} currently stored under `messageID` (or `undefined` when no * message with that ID exists) and returns the message that should replace it. * * Calls targeting the same `messageID` are serialized — each call awaits the previous * call for that ID before running. Calls targeting different `messageID`s run * independently. * * The `state` argument describes the {@link MessageState} the chat records for this * message after the upsert completes; it is applied uniformly to every item in the * returned message. Carbon AI Chat fires {@link BusEventType.PRE_RECEIVE} and * {@link BusEventType.RECEIVE} exactly when this call transitions the message into * {@link MessageState.COMPLETE} from any other state, including the case where the * message did not previously exist. STREAMING-to-STREAMING and COMPLETE-to-COMPLETE * upserts do not fire these events. * * If the returned message has no `id`, Carbon AI Chat assigns `messageID`. The * cancellation contract for outbound messages is unchanged — see * {@link CustomSendMessageOptions}. * * @param messageID The stable identifier the chat uses to track this message across * subsequent upserts. * @param state The {@link MessageState} to record for this message once the updater * resolves. * @param updater Function that produces the {@link MessageResponse} to store. * @throws `TypeError` when the updater returns `null`/`undefined`, returns a message * whose `id` differs from `messageID`, or returns a non-assistant message (a request * or a human-agent message). * @experimental Upsert semantics and the updater signature may evolve based on consumer feedback. */ upsertMessage: (messageID: string, state: MessageState, updater: UpsertMessageUpdater) => Promise; /** * Removes the messages with the given IDs from the chat view. */ removeMessages: (messageIDs: string[]) => Promise; /** * Clears the current conversation. This will trigger a restart of the conversation but will not start a new * conversation (hydration). It will also clear any loading indicators UNLESS you have set * {@link PublicConfigMessaging.messageLoadingIndicatorTimeoutSecs} to 0. */ clearConversation: () => Promise; /** * Inserts the given messages into the chat window as part of the chat history. This will fire the history:begin * and history:end events. */ insertHistory: (messages: HistoryItem[]) => Promise; /** * Restarts the conversation with the assistant. This does not make any changes to a conversation with a human agent. * This will clear all the current assistant messages from the main assistant view and cancel any outstanding * messages. It will also clear any loading indicators UNLESS you have set * {@link PublicConfigMessaging.messageLoadingIndicatorTimeoutSecs} to 0. */ restartConversation: () => Promise; } /** * @category Messaging */ interface CustomSendMessageOptions { /** * A signal to let customSendMessage to cancel a request if it has exceeded Carbon AI Chat's timeout. */ signal: AbortSignal; /** * If the message was sent with "silent" set to true to not be displayed in the conversation history. */ silent: boolean; /** * BusEventSend provides extra context such as MessageSendSource. */ busEventSend?: BusEventSend; } /** * This file contains the type definitions for the event bus. */ /** @category Events */ declare enum BusEventType { /** * When a panel has been closed. */ CLOSE_PANEL_BUTTON_TOGGLED = "closePanelButton:toggled", /** * Fired before a message is received. Can take mutations to the message. */ PRE_RECEIVE = "pre:receive", /** * Fired after a message is received. */ RECEIVE = "receive", /** * Fired before a message is sent to customSendMessage. Can take mutations to the message. */ PRE_SEND = "pre:send", /** * Fired after the message is sent to customSendMessage. */ SEND = "send", /** * Fired before the view changes (e.g. when the chat window closes). */ VIEW_PRE_CHANGE = "view:pre:change", /** * Fired after the view changes (e.g. when the chat window closes). */ VIEW_CHANGE = "view:change", /** * Fired when a button response item with button_type "custom_event" is clicked. * Provides the originating button item and the full message payload to handlers. */ MESSAGE_ITEM_CUSTOM = "messageItemCustom", /** * Fired when a userDefined message is received. */ USER_DEFINED_RESPONSE = "userDefinedResponse", /** * Fired when a message with custom_footer_slot.is_on is received. */ CUSTOM_FOOTER_SLOT = "customFooterSlot", /** * Fired when history begins to load. */ HISTORY_BEGIN = "history:begin", /** * Fired after history is loaded. */ HISTORY_END = "history:end", /** * Fired when new chat option within the chat header menu is selected. */ HISTORY_PANEL_NEW_CHAT = "history:newChat", /** * Fired before mobile chat history panel opens. */ HISTORY_PANEL_PRE_OPEN = "historyPanel:pre:open", /** * Fired before a conversation restarts. */ PRE_RESTART_CONVERSATION = "pre:restartConversation", /** * Fired after a conversation restarts. */ RESTART_CONVERSATION = "restartConversation", /** * When the chat has finished hydrating from history or welcome node request. */ CHAT_READY = "chat:ready", /** * Fired before a custom panel opens. */ CUSTOM_PANEL_PRE_OPEN = "customPanel:pre:open", /** * Fired after a custom panel opens. */ CUSTOM_PANEL_OPEN = "customPanel:open", /** * Fired before a custom panel closes. */ CUSTOM_PANEL_PRE_CLOSE = "customPanel:pre:close", /** * Fired after a custom panel closes. */ CUSTOM_PANEL_CLOSE = "customPanel:close", /** * Fired before a workspace opens. */ WORKSPACE_PRE_OPEN = "workspace:pre:open", /** * Fired after a workspace opens. */ WORKSPACE_OPEN = "workspace:open", /** * Fired before a workspace closes. */ WORKSPACE_PRE_CLOSE = "workspace:pre:close", /** * Fired after a workspace closes. */ WORKSPACE_CLOSE = "workspace:close", /** * This event is fired before Carbon AI Chat processes a message received from a human agent from a service desk. * You can use this to filter messages before they are displayed to the end user. */ HUMAN_AGENT_PRE_RECEIVE = "human_agent:pre:receive", /** * This event is fired after Carbon AI Chat processes a message received from a human agent from a service desk. * You can use this to update your history store. */ HUMAN_AGENT_RECEIVE = "human_agent:receive", /** * This event is fired before Carbon AI Chat sends a message to a human agent from a service desk. * You can use this to filter messages before they are sent to the agent. */ HUMAN_AGENT_PRE_SEND = "human_agent:pre:send", /** * This event is fired after Carbon AI Chat sends a message to a human agent from a service desk. * You can use this to update your history store. */ HUMAN_AGENT_SEND = "human_agent:send", /** * This event is fired before a chat with a service desk has started. This occurs as soon as the user clicks the * "Request agent" button and before any attempt is made to communicate with the service desk. */ HUMAN_AGENT_PRE_START_CHAT = "human_agent:pre:startChat", /** * This event is fired before a chat with an agent is ended. This occurs after the user has selected "Yes" from the * confirmation modal but it can also be fired if the chat is ended by the agent. Note that this is not fired if a * request for an agent is cancelled. The human_agent:endChat event however is fired in that case. */ HUMAN_AGENT_PRE_END_CHAT = "human_agent:pre:endChat", /** * This event is fired after a chat with an agent has ended. This is fired after {@link BusEventType.HUMAN_AGENT_PRE_END_CHAT} but * can be fired both from the user leaving the chat or the agent ending the chat. */ HUMAN_AGENT_END_CHAT = "human_agent:endChat", /** * This event is fired after Carbon AI Chat calls "areAnyAgentsOnline" for a service desk. It will report the value returned * from that call. This is particularly useful if some custom code wants to take action if no agents are online. */ HUMAN_AGENT_ARE_ANY_AGENTS_ONLINE = "human_agent:areAnyAgentsOnline", /** * Fired when a new chunk in a user_defined response comes through. */ CHUNK_USER_DEFINED_RESPONSE = "chunk:userDefinedResponse", /** * This event is fired when the user interacts with the feedback controls on a message. This includes both the feedback * buttons (thumbs up/down) as well as the details popup where the user can submit additional information. */ FEEDBACK = "feedback", /** * This event is fired when the "stop streaming" button in the input field is clicked. */ STOP_STREAMING = "stopStreaming", /** * This event is fired whenever the public state returned by ChatInstance.getState() changes. * This includes changes to viewState, showUnreadIndicator, and other persisted state. */ STATE_CHANGE = "state:change", /** * Fired if the disclaimer is accepted. */ DISCLAIMER_ACCEPTED = "disclaimerAccepted", /** * Fired when a user clicks on navigation items in the chat header (homescreen button or overflow menu). */ HEADER_MENU_CLICK = "header:menuClick" } /** * The possible reasons why the view may be changed. * * @category Events */ declare enum ViewChangeReason { /** * Indicates the Carbon AI Chat has loaded for the first time and a view is trying to open. If openChatByDefault is * true then the main window will be trying to open, otherwise the launcher will be trying to open. */ WEB_CHAT_LOADED = "webChatLoaded", /** * Indicates the user clicked on our built-in launcher button that opened the main window. */ LAUNCHER_CLICKED = "launcherClicked", /** * Indicates the user clicked on our built-in minimize button that closed the launcher. */ MAIN_WINDOW_MINIMIZED = "mainWindowMinimized", /** * Indicates the view was changed by a call to {@link ChatInstance.changeView}. */ CALLED_CHANGE_VIEW = "calledChangeView" } /** * The different sources that can cause a send event to occur. * * @category Events */ declare enum MessageSendSource { /** * The user has entered a value from the main input on the message list. */ MESSAGE_INPUT = "messageInput", /** * The user has entered a value from the input on the home screen. */ HOME_SCREEN_INPUT = "homeScreenInput", /** * The user clicked a button from an option response. */ OPTION_BUTTON = "optionButton", /** * The user selected a value from a dropdown for an option response. */ OPTION_DROP_DOWN = "optionDropDown", /** * The message was sent as an event history update. */ HISTORY_UPDATE = "historyUpdate", /** * An external call to the public "instance.send" method was made. */ INSTANCE_SEND = "instanceSend", /** * The user chose a value from the date picker. */ DATE_PICKER = "datePicker", /** * The user clicked a post back button from a button response. */ POST_BACK_BUTTON = "postBackButton", /** * The user clicked a starter from the home screen. */ HOME_SCREEN_STARTER = "homeScreenStarter", /** * A default request for the welcome message was made. */ WELCOME_REQUEST = "welcomeRequest", /** * This is used for message events. */ EVENT = "event", /** * Some other source. */ OTHER = "other" } /** * The discriminating union of all the possible bus event types. * @category Events */ interface BusEvent { /** * The type of this event. */ type: BusEventType; } /** * * * @category Events */ interface BusEventClosePanelButtonClicked extends BusEvent { type: BusEventType.CLOSE_PANEL_BUTTON_TOGGLED; } /** * @category Events */ interface BusEventPreReceive extends BusEvent { type: BusEventType.PRE_RECEIVE; data: MessageResponse; } /** * @category Events */ interface BusEventReceive extends BusEvent { type: BusEventType.RECEIVE; data: MessageResponse; } /** * @category Events */ interface BusEventPreSend extends BusEvent { type: BusEventType.PRE_SEND; data: MessageRequest; /** * The source of the message being sent. */ source: MessageSendSource; } /** * @category Events */ interface BusEventSend extends BusEvent { type: BusEventType.SEND; data: MessageRequest; /** * The source of the message being sent. */ source: MessageSendSource; } /** * @category Service desk */ interface BusEventHumanAgentPreReceive extends BusEvent { type: BusEventType.HUMAN_AGENT_PRE_RECEIVE; data: MessageResponse; responseUserProfile?: ResponseUserProfile; } /** * @category Service desk */ interface BusEventHumanAgentReceive extends BusEvent { type: BusEventType.HUMAN_AGENT_RECEIVE; data: MessageResponse; responseUserProfile?: ResponseUserProfile; } /** * @category Service desk */ interface BusEventHumanAgentPreSend extends BusEvent { type: BusEventType.HUMAN_AGENT_PRE_SEND; data: MessageRequest; files: FileUpload[]; } /** * @category Service desk */ interface BusEventHumanAgentSend extends BusEvent { type: BusEventType.HUMAN_AGENT_SEND; data: MessageRequest; files: FileUpload[]; } /** * Fires before the view state is updated in the store. This event is awaited, making it ideal for async operations like animations. * * **Event Timing:** * 1. VIEW_PRE_CHANGE fires (awaited) * 2. View state is updated in store * 3. VIEW_CHANGE fires (awaited) * * **Use cases:** * - Run animations before the view changes * - Modify the new view state before it's applied * - Cancel the view change entirely * * @category Events */ interface BusEventViewPreChange extends BusEvent { type: BusEventType.VIEW_PRE_CHANGE; /** * The reason the view is changing. */ reason: ViewChangeReason; /** * The previous view state before this event. */ oldViewState: ViewState; /** * The new view state that Carbon AI Chat is going to switch to. This new state can be changed by the event handler. */ newViewState: ViewState; /** * This is used by the event handler to indicate that the view change should be cancelled and Carbon AI Chat's view should * not be changed. */ cancelViewChange: boolean; } /** * Fires after the view state has been updated in the store. This event is awaited, making it ideal for async operations that should happen after the view change. * * **Event Timing:** * 1. VIEW_PRE_CHANGE fires (awaited) * 2. View state is updated in store * 3. VIEW_CHANGE fires (awaited) ← You are here * * **Use cases:** * - React to completed view changes * - Run cleanup or follow-up animations * - Cancel and revert the view change (causes immediate revert without firing events) * * @category Events */ interface BusEventViewChange extends BusEvent { type: BusEventType.VIEW_CHANGE; /** * The reason the view is changing. */ reason: ViewChangeReason; /** * The previous view state from before the view:pre:change event. */ oldViewState: ViewState; /** * The new view state that Carbon AI Chat has switched to. This new state can be changed by the event handler. */ newViewState: ViewState; /** * This is used by the event handler to indicate that the view change should be cancelled and Carbon AI Chat's view should * not be changed. Since the view has already changed when this event is fired, this property will cause the view to * change back. Note that the view change events are *not* fired when the view changes back. */ cancelViewChange: boolean; } /** * @category Events */ interface BusEventReset extends BusEvent { type: BusEventType.RESTART_CONVERSATION; } /** * @category Events */ interface BusEventChatReady extends BusEvent { type: BusEventType.CHAT_READY; } /** * @category Events */ interface BusEventPreReset extends BusEvent { type: BusEventType.PRE_RESTART_CONVERSATION; } /** * This describes a custom event that can be authored with the button response type of type "option". When clicked, * this event will fire and provide information authored in the custom event. * * @category Events */ interface BusEventMessageItemCustom extends BusEvent { type: BusEventType.MESSAGE_ITEM_CUSTOM; /** * The button item that triggered this custom event. */ messageItem: ButtonItem; /** * The full message response that contained the button item that triggered this custom event. */ fullMessage: MessageResponse; } /** * Used to populate user_defined responses. Please see the React or web component documentation as usage of this * differs based on implementation. * * @category Events */ interface BusEventUserDefinedResponse extends BusEvent { type: BusEventType.USER_DEFINED_RESPONSE; data: { /** * The individual message item that is being displayed in this custom response. */ message: GenericItem; /** * The full message (response or request) that contains the message item. */ fullMessage: Message; /** * The slot name for users of the web components cds-aichat-container or cds-aichat-custom-element. */ slot?: string; /** * The current {@link MessageState} of the containing message at the moment this event * fired. Carbon AI Chat populates this whenever it has a recorded lifecycle state for * the message — including messages produced through * {@link ChatInstanceMessaging.upsertMessage}, {@link ChatInstanceMessaging.addMessage}, * and the final-response transition of {@link ChatInstanceMessaging.addMessageChunk}. * See {@link MessageState} for the lifecycle values. * * @experimental Field is additive; its presence and semantics may evolve as the * lifecycle model stabilizes. */ state?: MessageState; }; } /** * @category Events */ interface BusEventChunkUserDefinedResponse extends BusEvent { type: BusEventType.CHUNK_USER_DEFINED_RESPONSE; data: { /** * The individual message item that is being displayed in this custom response. */ messageItem: DeepPartial; /** * The full chunk that contained the user defined response. */ chunk: PartialOrCompleteItemChunk; /** * The slot name for users of the web components cds-aichat-container or cds-aichat-custom-element. */ slot?: string; }; } /** * Used to populate custom message footer slots. * * @category Events */ interface BusEventCustomFooterSlot extends BusEvent { type: BusEventType.CUSTOM_FOOTER_SLOT; data: { /** * The unique identifier for this footer slot. */ slotName: string; /** * The message item that is being rendered. */ messageItem: GenericItem; /** * The assistant response object that contains the messageItem. */ message: MessageResponse; /** * Any additional data to be passed to the render function. */ additionalData?: unknown; }; } /** * The event is fired whenever the widget begins processing a list of messages that have been loaded from history. * This event may be fired not only when the history is first loaded but it may be fired later during the life of * the widget if additional messages are loaded from history. * * This event is fired when this process begins. This is fired before all the "pre:receive" and "receive" events are * fired which means that the messages here are the original messages before any possible modifications by the event * handlers. * * @category Events */ interface BusEventHistoryBegin extends BusEvent { /** * The discriminating type of this event. */ type: BusEventType.HISTORY_BEGIN; /** * The list of all the messages that are being loaded by this history event. */ messages: Message[]; /** * Indicates that modifications were made to the given messages and that updates to those messages should be saved in * the history store. This is similar to the update behavior of the "pre:receive" event that is handled * automatically. */ updateMessageIDs?: string[]; } /** * The event is fired whenever the widget begins processing a list of messages that have been loaded from history. * This event may be fired not only when the history is first loaded but it may be fired later during the life of * the widget if additional messages are loaded from history. * * This event is fired when this process ends. This is fired after all the "pre:receive" and "receive" events are * fired which means that the messages here are the potentially modified messages after any possible modifications * by the event handlers. * * @category Events */ interface BusEventHistoryEnd extends BusEvent { /** * The discriminating type of this event. */ type: BusEventType.HISTORY_END; /** * The list of all the messages that were loaded by this history event. */ messages: Message[]; } /** * @category Events */ interface BusEventCustomPanelPreOpen extends BusEvent { type: BusEventType.CUSTOM_PANEL_PRE_OPEN; } /** * @category Events */ interface BusEventCustomPanelOpen extends BusEvent { type: BusEventType.CUSTOM_PANEL_OPEN; } /** * @category Events */ interface BusEventCustomPanelPreClose extends BusEvent { type: BusEventType.CUSTOM_PANEL_PRE_CLOSE; } /** * @category Events */ interface BusEventCustomPanelClose extends BusEvent { type: BusEventType.CUSTOM_PANEL_CLOSE; } /** * @category Events * @experimental */ interface BusEventWorkspacePreOpen extends BusEvent { type: BusEventType.WORKSPACE_PRE_OPEN; data: { /** * The ID of the given workspace. */ workspaceId?: string; /** * Additional meta data. */ additionalData?: unknown; /** * The individual message item that is being displayed in this custom response. */ message: GenericItem; /** * The full message response that contains the message item. */ fullMessage: MessageResponse; }; } /** * @category Events * @experimental */ interface BusEventWorkspaceOpen extends BusEvent { type: BusEventType.WORKSPACE_OPEN; data: { /** * The ID of the given workspace. */ workspaceId?: string; /** * Additional meta data. */ additionalData?: unknown; /** * The individual message item that is being displayed in this custom response. */ message: GenericItem; /** * The full message response that contains the message item. */ fullMessage: MessageResponse; }; } /** * @category Events * @experimental */ interface BusEventWorkspacePreClose extends BusEvent { type: BusEventType.WORKSPACE_PRE_CLOSE; data: { /** * The ID of the given workspace. */ workspaceId?: string; /** * Additional meta data. */ additionalData?: unknown; /** * The individual message item that is being displayed in this custom response. */ message: GenericItem; /** * The full message response that contains the message item. */ fullMessage: MessageResponse; }; } /** * @category Events * @experimental */ interface BusEventWorkspaceClose extends BusEvent { type: BusEventType.WORKSPACE_CLOSE; data: { /** * The ID of the given workspace. */ workspaceId?: string; /** * Additional meta data. */ additionalData?: unknown; /** * The individual message item that is being displayed in this custom response. */ message: GenericItem; /** * The full message response that contains the message item. */ fullMessage: MessageResponse; }; } /** * This event is fired before the user is connected to a service desk. This occurs as soon as the user clicks the * "Request agent" button and before any attempt is made to communicate with the service desk. * * @category Service desk */ interface BusEventHumanAgentPreStartChat extends BusEvent { /** * The type of the event. */ type: BusEventType.HUMAN_AGENT_PRE_START_CHAT; /** * The message that was used to trigger the connection to the agent. */ message: MessageResponse; /** * This flag can be set by a listener to indicate that the connection process should be cancelled. */ cancelStartChat?: boolean; /** * Some arbitrary payload of data that will be passed to the service desk when a chat is started. */ preStartChatPayload?: TPayloadType; } /** * This event is fired before a chat with an agent is ended. This occurs after the user has selected "Yes" from the * confirmation modal but it can also be fired if the chat is ended by the agent. * * @category Service desk */ interface BusEventHumanAgentPreEndChat extends BusEvent { /** * The type of the event. */ type: BusEventType.HUMAN_AGENT_PRE_END_CHAT; /** * Indicates if the chat was ended by the agent. */ endedByHumanAgent: boolean; /** * An arbitrary payload object that a listener may set. This payload will be passed to the service desk * ServiceDesk endChat function. */ preEndChatPayload: TPayloadType; /** * This value may be set by a listener to indicate that the process of ending the chat should be cancelled. */ cancelEndChat: boolean; } /** * This event is fired after a chat with an agent has ended. This is fired after {@link BusEventType.HUMAN_AGENT_PRE_END_CHAT} but * can be fired both from the user leaving the chat or the agent ending the chat. * * @category Service desk */ interface BusEventHumanAgentEndChat extends BusEvent { /** * The type of the event. */ type: BusEventType.HUMAN_AGENT_END_CHAT; /** * Indicates if the chat was ended by the agent. */ endedByHumanAgent: boolean; /** * Indicates if the chat was ended because the request for an agent was cancelled or an error occurred while * starting the chat. This means the start never fully started. */ requestCancelled: boolean; } /** * This event is fired after Carbon AI Chat calls "areAnyAgentsOnline" for a service desk. It will report the value returned * from that call. This is particularly useful if some custom code wants to take action if no agents are online. * * @category Service desk */ interface BusEventHumanAgentAreAnyAgentsOnline extends BusEvent { /** * The type of the event. */ type: BusEventType.HUMAN_AGENT_ARE_ANY_AGENTS_ONLINE; /** * The result that was returned from "areAnyAgentsOnline". If an error occurred, this will be * {@link HumanAgentsOnlineStatus.OFFLINE}. */ areAnyAgentsOnline: HumanAgentsOnlineStatus; } /** * The ways the user may interact with the feedback controls. * * @category Events */ declare enum FeedbackInteractionType { /** * Indicates the details popup was opened after the user clicked one of the feedback buttons. */ DETAILS_OPENED = "detailsOpened", /** * Indicates the details popup was closed after the user clicked the "X" button to close it or if the user clicked the * feedback button that opened it. */ DETAILS_CLOSED = "detailsClosed", /** * Indicates feedback was submitted. This includes both when the details panel is open and submitted as well as when * the user clicks a feedback button and the details are not shown. */ SUBMITTED = "submitted" } /** * This event is fired when the user interacts with the feedback controls on a message. This includes both the feedback * buttons (thumbs up/down) as well as the details popup where the user can submit additional information. * * @category Events */ interface BusEventFeedback extends BusEvent { /** * The message item for which feedback was provided. */ messageItem: GenericItem; /** * The message for which feedback was provided. */ message: MessageResponse; /** * Indicates if the user is providing positive or negative feedback. */ isPositive: boolean; /** * The type of interaction the user had with the feedback. */ interactionType: FeedbackInteractionType; /** * When submitting feedback details, this is the text the user entered into the text field (if visible). */ text?: string; /** * When submitting feedback details, this is the list of categories the user selected (if visible). */ categories?: string[]; } /** * This event is fired whenever the public state returned by ChatInstance.getState() changes. * This includes changes to viewState, showUnreadIndicator, and other persisted state. * * @category Events */ interface BusEventStateChange extends BusEvent { /** * The type of the event. */ type: BusEventType.STATE_CHANGE; /** * The previous state before the change. */ previousState: PublicChatState; /** * The new state after the change. */ newState: PublicChatState; } /** * The type of navigation item clicked in the header. * * @category Events */ declare enum HeaderMenuClickType { /** * The homescreen/back button was clicked. */ HOMESCREEN_BUTTON = "homescreenButton", /** * The overflow menu button was clicked (menu opened). */ OVERFLOW_MENU_OPENED = "overflowMenuOpened", /** * An item in the overflow menu was clicked. */ OVERFLOW_MENU_ITEM = "overflowMenuItem" } /** * This event is fired when a user clicks on navigation items in the chat header. * This includes the homescreen button and overflow menu items. * * @category Events */ interface BusEventHeaderMenuClick extends BusEvent { /** * The type of the event. */ type: BusEventType.HEADER_MENU_CLICK; /** * The type of navigation item that was clicked. */ clickType: HeaderMenuClickType; /** * For overflow menu items, this is the index of the item clicked. * For homescreen button, this will be undefined. */ menuItemIndex?: number; /** * For overflow menu items, this is the text label of the item clicked. * For homescreen button, this will be the back button label. */ menuItemText?: string; } /** * The types of corners the chat can have. * * @category Config */ declare enum CornersType { /** * Makes the corners on the chat component rounded. */ ROUND = "round", /** * Makes the corners on the chat component square. */ SQUARE = "square" } /** * Configuration for individual corners using logical property names. * Supports RTL layouts by using start/end instead of left/right. * * Any undefined corner will fall back to the default value (ROUND). * * @category Config */ interface PerCornerConfig { /** * Top-left corner in LTR, top-right in RTL. * Maps to border-start-start-radius. */ startStart?: CornersType; /** * Top-right corner in LTR, top-left in RTL. * Maps to border-start-end-radius. */ startEnd?: CornersType; /** * Bottom-left corner in LTR, bottom-right in RTL. * Maps to border-end-start-radius. */ endStart?: CornersType; /** * Bottom-right corner in LTR, bottom-left in RTL. * Maps to border-end-end-radius. */ endEnd?: CornersType; } /** * Resolved corner configuration with all corners defined. * Used internally after normalizing the user's configuration. * * @category Config */ interface ResolvedCornerConfig { startStart: CornersType; startEnd: CornersType; endStart: CornersType; endEnd: CornersType; } /** * A conversation starter button on the home screen. Currently, only label is provided by tooling. * * @category Config */ interface HomeScreenStarterButton { /** * The display label of the button. This is also the value that is sent as the user's utterance to the assistant * when the button is clicked. */ label: string; /** * Indicates if the button was previously clicked and should be displayed as selected. */ isSelected?: boolean; } /** * Starter buttons that appear on home screen. * * @category Config */ interface HomeScreenStarterButtons { isOn?: boolean; buttons?: HomeScreenStarterButton[]; } /** * Configuration for the optional home screen that appears before the assistant chat window. * * @category Config */ interface HomeScreenConfig { /** * If the home page is turned on via config or remote config. */ isOn?: boolean; /** * The greeting to show to the user to prompt them to start a conversation. */ greeting?: string; /** * Optional conversation starter utterances that are displayed as buttons. */ starters?: HomeScreenStarterButtons; /** * Do not show the greeting or starters. */ customContentOnly?: boolean; /** * Defaults to false. If enabled, a user can not navigate back to the home screen after they have sent a message to the * assistant. If false, the home screen is navigatable after an initial message is sent. */ disableReturn?: boolean; } /** * Current state of home screen (currently, limited to if it is open or closed). * * @category Config */ interface HomeScreenState { /** * Indicates if the home screen is currently open. */ isHomeScreenOpen: boolean; /** * Indicates if the home screen should display a "return to assistant" button. This button is displayed when the user * has clicked the "back to home" button from the assistant. */ showBackToAssistant: boolean; } /** * These variables map to CSS custom properties used in styling the AI chat interface. * * Keys map to the underlying `--cds-aichat-*` custom properties. * * You can use any standard CSS as the value. * * @category Config */ declare enum LayoutCustomProperties { /** * Float layout only. * * Minimum height of the chat container. * * Defaults to `calc(100vh - 4rem)`. */ height = "height", /** * Float layout only. * * Maximum height of the chat container (float layout). * * Defaults to `640px`. */ max_height = "max-height", /** * Float layout only. * * Width of the chat panel (float layout). * * Defaults to `min(380px, var(--cds-aichat-max-width))`. */ width = "width", /** * Float layout only. * * Minimum height of the chat container. * * Defaults to `max(150px, calc(min(256px, 100vh) - var(--cds-aichat-bottom-position)))`. */ min_height = "min-height", /** * Float layout only. * * Maximum width of the chat container (float layout). * * Defaults to the inherited value of `--cds-aichat-max-width` (not explicitly set). */ max_width = "max-width", /** * Float layout only. * * z-index of the chat overlay or container (float layout). * * Defaults to `99999`. */ z_index = "z-index", /** * Float layout only. * * Distance from the bottom of the viewport for the floating container. * * Defaults to `48px`. */ bottom_position = "bottom-position", /** * Float layout only. * * Distance from the right of the viewport for the floating container. * * Defaults to `32px`. */ right_position = "right-position", /** * Float layout only. * * Distance from the top of the viewport for the floating container. * * Defaults to `auto`. */ top_position = "top-position", /** * Float layout only. * * Distance from the left of the viewport for the floating container. * * Defaults to `auto`. */ left_position = "left-position", /** * Float layout only. * * Default launcher button size. * * Defaults to `56px`. */ launcher_default_size = "launcher-default-size", /** * Float layout only. * * Distance from the bottom of the viewport for the launcher. * * Defaults to `48px`. */ launcher_position_bottom = "launcher-position-bottom", /** * Float layout only. * * Distance from the right of the viewport for the launcher. * * Defaults to `32px`. */ launcher_position_right = "launcher-position-right", /** * Float layout only. * * Extended launcher width. * * Defaults to `280px`. */ launcher_extended_width = "launcher-extended-width", /** * Shared token. * * Maximum width for message content area. * * Defaults to `672px`. */ messages_max_width = "messages-max-width", /** * Shared token. * * Minimum width for message content area. * * Defaults to `320px`. */ messages_min_width = "messages-min-width", /** * Shared token. * * Minimum width for workspace panel. * * Defaults to `480px`. */ workspace_min_width = "workspace-min-width", /** * Shared token. * * Maximum width for card components. * * Defaults to `424px`. */ card_max_width = "card-max-width", /** * Shared token. * * Launcher button background color. */ launcher_color_background = "launcher-color-background", /** * Shared token. * * Launcher avatar/icon color. */ launcher_color_avatar = "launcher-color-avatar", /** * Shared token. * * Launcher hover state background color. */ launcher_color_background_hover = "launcher-color-background-hover", /** * Shared token. * * Launcher active state background color. */ launcher_color_background_active = "launcher-color-background-active", /** * Shared token. * * Launcher focus border color. */ launcher_color_focus_border = "launcher-color-focus-border", /** * Shared token. * * Launcher text color on mobile. */ launcher_mobile_color_text = "launcher-mobile-color-text", /** * Shared token. * * Expanded launcher message text color. */ launcher_expanded_message_color_text = "launcher-expanded-message-color-text", /** * Shared token. * * Expanded launcher message background color. */ launcher_expanded_message_color_background = "launcher-expanded-message-color-background", /** * Shared token. * * Expanded launcher message hover background color. */ launcher_expanded_message_color_background_hover = "launcher-expanded-message-color-background-hover", /** * Shared token. * * Expanded launcher message active background color. */ launcher_expanded_message_color_background_active = "launcher-expanded-message-color-background-active", /** * Shared token. * * Expanded launcher message focus border color. */ launcher_expanded_message_color_focus_border = "launcher-expanded-message-color-focus-border", /** * Shared token. * * Unread indicator background color. */ unread_indicator_color_background = "unread-indicator-color-background", /** * Shared token. * * Unread indicator text color. */ unread_indicator_color_text = "unread-indicator-color-text" } /** * Configuration for the launcher. * * @category Config */ interface LauncherConfig { /** * If the launcher is visible. Defaults to true. */ isOn?: boolean; /** * Controls whether the unread indicator dot shows even when no human-agent unread count exists. */ showUnreadIndicator?: boolean; /** * Properties specific to the mobile launcher. */ mobile?: LauncherCallToActionConfig; /** * Properties specific to the desktop launcher. */ desktop?: LauncherCallToActionConfig; } /** * @category Config */ interface LauncherCallToActionConfig { /** * If the launcher will have a call to action expanded state. Defaults to false. This feature will be removed in * the next major release of the AI Chat. * * @deprecated */ isOn?: boolean; /** * The title that will be used by the expanded state of the launcher. If nothing is set in the config then a default * translated string will be used. * * @deprecated */ title?: string; /** * The amount of time to wait before extending the launcher. If nothing is set then the default time of * 15s will be used. * * @deprecated */ timeToExpand?: number; /** * An optional override of the icon shown on the launcher. */ avatarUrlOverride?: string; } /** * Configuration for a keyboard shortcut. * * @category Config * @experimental */ interface ChatShortcutConfig { /** * Whether the keyboard shortcut is enabled. * Default: true */ is_on?: boolean; /** * The primary key (e.g., 'c', 'F6', '/') */ key: string; /** * Modifier keys required to be held */ modifiers: { alt?: boolean; shift?: boolean; ctrl?: boolean; meta?: boolean; }; } /** * Configuration for all keyboard shortcuts in the chat. * Designed to be extensible for future shortcuts. * * @category Config * @experimental */ interface KeyboardShortcuts { /** * Shortcut to toggle focus between the message list and input field. * Default: F6 (standard Windows accessibility shortcut for cycling between regions) */ messageFocusToggle?: ChatShortcutConfig; } /** * This file contains the definition for the public application configuration operations that are provided by the * host page. */ /** * The raw strings used for {@link PublicConfig.strings}. Presented in ICU format. * * @category Config */ declare const enLanguagePack: { ai_slug_label: string; ai_slug_title: string; ai_slug_description: string; components_overflow_ariaLabel: string; components_swiper_currentLabel: string; errors_communicating: string; errors_imageSource: string; errors_videoSource: string; errors_audioSource: string; media_audioPlayer_loading: string; media_audioPlayer_ready: string; media_audioPlayer_loadingLabel: string; media_audioPlayer_readyLabel: string; media_audioPlayer_errorLabel: string; media_videoPlayer_loading: string; media_videoPlayer_ready: string; media_videoPlayer_loadingLabel: string; media_videoPlayer_readyLabel: string; media_videoPlayer_errorLabel: string; errors_iframeSource: string; errors_singleMessage: string; errors_ariaMessageRetrying: string; errors_ariaMessageFailed: string; errors_noHumanAgentsAvailable: string; errors_noHumanAgentsJoined: string; errors_connectingToHumanAgent: string; errors_busy: string; errors_agentAppSessionExpired: string; errors_generalContent: string; errors_somethingWrong: string; input_ariaLabel: string; input_placeholder: string; input_buttonLabel: string; input_uploadButtonLabel: string; input_sendingMessage: string; input_keyboardShortcutAnnouncement: string; window_title: string; window_ariaChatRegion: string; window_ariaChatRegionNamespace: string; window_ariaWindowOpened: string; window_ariaWindowClosed: string; window_ariaWindowLoading: string; launcher_isOpen: string; launcher_isClosed: string; launcher_desktopGreeting: string; launcher_mobileGreeting: string; launcher_ariaIsExpanded: string; launcher_closeButton: string; media_transcript_label: string; media_transcript_show: string; media_transcript_hide: string; messages_youSaid: string; messages_assistantSaid: string; messages_agentSaid: string; messages_searchResults: string; messages_searchResultsLink: string; messages_searchResultsOpenDocument: string; messages_searchResultsOpenDocumentWithLabel: string; messages_searchResultsExpand: string; messages_searchResultsCollapse: string; messages_assistantIsLoading: string; messages_agentIsTyping: string; messages_focusHandle: string; messages_processingLabel: string; messages_scrollHandle: string; messages_scrollHandleDetailed: string; messages_scrollHandleDetailedNoShortcut: string; messages_scrollHandleEnd: string; messages_scrollHandleEndDetailed: string; messages_scrollHandleEndDetailedNoShortcut: string; messages_scrollMoreButton: string; messages_reasoningStart: string; messages_streamingStart: string; message_labelAssistant: string; message_labelYou: string; buttons_restart: string; buttons_cancel: string; buttons_retry: string; options_select: string; options_ariaOptionsDisabled: string; header_previewLinkTitle: string; header_ariaAssistantAvatar: string; header_overflowMenu_options: string; history_view_chats: string; history_new_chat: string; homeScreen_returnToAssistant: string; homeScreen_returnToHome: string; homeScreen_overflowMenuHomeScreen: string; homeScreen_ariaQuickStartListButton: string; homeScreen_ariaQuickStartListOpened: string; homeScreen_ariaQuickStartListClosed: string; homeScreen_ariaHomeScreenContent: string; homeScreen_shown: string; homeScreen_hidden: string; default_agent_availableMessage: string; default_agent_unavailableMessage: string; agent_reason_error: string; agent_sdMissingWarning: string; agent_noName: string; agent_chatTitle: string; agent_startChat: string; agent_connecting: string; agent_agentNoNameTitle: string; agent_agentJoinedName: string; agent_agentJoinedNoName: string; agent_youConnectedWarning: string; agent_connectingMinutes: string; agent_connectingQueue: string; agent_ariaHumanAgentAvatar: string; agent_ariaGenericAvatar: string; agent_ariaGenericAssistantAvatar: string; agent_youEndedChat: string; agent_conversationWasEnded: string; agent_disconnected: string; agent_reconnected: string; agent_agentLeftChat: string; agent_agentLeftChatNoName: string; agent_agentEndedChat: string; agent_agentEndedChatNoName: string; agent_transferring: string; agent_transferringNoName: string; agent_endChat: string; agent_confirmSuspendedEndChatTitle: string; agent_confirmSuspendedEndChatMessage: string; agent_confirmCancelRequestTitle: string; agent_confirmCancelRequestMessage: string; agent_confirmCancelRequestNo: string; agent_confirmCancelRequestYes: string; agent_confirmEndChat: string; agent_confirmEndChatNo: string; agent_confirmEndChatYes: string; agent_confirmEndSuspendedYes: string; agent_assistantReturned: string; agent_newMessage: string; agent_cardButtonChatRequested: string; agent_cardButtonConnected: string; agent_cardButtonChatEnded: string; agent_cardMessageChatEnded: string; agent_cardMessageConnected: string; agent_connectButtonCancel: string; agent_connectedButtonEndChat: string; agent_connectWaiting: string; agent_defaultMessageToHumanAgent: string; agent_inputPlaceholderConnecting: string; agent_inputPlaceholderReconnecting: string; agent_sharingStopSharingButton: string; agent_sharingRequestTitle: string; agent_sharingRequestMessage: string; agent_sharingAcceptButton: string; agent_sharingDeclineButton: string; agent_sharingRequested: string; agent_sharingAccepted: string; agent_sharingDeclined: string; agent_sharingCancelled: string; agent_sharingEnded: string; agent_suspendedWarning: string; icon_ariaUnreadMessages: string; showMore: string; showMoreResults: string; disclaimer_title: string; disclaimer_accept: string; disclaimer_icon_label: string; disclaimer_acceptance_label: string; general_ariaCloseInformationOverlay: string; general_ariaAnnounceOpenedInformationOverlay: string; general_ariaAnnounceClosedInformationOverlay: string; general_ariaAnnounceEscapeOverlay: string; general_returnToAssistant: string; conversationalSearch_streamingIncomplete: string; conversationalSearch_viewSourceDocument: string; conversationalSearch_citationsLabel: string; conversationalSearch_toggleCitations: string; conversationalSearch_responseStopped: string; iframe_ariaSourceLoaded: string; iframe_ariaImageAltText: string; iframe_ariaClosePanel: string; iframe_ariaOpenedPanel: string; iframe_ariaClosedPanel: string; iframe_ariaClickPreviewCard: string; datePicker_chooseDate: string; datePicker_confirmDate: string; fileSharing_fileTooLarge: string; fileSharing_ariaAnnounceSuccess: string; fileSharing_fileIcon: string; fileSharing_removeButtonTitle: string; fileSharing_statusUploading: string; fileSharing_uploadFailed: string; fileSharing_agentMessageText: string; fileSharing_request: string; carousel_prevNavButton: string; carousel_nextNavButton: string; input_completionsTagApp: string; input_completionsTagAssistant: string; table_filterPlaceholder: string; table_previousPage: string; table_nextPage: string; table_itemsPerPage: string; table_paginationSupplementalText: string; table_paginationStatus: string; codeSnippet_feedback: string; codeSnippet_showLessText: string; codeSnippet_showMoreText: string; codeSnippet_tooltipContent: string; codeSnippet_lineCount: string; codeSnippet_foldCollapse: string; codeSnippet_foldExpand: string; codeSnippet_ariaLabelReadOnly: string; codeSnippet_ariaLabelReadOnlyWithLanguage: string; codeSnippet_ariaLabelEditable: string; codeSnippet_ariaLabelEditableWithLanguage: string; table_downloadButton: string; feedback_positiveLabel: string; feedback_negativeLabel: string; feedback_defaultTitle: string; feedback_defaultPrompt: string; feedback_defaultPlaceholder: string; feedback_categoriesLabel: string; feedback_submitLabel: string; feedback_cancelLabel: string; input_stopResponse: string; messages_responseStopped: string; messages_requestCancelled: string; chainOfThought_stepTitle: string; chainOfThought_inputLabel: string; chainOfThought_outputLabel: string; chainOfThought_toolLabel: string; chainOfThought_statusSucceededLabel: string; chainOfThought_statusFailedLabel: string; chainOfThought_statusProcessingLabel: string; chainOfThought_explainabilityLabel: string; reasoningSteps_mainLabelOpen: string; reasoningSteps_mainLabelClosed: string; workspace_opened: string; workspace_opened_no_title: string; workspace_closed: string; panel_opened: string; panel_closed: string; history_shown: string; history_hidden: string; aria_workspaceRegion: string; aria_historyRegion: string; aria_messagesRegion: string; aria_catastrophicErrorPanel: string; aria_hydrationPanel: string; aria_customPanel: string; aria_disclaimerPanel: string; aria_responsePanel: string; aria_iframePanel: string; aria_viewSourcePanel: string; }; /** * A language pack represents the set of display strings for a particular language. * It defines all the text strings that can be customized for different languages. * * @category Config */ type LanguagePack = typeof enLanguagePack; /** * Configuration interface for Carbon AI Chat. * * @category Config */ interface PublicConfig { /** * This is a one-off listener for catastrophic errors. This is used instead of a normal event bus handler because this function can be * defined and called before the event bus has been created. */ onError?: (data: OnErrorData) => void; /** * By default, the chat window will be rendered in a "closed" state. */ openChatByDefault?: boolean; /** * Disclaimer screen configuration. * * If `disclaimerHTML` changes after the disclaimer has been accepted, we request a user to accept again. */ disclaimer?: DisclaimerPublicConfig; /** * This value is only used when a custom element is being used to render the widget. By default, a number of * enhancements to the widget are activated on mobile devices which can interfere with a custom element. This * value can be used to disable those enhancements while using a custom element. */ disableCustomElementMobileEnhancements?: boolean; /** * Add a bunch of noisy console.log messages! */ debug?: boolean; /** * Which Carbon theme tokens to inject. If unset (falsy), the chat inherits tokens from the host page. * Set to a specific theme to force token injection. */ injectCarbonTheme?: CarbonTheme; /** * Enables Carbon AI theme styling. Defaults to true. */ aiEnabled?: boolean; /** * This is a factory for producing custom implementations of service desks. If this value is set, then this will * be used to create an instance of a {@link ServiceDesk} when the user attempts to connect to an agent. * * If it is changed in the middle of a conversation (you should obviously avoid this) the conversation with the * human agent will be disconnected. */ serviceDeskFactory?: (parameters: ServiceDeskFactoryParameters) => Promise; /** * Any public config to apply to service desks. */ serviceDesk?: ServiceDeskPublicConfig; /** * If the Carbon AI Chat should grab focus if the chat is open on page load. */ shouldTakeFocusIfOpensAutomatically?: boolean; /** * An optional namespace that can be added to the Carbon AI Chat that must be 30 characters or under. This value is * intended to enable multiple instances of the Carbon AI Chat to be used on the same page. The namespace for this web * chat. This value is used to generate a value to append to anything unique (id, session keys, etc) to allow * multiple Carbon AI Chats on the same page. * * Note: this value is used in the aria region label for the Carbon AI Chat. This means this value will be read out loud * by users using a screen reader. */ namespace?: string; /** * Indicates if Carbon AI Chat should sanitize HTML from the assistant. */ shouldSanitizeHTML?: boolean; /** * Extra config for controlling the behavior of the header. */ header?: HeaderConfig; /** * The config object for chat history. */ history?: HistoryConfig; /** * The config object for changing Carbon AI Chat's layout. */ layout?: LayoutConfig; /** * Config options for controlling messaging. */ messaging?: PublicConfigMessaging; /** * Sets the chat into a read only mode for displaying old conversations. */ isReadonly?: boolean; /** * Allows for feedback to persist in all messages, not just the latest message. */ persistFeedback?: boolean; /** * Sets the name of the assistant. Defaults to "watsonx". Used in screen reader announcements and error messages. */ assistantName?: string; /** * Sets the URL pointing to a custom avatar for the response author. This image should be a square. If not provided, the default Watsonx icon will be used. */ assistantAvatarUrl?: string; /** * The locale to use for the widget. This controls the language pack and regional formatting. * Example values include: 'en', 'en-us', 'fr', 'es'. */ locale?: string; /** * Configuration for the homescreen. * * If you change anything but `is_on` after the chat session has started, the chat will handle it gracefully. * * If you turn on the homescreen after the user has already started chatting, it will show up in the header as * an icon, but the user won't be forced to go back to the homescreen (unlike turning on the disclaimer mid-chat). */ homescreen?: HomeScreenConfig; /** * Configuration for the launcher. */ launcher?: LauncherConfig; /** * Configuration for the main input field on the chat. */ input?: InputConfig; /** * Configuration for file upload behavior in the chat input. * When `is_on` is `true`, the chat renders a file attachment button in the input area. * * @experimental */ upload?: UploadConfig; /** * Optional partial language pack overrides. Values merge with defaults. */ strings?: DeepPartial; /** * Configuration for keyboard shortcuts in the chat. * Allows customization of keyboard shortcuts for various actions. * * @experimental */ keyboardShortcuts?: KeyboardShortcuts; /** * Markdown rendering customization. The framework-neutral subset; React and * web-component layers extend this with their own `customRenderers` member. * * @experimental */ markdown?: PublicConfigMarkdown; } /** * Element type of {@link PublicConfigMarkdown.markdownItPlugins}. Either a * bare plugin function or a `[plugin, options]` / `[plugin, ...params]` tuple * matching `MarkdownIt.use(...)`. * * @category Config * @experimental */ type MarkdownItPlugin = MarkdownItPlugin$1; /** * Framework-neutral markdown configuration shared by the React `ChatContainer` * and the `cds-aichat-container` web component. Each layer extends this with * its own `customRenderers` member returning the layer-appropriate type * (`ReactNode` vs `HTMLElement | null`). * * @category Config * @experimental */ interface PublicConfigMarkdown { /** * Markdown-it plugins applied after the built-in plugins * (markdown-it-attrs, markdown-it-highlight, markdown-it-task-lists). * Memoize this array — a new reference each render rebuilds the * markdown-it instance. * * @experimental */ markdownItPlugins?: MarkdownItPlugin[]; } /** * A single menu option. * * @category Config */ interface CustomMenuOption { /** * The text to display for the menu option. */ text: string; /** * The callback handler to call when the option is selected. * Provide either this or `href`, but not both. */ handler?: () => void; /** * The URL to navigate to when the option is selected. * Provide either this or `handler`, but not both. */ href?: string; /** * The target attribute for the link when using `href`. * Defaults to "_self" if not specified. * Common values: "_self", "_blank", "_parent", "_top" */ target?: string; /** * If true, the menu option will be disabled and cannot be selected. */ disabled?: boolean; /** * Optional data-testid attribute for testing purposes. * This allows tests to reliably find and interact with specific menu options. */ testId?: string; } /** * @category Config */ declare enum MinimizeButtonIconType { /** * This shows an "X" icon. */ CLOSE = "close", /** * This shows a "-" icon. */ MINIMIZE = "minimize", /** * This shows an icon that indicates that the Carbon AI Chat can be collapsed into a side panel. */ SIDE_PANEL_LEFT = "side-panel-left", /** * This shows an icon that indicates that the Carbon AI Chat can be collapsed into a side panel. */ SIDE_PANEL_RIGHT = "side-panel-right", /** * This shows an icon that indicates that the Carbon AI Chat can be collapsed into a side panel. */ SIDE_PANEL_DOWN = "side-panel-down" } /** * Configuration for the input field in the main chat and homescreen. * * @category Config */ interface InputConfig { /** * The maximum number of characters allowed in the input field. Defaults to 10000. */ maxInputCharacters?: number; /** * Controls whether the main input surface is visible when the chat loads. * Defaults to true. */ isVisible?: boolean; /** * If true, the main input surface starts in a disabled (read-only) state. * Equivalent to {@link PublicConfig.isReadonly}, but scoped just to the assistant input. */ isDisabled?: boolean; } /** * Configuration for file upload behavior in the chat input. * * @experimental * @category Config */ interface UploadConfig { /** * Whether file upload is enabled. When `true`, the chat renders a file attachment button * in the input area. Defaults to `false`. * * If `is_on` is `true` but `onFileUpload` is not provided, an error is logged and * file upload is disabled. */ is_on: boolean; /** * Accepted MIME types or file extensions, in the same format as the HTML `accept` attribute. * Examples: `"image/*"`, `".pdf,.docx"`, `"application/pdf"`. * If omitted, all file types are accepted. */ accept?: string; /** * Maximum file size in bytes. Files exceeding this limit are rejected client-side * before `onFileUpload` is called. */ maxFileSizeBytes?: number; /** * Maximum number of files that can be attached at once. If omitted, there is no limit. */ maxFiles?: number; /** * Called once per file when the user selects it. * * Return a {@link StructuredData} object representing this file's contribution to the * pending message. The widget merges the returned `StructuredData` into * `pendingStructuredData` and tracks it per-upload so that individual files can be * removed before the message is sent. * * On failure: throw or return a rejected `Promise` — the widget marks the file as * errored in the UI. * * @param file - The `File` object selected by the user. * @param abortSignal - Fires if the user removes the pending upload before it * completes, or if the chat is destroyed. * * @experimental */ onFileUpload?: (file: File, abortSignal: AbortSignal) => Promise; } /** * Configuration for the main header of the chat. * * @category Config */ interface HeaderConfig { /** * If the chat should supply its own header. Can be false if you have a fullscreen chat or one embedded into a page and * you want to only make use of the main application header. Defaults to true. */ isOn?: boolean; /** * Indicates the icon to use for the close button in the header. */ minimizeButtonIconType?: MinimizeButtonIconType; /** * Hide the ability to minimize the Carbon AI Chat. */ hideMinimizeButton?: boolean; /** * If true, shows the restart conversation button in the header of home screen and main chat. */ showRestartButton?: boolean; /** * The chat header title. */ title?: string; /** * The name displayed after the title. */ name?: string; /** * All the currently configured custom menu options. */ menuOptions?: CustomMenuOption[]; /** * Controls whether to show the AI label/slug in the header. Defaults to true. * * There is currently no version of this that does not include the AI theme * blue gradients. */ showAiLabel?: boolean; /** * Controls whether the default AI label content should be hidden. * The default content is only meant to serve as a placeholder and should be * replaced with custom content using: * {@link WriteableElementName.EXPLAINABILITY_POPOVER_CONTENT} and * {@link WriteableElementName.EXPLAINABILITY_POPOVER_ACTIONS}. * When set to true, all the default ai label content including the deprecated * {@link WriteableElementName.AI_TOOLTIP_AFTER_DESCRIPTION_ELEMENT} * writeable element will be removed. * * @default false */ hideDefaultAiLabelContent?: boolean; /** * Controls whether the header should be constrained to the messages max width * (--cds-aichat-messages-max-width) or go full width. When true, the header * will be constrained to match the message width. When false (default), the * header will span the full width of the chat container. * * @default false */ hasContentMaxWidth?: boolean; /** * Custom actions to display in the header toolbar. These actions can overflow * into a menu when space is limited. * * The icon property accepts CarbonIcon objects (from @carbon/web-components) or * React icon components (from @carbon/icons-react). * * Built-in buttons (restart, close) will be appended after these custom actions if * configured to be shown. You can, of course, disabled those OOTB icons and replace * them with your own. */ actions?: ToolbarAction[]; } /** * Configuration for the history panel of the chat. * * @category Config */ interface HistoryConfig { /** * Indicates if the history panel should be shown. */ isOn?: boolean; /** * Controls whether the mobile menu options (New chat, View chats) should be shown * in the header when the history panel is in mobile mode. * * When true (default), the mobile menu will appear in the header on small screens, * providing quick access to start a new chat or view chat history. * * When false, the mobile menu will be hidden even when in mobile mode. * * @default true */ showMobileMenu?: boolean; /** * Controls whether history starts closed and enables state preservation across mode changes. * * When false (default): * - Desktop starts open, mobile starts closed * - Resizing between modes resets to default state * * When true: * - Both desktop and mobile start closed * - User's open/closed state is preserved when resizing between modes * - Enables external control via: instance.customPanels.getPanel(PanelType.HISTORY).open()/close() * * @default false */ startClosed?: boolean; } /** * @category Config */ interface LayoutConfig { /** * Indicates if the Carbon AI Chat widget should keep its border and box-shadow. */ showFrame?: boolean; /** * Indicates if content inside the Carbon AI Chat widget should be constrained to a max-width. * * At larger widths the card, carousel, options and conversational search response types * have pending issues. */ hasContentMaxWidth?: boolean; /** * Controls the corner style of the chat component. * * Can be a simple CornersType value to apply to all corners: * ```typescript * corners: CornersType.ROUND * ``` * * Or a PerCornerConfig object to control each corner individually: * ```typescript * corners: { * startStart: CornersType.ROUND, // top-left in LTR * startEnd: CornersType.ROUND, // top-right in LTR * endStart: CornersType.SQUARE, // bottom-left in LTR * endEnd: CornersType.SQUARE // bottom-right in LTR * } * ``` * * Undefined corners in PerCornerConfig will fall back to CornersType.ROUND. */ corners?: CornersType | PerCornerConfig; /** * CSS variable overrides for the chat UI. This is a convienience method, you may also set these properties via CSS. * * Keys correspond to values from `LayoutCustomProperties` (e.g. `LayoutCustomProperties.height`), * which map to the underlying `--cds-aichat-…` custom properties. * Values are raw CSS values such as `"420px"`, `"9999"`, etc. * * Example: * { height: "560px", width: "420px" } */ customProperties?: Partial>; } /** * Config options for controlling messaging. * * @category Config */ interface PublicConfigMessaging { /** * Indicates if Carbon AI Chat should make a request for the welcome message when a new conversation begins. If this is * true, then Carbon AI Chat will start with an empty conversation. * * **Manual session management required**: Changes to this property after conversation has started have no effect. * To apply new welcome behavior, call `instance.messaging.restartConversation()`. */ skipWelcome?: boolean; /** * Changes the timeout used by the message service when making message calls. The timeout is in seconds. The * default is 150 seconds. After this time, an error will be shown in the client and an Abort signal will be sent * to customSendMessage. If set to 0, the chat will never timeout. This is tied to either {@link ChatInstanceMessaging.addMessage} or * {@link ChatInstanceMessaging.addMessageChunk} being called after this message was sent. If neither of those methods * are called with in the window defined here, the chat will timeout (unless the value is set to 0). */ messageTimeoutSecs?: number; /** * Controls how long AI chat should wait before showing the loading indicator. If set to 0, the chat will never show * the loading indicator on its own. This is tied to either {@link ChatInstanceMessaging.addMessage} or * {@link ChatInstanceMessaging.addMessageChunk} being called after this message was sent. If neither of those methods * are called with in the window defined here, the loading indicator will be shown. */ messageLoadingIndicatorTimeoutSecs?: number; /** * A callback for Carbon AI Chat to use to send messages to your assistant. * * Carbon AI Chat will queue up any additional user messages until the Promise from a previous call to customSendMessage * has resolved. If you do not make customSendMessage async, it will be up to you to manage what happens when a message is * sent when the previous is still processing. If the Promise rejects, an error indicator will be displayed next to the user's message. * * If the request takes longer than PublicConfigMessaging.messageTimeoutSecs than the AbortSignal will be sent. */ customSendMessage?: (request: MessageRequest, requestOptions: CustomSendMessageOptions, instance: ChatInstance) => Promise | void; /** * This is a callback function that is used by Carbon AI Chat to retrieve history data for populating the Carbon AI Chat. If * this function is defined, it will be used instead of any other mechanism for fetching history. * * If this function is mutated after it was initially called, the chat does not re-call it. */ customLoadHistory?: (instance: ChatInstance) => Promise; /** * Controls when the stop streaming button becomes visible during message streaming. * * You must have {@link PublicConfigMessaging.customSendMessage} return a promise for * this setting to work correctly. * * When `true`, the stop button appears immediately when `customSendMessage` is called, * allowing users to cancel requests before the first streaming chunk arrives. This is * useful for slow-starting requests or when you want to give users immediate control * over long-running operations. The button will remain visible as long as there is an * active streaming message, even if the initial message promise resolves. * * When `false` (default), the stop button only appears after the first streaming chunk * arrives with `cancellable: true` metadata, maintaining backward compatibility with * existing behavior. * */ showStopButtonImmediately?: boolean; } /** * @category Config */ interface DisclaimerPublicConfig { /** * If the disclaimer is turned on. */ isOn: boolean; /** * HTML content to show in disclaimer. */ disclaimerHTML: string; } /** * A string identifying what Carbon Theme we should base UI variables off of. * Defaults to "inherit". If you are not hosting the chat on a website that is Carbon styles, you will want to choose * once of the non-inherited values to inject the correct CSS custom property values into the code. See * https://carbondesignsystem.com/guidelines/color/tokens. * * @category Config */ declare enum CarbonTheme { /** * Injects Carbon white theme tokens. */ WHITE = "white", /** * Injects Carbon Gray 10 theme tokens. */ G10 = "g10", /** * Injects Carbon Gray 90 theme tokens. */ G90 = "g90", /** * Injects Carbon Gray 100 theme tokens. */ G100 = "g100" } /** * The different categories of errors that the system can record. These values are published for end user consumption. * * @category Config */ declare enum OnErrorType { /** * Indicates an error sending a message to the assistant. This error is only generated after all retries have * failed and the system has given up. */ MESSAGE_COMMUNICATION = "MESSAGE_COMMUNICATION", /** * This indicates an error in one of the components that occurs as part of rendering the UI. */ RENDER = "RENDER", /** * This indicates a known error with the configuration for a service desk. Fired when a connect_to_agent * response type is received, but none is configured. */ INTEGRATION_ERROR = "INTEGRATION_ERROR", /** * This indicates that some error occurred while trying to hydrate the chat. This will prevent the chat from * functioning. */ HYDRATION = "HYDRATION" } /** * Fired when a serious error in the chat occurs. * * @category Config */ interface OnErrorData { /** * The type of error that occurred. */ errorType: OnErrorType; /** * A message associated with the error. */ message: string; /** * An extra blob of data associated with the error. This may be a stack trace for thrown errors. */ otherData?: unknown; /** * If the error is of the severity that requires a whole restart of Carbon AI Chat. */ catastrophicErrorType?: boolean; } /** * A TypeScript definition file for ObjectMap. */ /** * This interface represents an object which behaves like a map. The object contains a set of properties representing * keys in the map and the values of those properties are all of the same type (TPropertyType). The type of the keys * defaults to any string but you can specify a type that is a string enum instead if you want a map that contains * only keys for a given enum (or other similar type). * * @category Utilities */ type ObjectMap = Partial>; /** * The subset of HumanAgentState that is persisted to browser storage. * * @category Instance */ interface PersistedHumanAgentState { /** Indicates that the user is connected to a human agent. */ isConnected: boolean; /** Indicates if the human agent conversation is currently suspended. */ isSuspended: boolean; /** The profile of the last human agent to join the chat. */ responseUserProfile?: ResponseUserProfile; /** Cache of known agent profiles by ID. */ responseUserProfiles: Record; /** Arbitrary state saved by the service desk. */ serviceDeskState?: unknown; } /** * Items stored in sessionStorage. * * @category Instance */ interface PersistedState { /** * Indicates if this state was loaded from browser session storage or if was created as part of a new session. */ wasLoadedFromBrowser: boolean; /** * The version of the Carbon AI Chat that this data is persisted for. If there are any breaking changes to the * application state and a user reloads and gets a new version of the widget, bad things might happen so we'll * just invalidate the persisted storage if we ever attempt to load an old version on Carbon AI Chat startup. */ version: string; /** * Indicates which of the Carbon AI Chat views are visible and which are hidden. */ viewState: ViewState; /** * Indicates if we should show an unread indicator on the launcher. This is set by * {@link ChatInstance.updateAssistantUnreadIndicatorVisibility} and will display an empty circle on * the launcher. This setting is overridden if there are any unread human agent messages in which case a circle * with a number is displayed. */ showUnreadIndicator: boolean; /** * Indicates if the launcher should be in the expanded state. */ launcherIsExpanded: boolean; /** * Determines if the launcher should start a timer to show its expanded state. */ launcherShouldStartCallToActionCounterIfEnabled: boolean; /** * If the user has received a message beyond the welcome node. We use this to mark if the chat has been interacted * with. This flag is duplicated so the information is available before hydration and before the user is known. * Note that this property reflects only the last user and should only be used when an approximate value is * acceptable. */ hasSentNonWelcomeMessage: boolean; /** * Map of if a disclaimer has been accepted on a given window.hostname value, keyed by hostname via * {@link ObjectMap}. */ disclaimersAccepted: ObjectMap; /** * State of home screen. */ homeScreenState: HomeScreenState; /** * The persisted subset of the human agent state. */ humanAgentState: PersistedHumanAgentState; } /** * The state information for a catastrophic error panel. * * @category Instance */ interface CatastrophicErrorPanelState { /** * Whether the catastrophic error panel is currently open. */ isOpen: boolean; /** * The error title to be displayed in the `CatastrophicErrorPanel`. */ title?: string; /** * The error body text to be displayed in the `CatastrophicErrorPanel`. Will render markdown if provided. */ bodyText?: string; /** * When true, the panel renders without the built-in retry button. The consumer is then responsible * for closing the panel by calling `instance.updateCatastrophicErrorPanel({ isOpen: false })` once * their own recovery flow completes. */ hideRetryButton?: boolean; } /** * Options for controlling how the scrolling occurs. * * @category Instance */ interface AutoScrollOptions { /** * Indicates that the container should scroll to the given "scroll bottom" value meaning the content is scrolled down * from the top by that amount. A value of 0 will scroll to the very top. */ scrollToTop?: number; /** * Indicates that the container should scroll to the given "scroll bottom" value meaning the content is scrolled up * from the bottom by that amount. A value of 0 will scroll to the very bottom. */ scrollToBottom?: number; /** * If appropriate, prefer animations. */ preferAnimate?: true; } /** * The interface represents the API contract with the chat widget and contains all the public methods and properties * that can be used with Carbon AI Chat. * * @category Instance */ interface ChatInstance extends EventHandlers, ChatActions { /** * Returns state information of the Carbon AI Chat that could be useful. */ getState: () => PublicChatState; /** * Manager for accessing and controlling custom panels. */ customPanels?: CustomPanels; } /** * This is the state made available by calling {@link ChatInstance.getState}. This is a public method that returns immutable values. * * @category Instance */ interface PublicInputState { /** * @experimental Raw text currently queued in the input before being sent to customSendMessage. */ rawValue: string; /** * A snapshot of the pending structured data currently queued in the input. This data will be merged * into the next outgoing {@link MessageRequest} when the user sends a message via the UI. * * @experimental */ structuredData?: StructuredData; /** * `true` while one or more file uploads initiated via {@link UploadConfig.onFileUpload} are still * in progress. The send button is disabled while this is `true`. * * @experimental */ hasInFlightUploads: boolean; } /** * Represents public state for default custom panel. * * @category Instance */ interface PublicDefaultCustomPanelState { /** Indicates if the default custom panel overlay is currently open. */ isOpen: boolean; } /** * Represents public state for workspace custom panel. * * @category Instance */ interface PublicWorkspaceCustomPanelState { /** Indicates if the workspace custom panel overlay is currently open. */ isOpen: boolean; /** * Config options for the workspace panels. */ options: WorkspaceCustomPanelConfigOptions; /** * The ID of the workspace attached to this panel. Used to match with a given Preview Card. */ workspaceID?: string; /** * Additional metadata associated with the workspace. */ additionalData?: unknown; } /** * Represents public state for history panel. * * @category Instance */ interface PublicHistoryPanelState { /** Indicates if the history panel is currently open. */ isOpen: boolean; /** Indicates if the history panel should open in chat panel. */ isMobile: boolean; } /** * Represents public state for each supported custom panel variant. * * @category Instance */ interface PublicCustomPanelsState { /** State for the default overlay-style custom panel. */ default: PublicDefaultCustomPanelState; /** * State for the workspace custom panel. * * @experimental */ workspace: PublicWorkspaceCustomPanelState; /** * State for the history panel. */ history: PublicHistoryPanelState; } /** * Type returned by {@link ChatInstance.getState}. * * @category Instance */ type PublicChatState = Readonly & { /** * Current human agent state. */ humanAgent: PublicChatHumanAgentState; /** * Counter that indicates if a message is loading and a loading indicator should be displayed. * If "0" then we do not show loading indicator. */ isMessageLoadingCounter: number; /** * Optional string to display next to the loading indicator. */ isMessageLoadingText?: string; /** * Counter that indicates if the chat is hydrating and a full screen loading state should be displayed. */ isHydratingCounter: number; /** * The message id of the currently active response. The "active response" is the latest response that has been * received or is expected. For instance, if you send another message the current activeResponseId will be set to * null until you get a new response back. This is meant to be used to disable any user inputs in a user_defined * response that you don't want active if its not a message you should be receiving inputs from. */ activeResponseId: string | null; /** * @experimental State representing the main input surface. */ input: PublicInputState; /** * State for any surfaced custom panels. */ customPanels: PublicCustomPanelsState; /** * State for the workspace panel. * * @experimental */ workspace: PublicWorkspaceCustomPanelState; }>; /** * Methods for controlling the input field. * * @category Instance */ interface ChatInstanceInput { /** * @experimental Updates the raw text queued in the input before it is sent to customSendMessage. * Use this when you want to manipulate the canonical value while leaving presentation up to the default renderer or, * in the future, a custom slot implementation. * * @example * ```ts * instance.input.updateRawValue((prev) => `${prev} @celeste`); * ``` */ updateRawValue: (updater: (previous: string) => string) => void; /** * Updates the pending structured data that will be merged into the next outgoing {@link MessageRequest} * when the user sends a message via the UI send button or Enter key. The updater function receives the * current pending structured data (or `undefined` if none is set) and should return the new value. * Return `undefined` to clear the pending structured data. * * This is the primary mechanism for pushing structured inputs (form fields, file references, etc.) * into the active input so they are included when the user hits Send. * * @example * ```ts * // Add a field to the pending structured data * instance.input.updateStructuredData((prev) => ({ * ...prev, * fields: [ * ...(prev?.fields ?? []), * { id: 'rating', type: 'number', value: 4 } * ] * })); * * // Replace all pending structured data * instance.input.updateStructuredData(() => ({ * fields: [{ id: 'selection', type: 'multi_select', value: ['a', 'b'] }] * })); * * // Clear pending structured data * instance.input.updateStructuredData(() => undefined); * ``` * * @experimental */ updateStructuredData: (updater: (previous: StructuredData | undefined) => StructuredData | undefined) => void; } /** * Current connection state of the human agent experience. * * @category Instance */ type PublicChatHumanAgentState = Readonly; /** * This is a subset of the public interface that is managed by the event bus that is used for registering and * unregistering event listeners on the bus. * * @category Instance */ interface EventHandlers { /** * Adds the given event handler as a listener for events of the given type. * * @param handlers The handler or handlers along with the event type to start listening for events. * @returns The instance for method chaining. */ on: (handlers: TypeAndHandler | TypeAndHandler[]) => EventHandlers; /** * Removes an event listener that was previously added via {@link on} or {@link once}. * * @param handlers The handler or handlers along with the event type to stop listening for events. * @returns The instance for method chaining. */ off: (handlers: TypeAndHandler | TypeAndHandler[]) => EventHandlers; /** * Adds the given event handler as a listener for events of the given type. After the first event is handled, this * handler will automatically be removed. * * @param handlers The handler or handlers along with the event type to start listening for an event. * @returns The instance for method chaining. */ once: (handlers: TypeAndHandler | TypeAndHandler[]) => EventHandlers; } /** * The type of handler for event bus events. This function may return a Promise in which case, the bus will await * the result and the loop will block until the Promise is resolved. * * @category Instance */ type EventBusHandler = (event: T, instance: ChatInstance) => unknown; /** * The type of the object that is passed to the event bus functions (e.g. "on") when registering a handler. * * @category Instance */ interface TypeAndHandler { /** * The type of event this handler is for. */ type: BusEventType; /** * The handler for events of this type. */ handler: EventBusHandler; } /** * This is a subset of the public interface that provides methods that can be used by the user to control the widget * and have it perform certain actions. * * @category Instance */ interface ChatActions { /** * Messaging actions for a chat instance. */ messaging: ChatInstanceMessaging; /** * This function can be called when another component wishes this component to gain focus. It is up to the * component to decide where focus belongs. This may return true or false to indicate if a suitable focus location * was found. */ requestFocus: () => boolean | void; /** * Sends the given message to the assistant on the remote server. This will result in a "pre:send" and "send" event * being fired on the event bus. The returned promise will resolve once a response has received and processed and * both the "pre:receive" and "receive" events have fired. It will reject when too many errors have occurred and * the system gives up retrying. * * @param message The message to send. * @param options Options for the message sent. */ send: (message: MessageRequest | string, options?: SendOptions) => Promise; /** * Fire the view:pre:change and view:change events and change the view of the Carbon AI Chat. If a {@link ViewType} is * provided then that view will become visible and the rest will be hidden. If a {@link ViewState} is provided that * includes all of the views then all of the views will be changed accordingly. If a partial {@link ViewState} is * provided then only the views provided will be changed. */ changeView: (newView: ViewType | ViewState) => Promise; /** * Returns the list of writable elements. */ writeableElements: Partial; /** * @deprecated Configure via {@link InputConfig.isVisible}. */ updateInputFieldVisibility: (isVisible: boolean) => void; /** * @deprecated Configure via {@link InputConfig.isDisabled} * or {@link PublicConfig.isReadonly}. */ updateInputIsDisabled: (isDisabled: boolean) => void; /** * @deprecated Configure via {@link LauncherConfig.showUnreadIndicator}. */ updateAssistantUnreadIndicatorVisibility: (isVisible: boolean) => void; /** * Scrolls to the (original) message with the given ID. Since there may be multiple message items in a given * message, this will scroll the first message to the top of the message window. * * @param messageID The (original) message ID to scroll to. * @param animate Whether or not the scroll should be animated. Defaults to true. */ scrollToMessage: (messageID: string, animate?: boolean) => void; /** * Fires an event that will open or close the Catastrophic Error Panel in the chat. This also accepts a * custom title and body text (markdown supported) to be displayed in the Catastrophic Error Panel. * * @param panelState The new state of the Catastrophic Error Panel, optionally including a custom title and body text. */ updateCatastrophicErrorPanel: (panelState: CatastrophicErrorPanelState) => void; /** * Restarts the conversation with the assistant. This does not make any changes to a conversation with a human agent. * This will clear all the current assistant messages from the main assistant view and cancel any outstanding * messages. This will also clear the current assistant session which will force a new session to start on the * next message. * * @deprecated Use {@link ChatInstanceMessaging.restartConversation} instead. */ restartConversation: () => Promise; /** * Recalculates the chat's scroll position and spacer after an external layout change. * * Call this after your custom response component finishes rendering, loads media, or * otherwise changes height in a way the chat cannot detect automatically (e.g. after * injecting content via {@link WriteableElements}). The chat will re-pin the last * qualifying message to the top of the viewport and adjust the spacer accordingly. * * To scroll to the very bottom of the message list instead, pass `{ scrollToBottom: 0 }`. * The spacer reconciliation pass still runs after explicit top/bottom overrides so pin * geometry remains accurate for subsequent updates. * * @param options Optional overrides for scroll behavior. See {@link AutoScrollOptions}. */ doAutoScroll: (options?: AutoScrollOptions) => void; /** * @param direction Either increases or decreases the internal counter that indicates whether the "message is loading" * indicator is shown. If the count is greater than zero, then the indicator is shown. Values of "increase" or "decrease" will * increase or decrease the value. "reset" will set the value back to 0. You may pass undefined as the first value * if you just wish to update the message. * * You can access the current value via {@link ChatInstance.getState}. * * @param message You can also, optionally, pass a plain text string as the second argument. It will display next to the loading indicator for * you to give meaningful feedback while the message is loading (or simple strings like "Thinking...", etc). The most * recent value will be used. So if you call it with a string value and then again with no value, the value will be * replaced with undefined and stop showing in the UI. */ updateIsMessageLoadingCounter: (direction: IncreaseOrDecrease, message?: string) => void; /** * Either increases or decreases the internal counter that indicates whether the hydration fullscreen loading state is * shown. If the count is greater than zero, then the indicator is shown. Values of "increase" or "decrease" will * increase or decrease the value. "reset" will set the value back to 0. * * You can access the current value via {@link ChatInstance.getState}. */ updateIsChatLoadingCounter: (direction: IncreaseOrDecrease) => void; /** * Actions for mutating the chat input contents. */ input: ChatInstanceInput; /** * Actions that are related to a service desk integration. */ serviceDesk: ChatInstanceServiceDeskActions; /** * Remove any record of the current session from the browser's SessionStorage. * * @param keepOpenState If we are destroying the session to restart the chat this can be used to preserve if the web * chat is open. */ destroySession: (keepOpenState?: boolean) => Promise; } /** * @category Instance */ type IncreaseOrDecrease = "increase" | "decrease" | "reset" | undefined; /** * This interface represents the options for when a MessageRequest is sent to the server with the send method. * * @category Instance */ interface SendOptions { /** * If you want to send a message to the API, but NOT have it show up in the UI, set this to true. The "pre:send" * and "send" events will still be fired but the message will not be added to the local message list displayed in * the UI. Note that the response message will still be added. */ silent?: boolean; } /** * An object of elements we expose to developers to write to. Be sure to check the documentation of the React or * web component you are using for how to make use of this, as it differs based on implementation. * * @category Instance */ type WriteableElements = Record; /** * @category Instance */ declare enum WriteableElementName { /** * An element that appears in the AI theme only and is shown beneath the title and description in the AI tooltip * content. * * @deprecated Use {@link WriteableElementName.EXPLAINABILITY_POPOVER_CONTENT} * and {@link WriteableElementName.EXPLAINABILITY_POPOVER_ACTIONS} for full control over AI label popover content. */ AI_TOOLTIP_AFTER_DESCRIPTION_ELEMENT = "aiTooltipAfterDescriptionElement", /** * An element that appears in the header's AI label popover body. When content is provided to this slot, * `HeaderConfig.hideDefaultAiLabelContent` should be set to true. */ EXPLAINABILITY_POPOVER_CONTENT = "explainabilityPopoverContent", /** * An element that appears in the header's AI label popover actions footer area. */ EXPLAINABILITY_POPOVER_ACTIONS = "explainabilityPopoverActions", /** * An element that appears in the main message body directly above the welcome node. */ WELCOME_NODE_BEFORE_ELEMENT = "welcomeNodeBeforeElement", /** * An element that appears in the header on a new line. Only visible while talking to the assistant. */ HEADER_BOTTOM_ELEMENT = "headerBottomElement", /** * An element that appears in the header's fixed-actions slot (before close/minimize buttons). */ HEADER_FIXED_ACTIONS_ELEMENT = "headerFixedActionsElement", /** * An element that appears after the messages area and before the input area. */ BEFORE_INPUT_ELEMENT = "beforeInputElement", /** * An element that appears after the input field. */ AFTER_INPUT_ELEMENT = "afterInputElement", /** * An element that appears in the footer area. */ FOOTER_ELEMENT = "footerElement", /** * An element that appears above the input field on the home screen. */ HOME_SCREEN_BEFORE_INPUT_ELEMENT = "homeScreenBeforeInputElement", /** * An element that appears on the home screen after the conversation starters. */ HOME_SCREEN_AFTER_STARTERS_ELEMENT = "homeScreenAfterStartersElement", /** * An element that appears on the home screen above the welcome message and conversation starters. */ HOME_SCREEN_HEADER_BOTTOM_ELEMENT = "homeScreenHeaderBottomElement", /** * An element to be housed in the custom panel. */ CUSTOM_PANEL_ELEMENT = "customPanelElement", /** * An element to be housed in the workspace panel. */ WORKSPACE_PANEL_ELEMENT = "workspacePanelElement", /** * An element to be housed in the history panel. */ HISTORY_PANEL_ELEMENT = "historyPanelElement" } /** * @category Instance */ type ChangeFunction = (text: string) => void; /** * Upload options. Currently only applies to conversations with a human agent. * * @category Instance */ interface FileUploadCapabilities { /** * Indicates that file uploads may be performed by the user. */ allowFileUploads: boolean; /** * If file uploads are allowed, this indicates if more than one file may be selected at a time. The default is false. */ allowMultipleFileUploads: boolean; /** * If file uploads are allowed, this is the set a file types that are allowed. This is filled into the "accept" * field for the file input element. */ allowedFileUploadTypes: string; } /** * Start or end conversations with human agent. * * @category Instance */ interface ChatInstanceServiceDeskActions { /** * Ends the conversation with a human agent. This does not request confirmation from the user first. If the user * is not connected or connecting to a human agent, this function has no effect. You can determine if the user is * connected or connecting by calling {@link ChatInstance.getState}. Note that this function * returns a Promise that only resolves when the conversation has ended. This includes after the * {@link BusEventType.HUMAN_AGENT_PRE_END_CHAT} and {@link BusEventType.HUMAN_AGENT_END_CHAT} events have been fired and * resolved. */ endConversation: () => Promise; /** * Sets the suspended state for an agent conversation. A conversation can be suspended or un-suspended only if the * user is currently connecting or connected to an agent. If a conversation is suspended, then messages from the user * will no longer be routed to the service desk and incoming messages from the service desk will not be displayed. In * addition, the current connection status with an agent will not be shown. */ updateIsSuspended: (isSuspended: boolean) => Promise; } /** * Eagerly loads every lazily imported dependency across both * `@carbon/ai-chat-components` and `@carbon/ai-chat` so tests can preload * everything they need (Jest, Vitest, server rendering, etc.). Only available * from `@carbon/ai-chat/server`. * * @category Testing */ declare function loadAllLazyDeps(): Promise; /** * Permissive context value used by `MarkdownWithDefaults`. Accepts callbacks * returning either a `ReactNode` (set by the React `ChatContainer` from * `ChatContainerPropsMarkdown.customRenderers`) or an `HTMLElement | null` * (set by `cds-aichat-container` / `cds-aichat-custom-element` from * `WCMarkdown.customRenderers`). The component dispatches based on the * runtime return type. */ interface MarkdownConfigContextValue { markdownItPlugins?: MarkdownItPlugin[]; customRenderers?: { table?: (args: unknown) => ReactNode | HTMLElement | null; codeBlock?: (args: unknown) => ReactNode | HTMLElement | null; }; } declare class ChatContainerInternal extends LitElement { static styles: lit.CSSResult; /** * The config to use to load Carbon AI Chat. Note that the "onLoad" property is overridden by this component. If you * need to perform any actions after Carbon AI Chat been loaded, use the "onBeforeRender" or "onAfterRender" props. */ config: PublicConfig; /** Optional partial language pack overrides */ strings?: DeepPartial; /** A factory for the {@link ServiceDesk} integration. */ serviceDeskFactory?: (parameters: ServiceDeskFactoryParameters) => Promise; /** Public configuration for the service desk integration. */ serviceDesk?: ServiceDeskPublicConfig; /** * The optional HTML element to mount the chat to. */ element?: HTMLElement; /** * This function is called before the render function of Carbon AI Chat is called. This function can return a Promise * which will cause Carbon AI Chat to wait for it before rendering. */ onBeforeRender: (instance: ChatInstance) => Promise | void; /** * This function is called after the render function of Carbon AI Chat is called. This function can return a Promise * which will cause Carbon AI Chat to wait for it before rendering. */ onAfterRender: (instance: ChatInstance) => Promise | void; /** * Merged markdown config (framework-neutral `markdownItPlugins` plus * layer-specific `customRenderers`). Forwarded to the React app via * `MarkdownConfigContext` so {@link MarkdownWithDefaults} can portal * consumer overrides into the rendered markdown components. * * @experimental */ markdown?: MarkdownConfigContextValue; firstUpdated(): void; updated(changedProperties: PropertyValues): void; /** * Track if a previous React 18+ root was already created so we don't create a memory leak on re-renders. */ root: Root; /** * Cache the container we hand to React so we can reuse it between renders. */ reactContainer?: HTMLDivElement; renderReactApp(): Promise; private ensureReactRoot; disconnectedCallback(): void; } declare global { interface HTMLElementTagNameMap { "cds-aichat-internal": ChatContainerInternal; } } /** * Shared Lit base class for the web components that expose a flattened * {@link PublicConfig} surface (`cds-aichat-container` and * `cds-aichat-custom-element`). * * It contributes every flattened reactive property from the single * {@link FLATTENED_PUBLIC_CONFIG_FIELDS} table and derives `resolvedConfig` * from that same table, so each config field is defined in exactly one place. */ /** * Declaration merging gives the instance typed access to `this.history`, * `this.debug`, ... without re-listing every {@link PublicConfig} field and * without emitting any runtime class field (so nothing shadows the accessors * Lit installs from `static properties`). */ interface FlattenedConfigElement extends Partial { } /** * Base class contributing all flattened `PublicConfig` reactive properties. * Not registered as a custom element — only the concrete subclasses are. */ declare abstract class FlattenedConfigElement extends LitElement { static properties: PropertyDeclarations; /** Base config object. Flattened properties layer on top of this. */ config?: PublicConfig; /** * Optional explicit opt-out attribute. If present, it wins over `ai-enabled`. * Not a {@link PublicConfig} field — it resolves into `config.aiEnabled`. */ aiDisabled?: boolean; /** * The {@link PublicConfig} reconstructed from `config` plus every defined * flattened property. */ protected get resolvedConfig(): PublicConfig; } /** * The user_defined message object passed into the renderUserDefinedResponse property on the main chat components. * * @category React */ interface RenderUserDefinedState { /** * The entire message object received when the entire message (not just the individual messageItem) has finished processing. */ fullMessage?: Message; /** * The messageItem after all partial chunks are received. This will first be set to the value of the `complete_item` * chunk. * Once the fullMessage is resolved, this value will update to the value of the item in the fullMessage, which will * be the same value unless you have done any post-processing mutations. */ messageItem?: GenericItem; /** * An array of each user defined item partial chunk. Each chunk contains the new chunk information, they are not * concatenated for you. When messageItem has been set an no more chunks are expected, this property is removed * to avoid memory leaks. */ partialItems?: DeepPartial[]; /** * The current {@link MessageState} of the containing message at the moment the renderer * was invoked. Use this to drive in-widget streaming indicators or error treatments * without inspecting the message items directly. * * @experimental Field is additive; its presence and semantics may evolve as the * lifecycle model stabilizes. */ state?: MessageState; } /** * The type of the render function that is used to render a custom footer. This function should return a * component that renders the custom message footer. * * @param slotName The unique identifier for this footer slot. * @param message The assistant response object that contains the messageItem. * @param messageItem The message item that is being rendered. * @param instance The current instance of the Carbon AI Chat. * @param additionalData Any additional data that was passed to the render function. * * @category React */ type RenderCustomMessageFooter = (slotName: string, message: MessageResponse, messageItem: GenericItem, instance: ChatInstance, additionalData?: Record) => ReactNode | null; /** * The type of the render function that is used to render user defined responses. This function should return a * component that renders the display for the message contained in the given event. * * @param state The BusEventUserDefinedResponse that was originally fired by Carbon AI Chat when the user defined response * was first fired. * @param instance The current instance of the Carbon AI Chat. * * @category React */ type RenderUserDefinedResponse = (state: RenderUserDefinedState, instance: ChatInstance) => ReactNode; /** * The type of the render function used to render user defined responses in web components. * This function should return an HTMLElement to display for the given user defined state, * or null to render nothing. * * The callback is invoked on every state update (new chunk, complete item, full message). * If you return the same element reference, the DOM is not disturbed. If you return a * new element, the previous content is replaced. * * @param state The accumulated state for this user defined response slot. * @param instance The current instance of Carbon AI Chat. * * @category Web component */ type WCRenderUserDefinedResponse = (state: RenderUserDefinedState, instance: ChatInstance) => HTMLElement | null; /** * The accumulated state for one custom message footer slot, passed to the * web component {@link WCRenderCustomMessageFooter} callback. * * @category Web component */ interface RenderCustomMessageFooterState { /** The unique identifier for this footer slot. */ slotName: string; /** The assistant response object that contains the messageItem. */ message: MessageResponse; /** The message item that the footer is attached to. */ messageItem: GenericItem; /** Optional application data supplied with the footer slot. */ additionalData?: Record; } /** * The render function used to render a custom message footer in web * components. When provided, the library manages all event listening, slot * tracking, and element lifecycle. The callback receives the accumulated state * and should return an HTMLElement to display, or null to render nothing. * * This is the web component analogue of {@link RenderCustomMessageFooter} and * mirrors the contract of {@link WCRenderUserDefinedResponse}. * * @param state The accumulated state for this custom footer slot. * @param instance The current instance of Carbon AI Chat. * * @category Web component */ type WCRenderCustomMessageFooter = (state: RenderCustomMessageFooterState, instance: ChatInstance) => HTMLElement | null; /** * A map of writeable element keys to a ReactNode to render to them. * * @category React */ type RenderWriteableElementResponse = { [K in keyof WriteableElements]?: ReactNode; }; /** * Markdown-it parser node tree, surfaced on the `node` field of * {@link MarkdownRendererTableArgs} and {@link MarkdownRendererCodeBlockArgs} * so custom renderers can inspect the parsed token structure when the * high-level data payload isn't enough. * * @category Messaging * @experimental */ type TokenTree = TokenTree$1; /** * Parsed table payload extended by {@link MarkdownRendererTableArgs} — the * argument shape the table renderer callback actually receives. Carries the * headers, rows, and streaming/loading flags. * * @category Messaging * @experimental */ type MarkdownRendererTableData = MarkdownRendererTableData$1; /** * Parsed code-block payload extended by {@link MarkdownRendererCodeBlockArgs} — * the argument shape the code-block renderer callback actually receives. * Carries the language, code text, and streaming flag. * * @category Messaging * @experimental */ type MarkdownRendererCodeBlockData = MarkdownRendererCodeBlockData$1; /** * Argument passed to the markdown table renderer callbacks on * {@link CustomMarkdownRenderers.table} and * {@link WCCustomMarkdownRenderers.table}. Extends * {@link MarkdownRendererTableData} with the source token, full * {@link TokenTree} node, and a stable `slotName` suitable for use as a key. * * @category Messaging * @experimental */ type MarkdownRendererTableArgs = MarkdownRendererTableArgs$1; /** * Argument passed to the fenced code-block renderer callbacks on * {@link CustomMarkdownRenderers.codeBlock} and * {@link WCCustomMarkdownRenderers.codeBlock}. Extends * {@link MarkdownRendererCodeBlockData} with the source token, full * {@link TokenTree} node, and a stable `slotName` suitable for use as a key. * * @category Messaging * @experimental */ type MarkdownRendererCodeBlockArgs = MarkdownRendererCodeBlockArgs$1; /** * Framework-neutral per-element renderer overrides accepted by the * underlying `cds-aichat-markdown` element. The React variant * {@link CustomMarkdownRenderers} and the web-component variant * {@link WCCustomMarkdownRenderers} extend this contract with their layer's * return type. Application code typically uses one of those variants rather * than this baseline directly. * * @category Messaging * @experimental */ type MarkdownCustomRenderers = MarkdownCustomRenderers$1; /** * Per-element renderer overrides for the React `ChatContainer`. Each callback * receives the parsed token data and returns a `ReactNode` that renders in * place of the default Carbon rendering. Return `null` to opt out of the * override for that particular descriptor — the default Carbon rendering * runs unchanged. * * Callbacks fire once per matching element per render pass, including every * streaming chunk that adds or changes the element's contents. When the * underlying element stays in the document but its data changes (a new table * row, more code lines), the same `slotName` is reused and the callback is * invoked again with the updated payload. * * @experimental * @category React */ interface CustomMarkdownRenderers { /** * Override the default rendering for markdown tables. Receives parsed table * data; return `null` to fall back to the default Carbon table renderer. */ table?: (args: MarkdownRendererTableArgs) => ReactNode; /** * Override the default rendering for fenced code blocks. Receives parsed * code-block data; return `null` to fall back to the default Carbon code * snippet renderer. */ codeBlock?: (args: MarkdownRendererCodeBlockArgs) => ReactNode; } /** * The web-component analogue of {@link CustomMarkdownRenderers} — same shape, * but each callback returns an `HTMLElement` (or `null`) instead of a React * node. Return `null` to opt out for a specific descriptor and use the * default Carbon rendering instead. * * Callbacks fire once per matching element per render pass; return the same * element reference across renders to avoid unnecessary DOM churn. * * @experimental * @category Web component */ interface WCCustomMarkdownRenderers { /** * Override the default rendering for markdown tables. Receives parsed table * data; return `null` to fall back to the default Carbon table renderer. */ table?: (args: MarkdownRendererTableArgs) => HTMLElement | null; /** * Override the default rendering for fenced code blocks. Receives parsed * code-block data; return `null` to fall back to the default Carbon code * snippet renderer. */ codeBlock?: (args: MarkdownRendererCodeBlockArgs) => HTMLElement | null; } /** * React-layer `markdown` config — extends {@link PublicConfigMarkdown} with * React renderers. * * @experimental * @category React */ interface ChatContainerPropsMarkdown extends PublicConfigMarkdown { /** * Per-element renderer overrides — see {@link CustomMarkdownRenderers}. * Pass a stable reference (`useMemo`) — an inline object literal will be a * fresh reference each render. * * @experimental */ customRenderers?: CustomMarkdownRenderers; } /** * Web-component-layer `markdown` config — extends {@link PublicConfigMarkdown} * with renderers returning `HTMLElement` (or `null`). * * @experimental * @category Web component */ interface WCMarkdown extends PublicConfigMarkdown { /** * Per-element renderer overrides — see {@link WCCustomMarkdownRenderers}. * Return the same element reference across renders to avoid unnecessary DOM * churn. * * @experimental */ customRenderers?: WCCustomMarkdownRenderers; } /** * Properties for the ChatContainer React component. This interface extends * {@link PublicConfig} with additional component-specific props, flattening all * config properties as top-level props for better TypeScript IntelliSense. * * Any additional DOM attributes passed to the component (for example * `className`, `id`, `style`, or `aria-*`) are forwarded to the underlying * host element. * * @category React */ interface ChatContainerProps extends Omit { /** * Markdown rendering customization. Extends the framework-neutral * {@link PublicConfigMarkdown} with React-layer custom renderers. * * @experimental */ markdown?: ChatContainerPropsMarkdown; /** * This function is called before the render function of Carbon AI Chat is called. This function can return a Promise * which will cause Carbon AI Chat to wait for it before rendering. */ onBeforeRender?: (instance: ChatInstance) => Promise | void; /** * This function is called after the render function of Carbon AI Chat is called. This function can return a Promise * which will cause Carbon AI Chat to wait for it before rendering. */ onAfterRender?: (instance: ChatInstance) => Promise | void; /** * Called before a view change (the chat opening or closing). Async — return a * Promise to defer the view change until it resolves. * * This is an opt-in observation hook. Unlike {@link ChatCustomElementProps}, * the container has no wrapping element to size, so no default visibility * behavior runs when this prop is omitted. */ onViewPreChange?: (event: BusEventViewPreChange, instance: ChatInstance) => Promise | void; /** * Called when a view change (the chat opening or closing) is complete. * * This is an opt-in observation hook. Unlike {@link ChatCustomElementProps}, * the container has no wrapping element to size, so no default visibility * behavior runs when this prop is omitted. */ onViewChange?: (event: BusEventViewChange, instance: ChatInstance) => void; /** * This is the function that this component will call when a custom footer should be rendered. */ renderCustomMessageFooter?: RenderCustomMessageFooter; /** * This is the function that this component will call when a user defined response should be rendered. */ renderUserDefinedResponse?: RenderUserDefinedResponse; /** * This is the render function this component will call when it needs to render a writeable element. */ renderWriteableElements?: RenderWriteableElementResponse; } /** * The cds-aichat-container managing creating slotted elements for user_defined responses, custom message footers, and writable elements. * It then passes that slotted content into cds-aichat-internal. That component will boot up the full chat application * and pass the slotted elements into their slots. */ declare class ChatContainer extends FlattenedConfigElement { /** * This function is called before the render function of Carbon AI Chat is called. This function can return a Promise * which will cause Carbon AI Chat to wait for it before rendering. */ onBeforeRender: (instance: ChatInstance) => Promise | void; /** * This function is called after the render function of Carbon AI Chat is called. */ onAfterRender: (instance: ChatInstance) => Promise | void; /** * Called before a view change (the chat opening or closing). Async — return a * Promise to defer the view change until it resolves. * * This is an opt-in observation hook. Unlike `cds-aichat-custom-element`, the * container has no wrapping element to size, so no default visibility * behavior runs when this property is omitted. */ onViewPreChange?: (event: BusEventViewPreChange) => Promise | void; /** * Called when a view change (the chat opening or closing) is complete. * * This is an opt-in observation hook. Unlike `cds-aichat-custom-element`, the * container has no wrapping element to size, so no default visibility * behavior runs when this property is omitted. */ onViewChange?: (event: BusEventViewChange, instance: ChatInstance) => void; /** * Optional callback to render user defined responses. When provided, the library manages all event listening, * slot tracking, streaming state, and element lifecycle. The callback receives the accumulated state and should * return an HTMLElement or null. * * When this property is not set, the existing event + manual slot approach continues to work. */ renderUserDefinedResponse?: WCRenderUserDefinedResponse; /** * Optional callback to render custom message footers. When provided, the library manages all event listening, * slot tracking, and element lifecycle. The callback receives the accumulated state and should * return an HTMLElement or null. * * When this property is not set, the existing event + manual slot approach continues to work. */ renderCustomMessageFooter?: WCRenderCustomMessageFooter; /** * The existing array of slot names for all user_defined components. */ _userDefinedSlotNames: string[]; /** * The existing array of slot names for all custom footers. */ _customFooterSlotNames: string[]; /** * The existing array of slot names for all writeable elements. */ _writeableElementSlots: string[]; /** * Active slot names for markdown-plugin output hosted at this element. * Populated when this element takes over from the markdown element by * accepting the host-mount event; drained when the matching unmount * event fires. */ _pluginSlotNames: string[]; /** * Page-level host elements created for plugin-output slots, keyed by slot * name. Created in this element's outer light DOM so consumer-loaded * stylesheets (e.g. KaTeX) reach the rendered HTML normally. */ private _pluginHosts; /** * The chat instance. */ _instance: ChatInstance; /** * Accumulated state per slot for user_defined responses when renderUserDefinedResponse is provided. */ _userDefinedStateBySlot: Record; /** * Accumulated state per slot for custom message footers when renderCustomMessageFooter is provided. */ _customFooterStateBySlot: Record; /** * Tracks the wrapper elements created by the callback rendering path. */ private _callbackElements; /** * Tracks the wrapper elements created by the custom-footer callback rendering path. */ private _callbackFooterElements; /** * Adds the slot attribute to the element for the user_defined response type and then injects it into the component by * updating this._userDefinedSlotNames; */ userDefinedHandler: (event: BusEventUserDefinedResponse | BusEventChunkUserDefinedResponse) => void; /** * Adds the slot attribute to the element for the custom_footer_slot type and then injects it into the component by * updating this._customFooterSlotNames; */ customFooterHandler: (event: BusEventCustomFooterSlot) => void; /** * Enhanced handler for CUSTOM_FOOTER_SLOT when the renderCustomMessageFooter callback is provided. * Tracks both slot names and the full per-slot state used by the callback rendering path. */ private enhancedCustomFooterHandler; /** * Enhanced handler for USER_DEFINED_RESPONSE when renderUserDefinedResponse callback is provided. * Tracks both slot names and full message state per slot. */ private enhancedUserDefinedHandler; /** * Enhanced handler for CHUNK_USER_DEFINED_RESPONSE when renderUserDefinedResponse callback is provided. * Handles both complete_item and partial_item chunks, accumulating state per slot. */ private enhancedUserDefinedChunkHandler; /** * Handles RESTART_CONVERSATION when the renderUserDefinedResponse and/or renderCustomMessageFooter * callback is provided. Clears all accumulated state and removes callback-rendered elements from the DOM. * * The custom-footer cleanup is guarded by renderCustomMessageFooter so the legacy footer passthrough * path (which the host clears itself) is left untouched. */ private restartHandler; /** * Synchronizes callback-rendered elements in the light DOM based on current state. * Called from render() when renderUserDefinedResponse is provided. */ private syncCallbackRenderedElements; /** * Synchronizes custom-footer callback-rendered elements in the light DOM based on current state. * Called from render() when renderCustomMessageFooter is provided. Direct analogue of * syncCallbackRenderedElements(). */ private syncCallbackRenderedFooterElements; /** * True when an outer chat element (cds-aichat-custom-element) further up * the composed path will catch the host-mount event. When true, this * element only forwards the slot through its render template and lets the * outer element create the page-level host. When false, this element is * outermost and must create the host itself. */ private hasOuterChatHandler; private handlePluginHostMount; private handlePluginHostUpdate; private handlePluginHostUnmount; connectedCallback(): void; disconnectedCallback(): void; onBeforeRenderOverride: (instance: ChatInstance) => Promise; addWriteableElementSlots(): void; private attachWriteableElements; /** * Renders the template while passing in class functionality */ render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { "cds-aichat-container": ChatContainer; } } /** * Attributes interface for the cds-aichat-container web component. * This interface extends {@link PublicConfig} with additional component-specific props, * flattening all config properties as top-level properties for better TypeScript IntelliSense. * * @category Web component */ interface CdsAiChatContainerAttributes extends Omit { /** * Markdown rendering customization. Extends the framework-neutral * `PublicConfig.markdown` with web-component `customRenderers`. * * @experimental */ markdown?: WCMarkdown; /** * This function is called before the render function of Carbon AI Chat is called. This function can return a Promise * which will cause Carbon AI Chat to wait for it before rendering. */ onBeforeRender?: (instance: ChatInstance) => Promise | void; /** * This function is called after the render function of Carbon AI Chat is called. */ onAfterRender?: (instance: ChatInstance) => Promise | void; /** * Called before a view change (the chat opening or closing). Async — return a Promise to defer the view * change until it resolves. This is an opt-in observation hook with no default visibility behavior. */ onViewPreChange?: (event: BusEventViewPreChange) => Promise | void; /** * Called when a view change (the chat opening or closing) is complete. This is an opt-in observation hook * with no default visibility behavior. */ onViewChange?: (event: BusEventViewChange, instance: ChatInstance) => void; /** * Optional callback to render user defined responses. When provided, the library manages all event listening, * slot tracking, streaming state, and element lifecycle. */ renderUserDefinedResponse?: WCRenderUserDefinedResponse; /** * Optional callback to render custom message footers. When provided, the library manages all event listening, * slot tracking, and element lifecycle. When omitted, the legacy event + manual slot approach continues to work. */ renderCustomMessageFooter?: WCRenderCustomMessageFooter; } /** * Attributes interface for the cds-aichat-custom-element web component. * This interface extends {@link PublicConfig} with additional component-specific props, * flattening all config properties as top-level properties for better TypeScript IntelliSense. * * @category Web component */ interface CdsAiChatCustomElementAttributes extends Omit { /** * Markdown rendering customization. Extends the framework-neutral * `PublicConfig.markdown` with web-component `customRenderers`. * * @experimental */ markdown?: WCMarkdown; /** * This function is called before the render function of Carbon AI Chat is called. This function can return a Promise * which will cause Carbon AI Chat to wait for it before rendering. */ onBeforeRender?: (instance: ChatInstance) => Promise | void; /** * This function is called after the render function of Carbon AI Chat is called. */ onAfterRender?: (instance: ChatInstance) => Promise | void; /** * An optional listener for "view:change" events. Such a listener is required when using a custom element in order * to control the visibility of the Carbon AI Chat main window. If no callback is provided here, a default one will be * used that injects styling into the app that will show and hide the Carbon AI Chat main window and also change the * size of the custom element so it doesn't take up space when the main window is closed. * * You can provide a different callback here if you want custom behavior such as an animation when the main window * is opened or closed. * * Note that this function can only be provided before Carbon AI Chat is loaded. After Carbon AI Chat is loaded, the event * handler will not be updated. */ onViewChange?: (event: BusEventViewChange, instance: ChatInstance) => void; /** * Optional callback to render user defined responses. When provided, the inner cds-aichat-container * manages all event listening, slot tracking, streaming state, and element lifecycle. */ renderUserDefinedResponse?: WCRenderUserDefinedResponse; /** * Optional callback to render custom message footers. When provided, the inner cds-aichat-container * manages all event listening, slot tracking, and element lifecycle. */ renderCustomMessageFooter?: WCRenderCustomMessageFooter; } export { BusEventType as N, ButtonItemKind as V, ButtonItemType as W, CancellationReason as X, CarbonTheme as Y, FeedbackInteractionType as aA, FileStatusValue as aC, HeaderMenuClickType as aN, HumanAgentMessageType as aV, HumanAgentsOnlineStatus as aW, IFrameItemDisplayOption as aY, CornersType as ag, ErrorType as au, LayoutCustomProperties as b8, OnErrorType as bC, OptionItemPreference as bE, PageObjectId as bF, PanelType as bG, ReasoningStepOpenState as b_, MessageErrorState as bl, MessageInputType as bo, MessageResponseTypes as bw, MessageSendSource as bx, MessageState as by, MinimizeButtonIconType as bz, ScreenShareState as c7, ViewChangeReason as cA, ViewType as cC, WidthOptions as cH, WriteableElementName as cL, enLanguagePack as cN, loadAllLazyDeps as cO, UserType as cx }; export type { CatastrophicErrorPanelState as $, AdditionalDataToAgent as A, BusEventViewPreChange as B, ChatContainerProps as C, BusEventHumanAgentReceive as D, BusEventHumanAgentSend as E, BusEventMessageItemCustom as F, BusEventPreReceive as G, BusEventPreReset as H, BusEventPreSend as I, BusEventReceive as J, BusEventReset as K, BusEventSend as L, BusEventStateChange as M, BusEventUserDefinedResponse as O, PersistedState as P, BusEventWorkspaceClose as Q, BusEventWorkspaceOpen as R, BusEventWorkspacePreClose as S, BusEventWorkspacePreOpen as T, ButtonItem as U, CardItem as Z, CarouselItem as _, ChatInstance as a, InlineErrorItem as a$, CdsAiChatContainerAttributes as a0, CdsAiChatCustomElementAttributes as a1, ChainOfThoughtStep as a2, ChangeFunction as a3, ChatContainerPropsMarkdown as a4, ChatInstanceInput as a5, ChatInstanceMessaging as a6, ChatInstanceServiceDeskActions as a7, ChatShortcutConfig as a8, Chunk as a9, FileFieldValue as aB, FileUpload as aD, FileUploadCapabilities as aE, FinalResponseChunk as aF, GenericItem as aG, GenericItemCustomFooterSlotOptions as aH, GenericItemMessageFeedbackCategories as aI, GenericItemMessageFeedbackOptions as aJ, GenericItemMessageOptions as aK, GridItem as aL, HeaderConfig as aM, HistoryConfig as aO, HistoryItem as aP, HomeScreenConfig as aQ, HomeScreenStarterButton as aR, HomeScreenStarterButtons as aS, HomeScreenState as aT, HorizontalCellAlignment as aU, IFrameItem as aX, ImageItem as aZ, IncreaseOrDecrease as a_, CompleteItemChunk as aa, ConnectToHumanAgentItem as ab, ConnectToHumanAgentItemTransferInfo as ac, ConnectingErrorInfo as ad, ConversationalSearchItem as ae, ConversationalSearchItemCitation as af, CustomMarkdownRenderers as ah, CustomMenuOption as ai, CustomPanelConfigOptions as aj, CustomPanelInstance as ak, CustomPanelOpenOptions as al, CustomPanels as am, CustomSendMessageOptions as an, DateItem as ao, DeepPartial as ap, DefaultCustomPanelConfigOptions as aq, DisclaimerPublicConfig as ar, DisconnectedErrorInfo as as, EndChatInfo as at, EventBusHandler as av, EventHandlers as aw, EventInput as ax, EventInputData as ay, ExternalFileReference as az, BusEventViewChange as b, ReasoningSteps as b$, InlineFile as b0, InputConfig as b1, ItemStreamingMetadata as b2, KeyboardShortcuts as b3, LanguagePack as b4, LauncherCallToActionConfig as b5, LauncherConfig as b6, LayoutConfig as b7, MarkdownCustomRenderers as b9, ObjectMap as bA, OnErrorData as bB, OptionItem as bD, PartialItemChunk as bH, PartialItemChunkWithId as bI, PartialOrCompleteItemChunk as bJ, PartialResponse as bK, PauseItem as bL, PerCornerConfig as bM, PersistedHumanAgentState as bN, PreviewCardItem as bO, PublicChatHumanAgentState as bP, PublicChatState as bQ, PublicConfig as bR, PublicConfigMarkdown as bS, PublicConfigMessaging as bT, PublicCustomPanelsState as bU, PublicDefaultCustomPanelState as bV, PublicHistoryPanelState as bW, PublicInputState as bX, PublicWorkspaceCustomPanelState as bY, ReasoningStep as bZ, MarkdownItPlugin as ba, MarkdownRendererCodeBlockArgs as bb, MarkdownRendererCodeBlockData as bc, MarkdownRendererTableArgs as bd, MarkdownRendererTableData as be, MediaFileAccessibility as bf, MediaItem as bg, MediaItemDimensions as bh, MediaSubtitleTrack as bi, MediaTranscript as bj, Message as bk, MessageHistoryFeedback as bm, MessageInput as bn, MessageItemPanelInfo as bp, MessageOutput as bq, MessageRequest as br, MessageRequestHistory as bs, MessageResponse as bt, MessageResponseHistory as bu, MessageResponseOptions as bv, AgentAvailability as c, RenderCustomMessageFooter as c0, RenderCustomMessageFooterState as c1, RenderUserDefinedResponse as c2, RenderUserDefinedState as c3, RenderWriteableElementResponse as c4, ResolvedCornerConfig as c5, ResponseUserProfile as c6, SearchResult as c8, SendOptions as c9, ViewState as cB, WCCustomMarkdownRenderers as cD, WCMarkdown as cE, WCRenderCustomMessageFooter as cF, WCRenderUserDefinedResponse as cG, WithBodyAndFooter as cI, WithWidthOptions as cJ, WorkspaceCustomPanelConfigOptions as cK, WriteableElements as cM, ServiceDesk as ca, ServiceDeskCallback as cb, ServiceDeskCapabilities as cc, ServiceDeskErrorInfo as cd, ServiceDeskFactoryParameters as ce, ServiceDeskPublicConfig as cf, SingleOption as cg, StartChatOptions as ch, StreamChunk as ci, StructuredData as cj, StructuredField as ck, StructuredFieldType as cl, StructuredFieldValue as cm, SystemMessageItem as cn, SystemMessageVariant as co, TestId as cp, TextItem as cq, TokenTree as cr, TypeAndHandler as cs, UploadConfig as ct, UpsertMessageUpdater as cu, UserDefinedItem as cv, UserMessageErrorInfo as cw, VerticalCellAlignment as cy, VideoItem as cz, AudioItem as d, AutoScrollOptions as e, BaseGenericItem as f, BaseMessageInput as g, BusEvent as h, BusEventChatReady as i, BusEventChunkUserDefinedResponse as j, BusEventClosePanelButtonClicked as k, BusEventCustomFooterSlot as l, BusEventCustomPanelClose as m, BusEventCustomPanelOpen as n, BusEventCustomPanelPreClose as o, BusEventCustomPanelPreOpen as p, BusEventFeedback as q, BusEventHeaderMenuClick as r, BusEventHistoryBegin as s, BusEventHistoryEnd as t, BusEventHumanAgentAreAnyAgentsOnline as u, BusEventHumanAgentEndChat as v, BusEventHumanAgentPreEndChat as w, BusEventHumanAgentPreReceive as x, BusEventHumanAgentPreSend as y, BusEventHumanAgentPreStartChat as z };