Customer Agent

Headless client

Conversation state, actions, and subscriptions without the Messenger UI.

createClient creates an independent client for support and interview conversations. It starts no requests until boot or a conversation action is called and does not load the Messenger or React. The built-in Messenger can use the same client through its client option.

import { createClient } from "@customer-agent/sdk"

const client = createClient({ appId: "your-app", user: { id: "user-123" } })
await client.boot()
const unsubscribe = client.subscribe(() => console.log(client.getState()))
await client.sendMessage("Hello")

Options

OptionRequiredEffect
appId: stringYesCustomer Agent application id; missing values throw during construction.
widgetId: stringNoStable client/event identifier; generated when omitted and fixed for that client.
anonymousId: stringNoStable anonymous visitor marker.
user: CustomerAgentUserNoKnown user identity and attributes.
context: CustomerAgentContextNoInitial context object.
contextReady: booleanNoInitial context readiness; false defers interview discovery.
locale: stringNoConversation language and attached Messenger locale.
page: CustomerAgentPageOptionsNoPage metadata overrides.

API addresses are configured in the SDK build. Branding, theme, launcher, and other presentation fields belong to Messenger options.

Browser clients restore cached sessions and include page/device context. Page options override collected page metadata. Imports and client construction are safe during server rendering; requests start explicitly. Without browser globals, the client uses in-memory session caches. Application origin policies still apply: non-browser callers must supply an allowed page.customerOrigin or page.pageUrl when the application requires a page origin.

Methods

MethodArgumentsReturnsEffect
bootNonePromise<void>Restores cached ordinary support and interview sessions, checks interview availability, and starts loading public config without waiting for it. Creates no empty support session.
getStateNoneCustomerAgentClientStateReads the current immutable snapshot.
getOptionsNoneCustomerAgentClientOptionsReads current identity/context options.
getPublicConfigOptional { refresh?: boolean }Promise<CustomerAgentPublicConfig | null>Resolves the app's public config and publishes it to publicConfig; cached per appId unless refresh is true. Missing config resolves null. Request failures and calls after shutdown reject; failures are not cached and leave publicConfig unchanged.
subscribelistener, optional selector() => voidNotifies when the snapshot or selected value changes. Does not immediately invoke the listener.
getConversationconversationId: stringCustomerAgentConversationState | nullReads a conversation snapshot.
getSessionOptional GetSessionOptionsPromise<{ conversationId; messages }>Selects and restores or creates a support scene. Omitting options selects ordinary support.
sendMessagecontent: string, optional attachment metadata array, optional GetSessionOptionsPromise<void>Sends to the specified support scene, or the selected scene when omitted, without changing the selection. Publishes optimistic, confirmed, or failed state.
uploadAttachmentfile: File, optional GetSessionOptionsPromise<{ id; filename; mimeType; sizeBytes; url }>Uploads to the specified scene, or the selected scene when omitted. Does not change the selection.
getSupportStateNoneCustomerAgentSupportStateReads support session state.
getInterviewStateNoneCustomerAgentInterviewStateReads availability/session state.
getInterviewSessionNoneCustomerAgentInterviewSession | nullReads current interview messages and status.
ensureInvitationNonePromise<{ invitationId: string }>Creates or returns an eligible invitation.
startInvitationinvitationId: stringPromise<{ entryId; sessionId; session }>Starts the invitation as an interview conversation.
startInterviewNonePromise<{ entryId; sessionId; session }>Ensures an eligible invitation and starts it.
chooseInvitationinvitationId, "close" | "later"Promise<void>Records the invitation choice.
sendInterviewMessagecontent: stringPromise<void>Sends to the active interview. Completion and reward events also work without UI.
loadInterviewRewardOptional sessionIdPromise<unknown>Loads reward data, updates the snapshot, and emits interview.reward_updated.
identifyuser: CustomerAgentUservoidUpdates identity and isolates the new identity's conversation state.
setContextContext, optional { merge; ready }voidMerges nested plain objects by default; merge: false replaces context.
updatePartial<Omit<CustomerAgentClientOptions, "widgetId">>voidUpdates options and refreshes session/availability state.
onEvent name, handler() => voidSubscribes to business events.
shutdownNonevoidCancels requests and timers and settles pending sends as failed without replaying them. A later boot can resume the same client.

