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
| Option | Required | Effect |
|---|---|---|
appId: string | Yes | Customer Agent application id; missing values throw during construction. |
widgetId: string | No | Stable client/event identifier; generated when omitted and fixed for that client. |
anonymousId: string | No | Stable anonymous visitor marker. |
user: CustomerAgentUser | No | Known user identity and attributes. |
context: CustomerAgentContext | No | Initial context object. |
contextReady: boolean | No | Initial context readiness; false defers interview discovery. |
locale: string | No | Conversation language and attached Messenger locale. |
page: CustomerAgentPageOptions | No | Page 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
| Method | Arguments | Returns | Effect |
|---|---|---|---|
boot | None | Promise<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. |
getState | None | CustomerAgentClientState | Reads the current immutable snapshot. |
getOptions | None | CustomerAgentClientOptions | Reads current identity/context options. |
getPublicConfig | Optional { 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. |
subscribe | listener, optional selector | () => void | Notifies when the snapshot or selected value changes. Does not immediately invoke the listener. |
getConversation | conversationId: string | CustomerAgentConversationState | null | Reads a conversation snapshot. |
getSession | Optional GetSessionOptions | Promise<{ conversationId; messages }> | Selects and restores or creates a support scene. Omitting options selects ordinary support. |
sendMessage | content: string, optional attachment metadata array, optional GetSessionOptions | Promise<void> | Sends to the specified support scene, or the selected scene when omitted, without changing the selection. Publishes optimistic, confirmed, or failed state. |
uploadAttachment | file: File, optional GetSessionOptions | Promise<{ id; filename; mimeType; sizeBytes; url }> | Uploads to the specified scene, or the selected scene when omitted. Does not change the selection. |
getSupportState | None | CustomerAgentSupportState | Reads support session state. |
getInterviewState | None | CustomerAgentInterviewState | Reads availability/session state. |
getInterviewSession | None | CustomerAgentInterviewSession | null | Reads current interview messages and status. |
ensureInvitation | None | Promise<{ invitationId: string }> | Creates or returns an eligible invitation. |
startInvitation | invitationId: string | Promise<{ entryId; sessionId; session }> | Starts the invitation as an interview conversation. |
startInterview | None | Promise<{ entryId; sessionId; session }> | Ensures an eligible invitation and starts it. |
chooseInvitation | invitationId, "close" | "later" | Promise<void> | Records the invitation choice. |
sendInterviewMessage | content: string | Promise<void> | Sends to the active interview. Completion and reward events also work without UI. |
loadInterviewReward | Optional sessionId | Promise<unknown> | Loads reward data, updates the snapshot, and emits interview.reward_updated. |
identify | user: CustomerAgentUser | void | Updates identity and isolates the new identity's conversation state. |
setContext | Context, optional { merge; ready } | void | Merges nested plain objects by default; merge: false replaces context. |
update | Partial<Omit<CustomerAgentClientOptions, "widgetId">> | void | Updates options and refreshes session/availability state. |
on | Event name, handler | () => void | Subscribes to business events. |
shutdown | None | void | Cancels 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.
| Method | Arguments | Returns | Effect |
|---|---|---|---|
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. |
removeCard | conversationId: string, cardId: string | void | Removes the card locally and suppresses its reappearance from subsequent history responses in the same client. Other message parts remain. |
onCardAction | (operation: CustomerAgentCardOperation) => void | () => void | Subscribes to newly triggered operations. Does not replay previous operations or interpret callback return values. |
performCardAction | conversationId: string, cardId: string, actionId: string | CustomerAgentCardOperation | null | Commits local-only pending before notifying subscribers. Returns null for unavailable, disabled, missing, pending or unknown actions. |
cancelCardAction | operationId: string | boolean | Discards a pending operation locally and restores its card actions without writing a result. Returns false for an old, completed, removed or different-identity operation. |
settleCardAction | CustomerAgentCardActionResult | boolean | Updates 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:
| Field | Type | Required | Effect |
|---|---|---|---|
id | string | Yes | Stable, nonempty card id within a conversation. |
schemaVersion | 1 | Yes | Supported card schema. |
revision | number | Yes | Nonnegative safe integer used to ignore older card snapshots. |
title | string | Yes | Nonempty heading, rendered as text. |
description | string | No | Plain text description. |
statusText | string | No | Host-supplied progress or result text. |
fallbackText | string | Yes | Nonempty text used for unsupported schemas and transcript output. |
actions | readonly { id: string; label: string; variant: "primary" | "secondary"; disabled?: boolean }[] | Yes | Zero 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.