Session, send, upload, invitation, and reward actions can reject on request failure. Sending while another message is pending rejects. Sending an interview message without an active session rejects. An identity change or shutdown invalidates pending results. Terminal interview replies are confirmed from the send response; a failed optional full-history refresh does not turn them into failed sends. Support sends do not automatically replay ambiguous network failures.

State

CustomerAgentClientState contains appId, widgetId, isReady, publicConfig, support, interview, activeSupportConversationId, and conversations: ReadonlyMap<string, CustomerAgentConversationState>. activeSupportScene: CustomerAgentSupportScene identifies the selected scene. support and getSupportState() describe that selection. supportSessions: ReadonlyMap<CustomerAgentSupportScene, CustomerAgentSupportState> retains published states for each scene, including an error after the widget has fallen back to ordinary support. Scene names and request options are described in Support sessions. The active support id may be client-local while its first session is being created; getSession returns the confirmed server id. Client readiness is independent of Messenger readiness. boot completes initial checks; request errors remain observable through the support/interview state.

publicConfig: CustomerAgentPublicConfig | null is null until loaded, when the application has no public config, and after an appId change until the new app's config loads. CustomerAgentPublicConfig contains appId, branding, businessHours, supportEmail, welcomeMessage (strings keyed by locale), and humanSupportEnabled, which is true only when the server returns true.

Each conversation has id, kind (support or interview), messages, and isSending, plus optional error, completion, reward, and status. Support conversations also expose optional scene, retentionFlowId, and server status ("open" or "closed"); interviews retain their session status. Messages contain id, role, content, ISO createdAt, optional assistantAuthor (llm, human, or host) and attachments, source (server, local, or error), and delivery (pending, sent, or failed). Attachment metadata contains id, filename, mimeType, sizeBytes, url, and optional expiresAt.

Messages may also contain parts: readonly CustomerAgentMessagePart[]. When present, these ordered parts supply the displayed content; content remains a string for existing consumers. A text part has { type: "text", text: string }. A card part has { type: "action-card", card, operation? }. Both support and interview conversations display these parts and include cards in text exports.

Action cards

Card insertion and terminal operation results are saved through the Customer Agent Card API. Pending operation state is local to the current client. Support polls merge returned cards and terminal operation state, including the server operation createdAt. removeCard remains a local removal for the current client lifetime. cardActionsAvailable: boolean in the client state indicates whether an action subscriber is registered. Widget unmounting leaves card actions running.

MethodArgumentsReturnsEffect
upsertCard{ conversationId: string, card: CustomerAgentActionCard }Promise<void>Saves a standalone assistant card or updates the card with the same id. The returned server revision becomes the current local revision. Updates retain message id, time and position. Lower local revisions are ignored.
removeCardconversationId: string, cardId: stringvoidRemoves the card locally and suppresses its reappearance from subsequent history responses in the same client. Other message parts remain.
onCardAction(operation: CustomerAgentCardOperation) => void() => voidSubscribes to newly triggered operations. Does not replay previous operations or interpret callback return values.
performCardActionconversationId: string, cardId: string, actionId: stringCustomerAgentCardOperation | nullCommits local-only pending before notifying subscribers. Returns null for unavailable, disabled, missing, pending or unknown actions.
cancelCardActionoperationId: stringbooleanDiscards a pending operation locally and restores its card actions without writing a result. Returns false for an old, completed, removed or different-identity operation.
settleCardActionCustomerAgentCardActionResultbooleanUpdates the matching operation and card. Returns false for an old, completed, removed or different-identity operation.

The conversation must already exist. Methods throw after shutdown; card methods that reference an unknown conversation throw. Invalid card data and invalid results throw TypeError. Successful results must supply the same card id and a revision at least as high as the current card.

CustomerAgentActionCard has the following fields:

FieldTypeRequiredEffect
idstringYesStable, nonempty card id within a conversation.
schemaVersion1YesSupported card schema.
revisionnumberYesNonnegative safe integer used to ignore older card snapshots.
titlestringYesNonempty heading, rendered as text.
descriptionstringNoPlain text description.
statusTextstringNoHost-supplied progress or result text.
fallbackTextstringYesNonempty text used for unsupported schemas and transcript output.
actionsreadonly { id: string; label: string; variant: "primary" | "secondary"; disabled?: boolean }[]YesZero to two actions, with unique nonempty ids and labels and at most one action of each variant.

Cards have no close button. The host can remove them with removeCard. Card data accepts neither components nor executable callbacks. Unknown card schemas received in message parts display their supplied fallback text. Appearance is configured through Messenger theme options.

CustomerAgentCardOperation contains operationId, conversationId, cardId, actionId, the operation createdAt, the starting revision, status, and optional message. CARD_OPERATION_STATUS exports PENDING, SUCCEEDED, FAILED, and UNKNOWN. These correspond to pending, succeeded, failed, and unknown.

CustomerAgentCardActionResult is one of:

{ operationId: string; status: "succeeded"; card: CustomerAgentActionCard; message?: string }
{ operationId: string; status: "failed" | "unknown"; message: string }

An action stays locked while pending or unknown. Pending is an optimistic client state and is not sent to the Card API. It remains pending until the host settles or cancels it. cancelCardAction removes that local pending state without writing to the Card API, so the card remains actionable. An unknown action still accepts a later matching result. A failure preserves the latest card and permits another action if it remains enabled. Success displays the supplied card, which may expose new actions. When the host settles an action, the SDK writes only the final result record to the Card API in the background. Network, 5xx, 408, and 429 write failures are retried; other rejected writes are not retried, and the next support refresh merges the server card state. Shutdown or an identity change stops unfinished writes. A new action receives a new operation id. The SDK never retries the business operation. Reloading discards local pending state; a pending operation returned by the server is not restored as an active local action. Shutdown clears action subscribers and marks unresolved pending cards unknown; resuming the client does not replay them. Identity changes invalidate old operation ids.

One host runtime must own business side effects; additional observers can use subscribe. The host executes its business request and reports its result separately. Business idempotency and result lookup belong to the host and its backend.

Support history refreshes every five seconds while a current session exists. Hidden browser pages pause refresh. Closing, detaching, or unsubscribing the Messenger does not stop the client. Unchanged messages and snapshots retain their references. A truncated or stale support history response does not remove confirmed replies or local entries.

Messenger attachment and migration

import { createClient, mountWidget } from "@customer-agent/sdk/widget"

const client = createClient({ appId: "your-app" })
await client.boot()
const widget = await mountWidget({ client })
widget.show({ type: "support" })
widget.unmount() // Client requests and state continue.
client.shutdown()

UI handles contain only presentation state and controls. Business events are subscribed on the client when UI may be absent. Widget open/close and other UI events belong to the widget. Forwarded business events retain their event object; observe each business event once on its client.

The root, widget, and React entries use named exports. Default exports, command strings, singleton functions, and implicit singleton hooks are removed. React consumers supply the client through CustomerAgentProvider and use useCustomerAgentState(selector?).

Client construction/imports and the published root declarations support Node environments without a DOM library, including TypeScript NodeNext resolution. createClient remains UI-free; mountWidget requires a browser document. Providers and widgets do not shut down the client when they unmount. Client completion loads its reward once per completed session; explicit reward loads can emit additional reward updates.

On this page