Website SDK reference
Every function, property and option of the website loader's GraineAgent, grouped by what you use it for: putting the agent on a page, identity and memory, the chat, drawing your own chat, voice and components (headless), booking a call with the widget's sheet, scheduled calls, screen context and actions, and errors.
Everything the website loader, https://www.graine.ai/embed/v1.js, puts on window.GraineAgent, grouped by what you use it for. Each function comes with what it is for, its signature, its parameters, what it returns, the errors it can raise and an example. The loader is served, not installed: the script at /embed/v1.js is always the current v1, so a website has nothing to upgrade, and GraineAgent.version reports the build it is running (currently "1.6.1"). The same API across every platform, topic by topic, is the SDK reference; the widget in full is Embed on your website.
Requirements, install, permissions and initialisation
| Loader | https://www.graine.ai/embed/v1.js — always the current v1, nothing to upgrade; plain JavaScript, no build step, no dependencies |
|---|---|
| Requires | The page's host in the agent's Allowed domains (Agent → Embed & Widgets). A site with a Content-Security-Policy allows https://www.graine.ai in script-src, connect-src and frame-src: the loader fetches from that address and shows the widget in a frame from it. |
| Microphone | The widget's frame asks for the microphone (allow="microphone") when the visitor starts a voice conversation, so a Permissions-Policy must not deny it to that frame. The browser shows its own prompt; nothing to add. Loaded headless, the frame is allowed autoplay too (allow="microphone; autoplay"), so the agent's voice plays on the strength of the visitor's tap on your page. |
| Storage | The loader keeps this browser's install ID and the visitor's memory choice in localStorage, and, in sessionStorage, whether the panel was open and an ID for the tab's conversation, so it goes on when the visitor moves to another page (never a word of it). Where storage is refused, they last for the page's life. |
HTML — on every page the agent belongs on (new in loader 1.6.0)
The tag loads the agent itself: every load() option below that is text can be a data- attribute (data-chat-size="large", data-launcher-label="Ask us"), data-variables takes JSON, and data-preload is preload: true. It is async, so it never holds your page up, and it may sit in the <head>. To pass values from your own script, call load() instead:
HTML — before </body>
The widget is a launcher button and a panel in a frame of its own, so your page's CSS cannot change it and its code cannot touch your page. It draws the agent's design from the Garage and loads its own typeface. Everything the page can call — identify, setVariables, setScreen, defineAction, scheduleCall, openBooking — is safe before load(): it waits until the agent is on the page.
To draw the chat, the voice conversation and the agent's components in your own design instead, load it headless: load({ …, headless: true }) shows no widget, and your page reads everything from GraineAgent.state() — see Draw your own UI (headless). The same agent can be declared in markup with the graine-agent element — see The web component.
Install and the first answer
Put the agent on the page, know when it is there, and take it off again.
GraineAgent.load
Call it once on every page the agent belongs on, to put the launcher and the panel on the page.
It checks the publishable key with Graine before it draws anything, so a misconfigured agent never shows a launcher that opens onto an error. Called again with the same agent — a route re-rendering — it is the same load and returns the same promise. Called with another agent, it takes the one on the page off first (its frame, launcher and conversation) and puts the new one on; the visitor stays identified. Requests made meanwhile wait for the new agent.
The options it reads:
| Option | Type | Default | Meaning |
|---|---|---|---|
agentId | string | required | Which agent to show: the website agent's ID from Agent → Embed & Widgets → Install. |
publishableKey | string | required | The agent's publishable key (pk_live_…), from the same place. It identifies the agent and is safe in page source. |
variables | object | none | Prompt variables for this agent's conversations on the page, by name — up to 12, about 1 KB in all with the rest. What the page learns later goes in setVariables(), which wins over these on a shared name; the visitor's traits from identify() win over both. |
mode | "both" | "voice" | "chat" | the agent's | Which conversations the widget offers on this page, among those the agent's What visitors get allows: it can narrow them, never add one the dashboard turned off (the console says when it was asked to). Changed in loader 1.6.0: before, the dashboard's setting never reached the website. |
start | "voice" | "chat" | the agent's | New in loader 1.6.0. Which one opens first where both are offered, over the agent's Opens on. |
preload | boolean | false | New in loader 1.6.0. Load the widget straight away. Without it, the page loads the widget's frame when the visitor shows interest — a pointer over the launcher, the keyboard on it, a tap, or open() — so a visitor who never opens it costs your page almost nothing. |
chatSize | "compact" | "large" | "full" | the design's | How big the panel opens on this page, over the agent's Window size in the Garage. open({ size }) overrides it for one open. |
accent | string (#RRGGBB) | "#318CE7" | The launcher's colour when the agent has no accent of its own in the dashboard. |
position | "bottom-right" | "bottom-left" | "bottom-right" | Which corner the launcher sits in when the dashboard does not say. |
launcherLabel | string | "Chat with us", or "Talk to us" for a voice-only agent | What a screen reader announces for the launcher (and the words on a pill-shaped launcher) when the dashboard does not say. |
chatCloseDelaySeconds | number | 15 | New in loader 1.4.2 / SDK 0.14.3. How long the chat's conversation outlasts its window, in seconds: once no window shows the chat — the panel closed, or, headless, chat.shown(false) or close() — it closes this long after it left the screen, unless the chat is shown again or a message goes either way first (a message starts the wait again). 0 closes it at once; anything over 300 is 300; anything that is not a number is 15. Shown again after it closed, the chat connects again, and an identified visitor's conversation continues where it left off. Before 1.4.2 a conversation stayed open for 5 idle minutes. |
tokenProvider | function | none | New in loader 1.5.0 / SDK 0.14.4. Server tokens: a function returning a promise of a token your server minted for the signed-in visitor (POST /v2/client-tokens, with your secret API key — never on the page), or of null when there is none right now. Every request to Graine then carries the newest one. Needed once the agent's Require server tokens is enforced; without it nothing is sent and nothing changes. See Server tokens and the bot check. |
headless | boolean | false | New in loader 1.4.0 / SDK 0.14.0. true shows no widget — no launcher, no panel — and your page draws the chat, the voice conversation and the components from state(), driving them with chat, voice and component. The frame stays on the page, 1 × 1 and transparent, out of the way of clicks and the keyboard: it holds the connection, the microphone and the audio. See Draw your own UI (headless). |
identityTokenRefresher | () => Promise<string | null> | none | New in SDK 0.14.4. Your function for a fresh identity token, called when Graine says the visitor's token has expired or refuses a request as unverified, and before a conversation starts with a JWT less than a minute from expiry — at most once in 30 seconds for the same visitor, never twice at once. From loader 1.6.1 it also fetches the token of a visitor you identified without one; see GraineAgent.identityTokenRefresher. The same as setting GraineAgent.identityTokenRefresher; it belongs to the page, so it stays when load() puts another agent on it. |
| Parameter | Type | Default | Meaning |
|---|---|---|---|
options | object | required | The options above. agentId and publishableKey are required; everything else is optional. |
Returns — Promise<boolean> — true once the agent is on the page; false when it could not start (the browser console says why) or another load() came first. Example value: true.
Errors — it never rejects. Missing agentId or publishableKey, a refused key or a refused page origin resolve false and log [Graine] … in the console; the visitors see nothing. New in loader 1.5.0: when the agent could not start, what your page asked meanwhile — and asks until the next load() — is refused at once with the reason, as a GraineError code: invalid_key, origin_refused, rate_limited, unavailable, or network when Graine did not answer within 30 seconds. The next load() starts afresh. Before 1.5.0 every failure read invalid_key, until the page reloaded.
GraineAgent.destroy
Call it when the agent should leave the page — a route without it, or a sign-out screen.
Takes the agent off the page: its frame, its launcher and the conversation in it. load() puts one back, the same agent or another. What belongs to the page stays: who the visitor is, this browser's install ID, the memory choice, the variables from setVariables(), the screen and the page's actions. After a load() that failed, it clears that failure too: what you ask next waits for the next load().
Parameters — none.
Returns — nothing.
Errors — none.
GraineAgent
Use it to reach everything the loader offers; it exists as soon as the script runs.
window.GraineAgent
One object for the whole page. Every function on it exists before load() is called; what needs the agent waits until the agent is on the page. One agent is on the page at a time.
What to expect — The properties below are read-only, apart from identityTokenRefresher, which you set. schedulingRules, bookingAvailable, bookingUnavailableReason, memorySettings and installId are read each time you ask, so read them again after load() or identify() rather than keeping a copy.
| Property | Type | Meaning |
|---|---|---|
version | "1.6.1" | Read it to know which loader build the page is running — include it when you ask for support. setVariables and currentVariables are there from 1.3.0; headless (state, chat, voice, component), bookingSlots and bookingUnavailableReason from 1.4.0; memorySettings from 1.5.0; load({ start, preload }) and the one-tag install from 1.6.0; and from 1.6.1 the loader waits for the identity token identityTokenRefresher fetches for a visitor identified without one. |
switchesAgents | true | Read it to know that load() with another agent switches agents in place; a loader without it needs a page reload to change agent. |
installId | string | Read it for this browser's install ID — the same value getInstallId() returns. |
schedulingRules | object | Read it to know what the agent lets visitors book; see GraineAgent.schedulingRules. |
bookingAvailable | boolean | Read it to decide whether to offer your own “Call me” button; see GraineAgent.bookingAvailable. |
bookingUnavailableReason | string | null | Read it to say why booking is not offered; see GraineAgent.bookingUnavailableReason. |
memorySettings | object | null | New in loader 1.5.0. Read it for the trait that identifies your visitors and whether the agent remembers them at all; see GraineAgent.memorySettings. |
verification | object | New in SDK 0.14.4. Read it for what Graine made of the visitor — verified, unverified or invalid, and why; see GraineAgent.verification. |
identityTokenRefresher | function | null | New in SDK 0.14.4. The one property you may set: your function for a fresh identity token; see GraineAgent.identityTokenRefresher. |
Its functions: load, destroy, setTokenProvider, identify, setIdentityToken, onVerificationChange, setMemory, getInstallId, memories, forgetMemory, newConversation, open, close, state, defineAction, removeAction, setScreen, setVariables, currentVariables, addMaskRule, reportEvent, openBooking, bookingSlots, scheduleCall, scheduledCalls, cancelScheduledCall — each with its parameters, what it returns, its errors and an example. And three groups for a page that draws its own UI: chat, voice and component.
Server tokens and the bot check
Two protections an Admin turns on per agent (Agent → Embed & Widgets → Security), each with a report-only stage before it is enforced. New in loader 1.5.0 / SDK 0.14.4.
Server tokens. Your server vouches for the signed-in visitor: it mints a short-lived token with POST /v2/client-tokens and your secret API key — the agent_id, the user_id you pass to identify(), the scopes the page needs (chat, call, memory, booking, workflows) and ttl_seconds (60–3600) — and your page hands the loader a function that fetches it. Every request the loader and the widget make to Graine then carries it. Once Require server tokens is enforced, the publishable key alone opens nothing.
- When it is asked: as
load()starts; again shortly before the token expires (with a little jitter, and after a failure again in 2, 4, 8 … 60 seconds); whenidentify()names another visitor, or nobody (the token held was the one before's: it is let go of); and when Graine refuses a token — one question at a time. Nothing is asked while the page is hidden; back in view, a token close to its expiry is refreshed. A throw, or no answer within 15 seconds, counts asnull. - A live conversation is never ended because a token expired: tokens are checked when a conversation starts. A new conversation waits at most 10 seconds for a fresh token, then goes with the newest it has.
- Refused for its token (
token_required,token_invalid,token_expired), a request asks for a fresh token — at most once in 5 seconds — and goes once more, only with a different token.token_scopeandkey_revokedare final: the request rejects with the code and itsreason, and a conversation that cannot start says so rather than connecting another way. - The loader reads only the token's
iatandexp, keeps none in storage, and logs none. WithouttokenProvider, nothing is sent and nothing changes. - One provider mints for one agent. A page that puts another agent on with
load()passes that agent's provider.
The bot check. When it is on, the loader passes an invisible challenge from the provider your Admin chose — Cloudflare Turnstile or reCAPTCHA Enterprise — before it starts a conversation. Your page needs nothing beyond the loader: it loads the provider's script itself, only when a conversation is about to start (never as the page loads), and runs it out of sight. A managed check — a box to tick — appears only when the provider insists. The answer earns a pass that the loader sends instead of a new challenge for the next 30 minutes. If the challenge fails, the loader tries one fresh challenge; if the provider's script cannot load or does not answer within 10 seconds, the loader goes on without it and Graine's setting decides. A live conversation is never touched. If your site sends a Content Security Policy, allow the provider's script (challenges.cloudflare.com, or www.google.com/recaptcha/) and its frame.
| Code | HTTP | What it means |
|---|---|---|
token_required | 401 | The agent requires a server token and none came with the request: give load() a tokenProvider |
token_invalid | 401 | The token could not be checked — reason: malformed, signature, unknown_key, issuer or not_yet_valid |
token_expired | 401 | The token expired, and a fresh one did not come in time |
token_scope | 403 | The token is another agent's (agent) or another visitor's (user), or lacks the scope this needs (scope). Final |
key_revoked | 401 | This publishable key was revoked: load the agent with its new key. Final |
bot_check_failed | 403 or 503 | The bot check did not pass (missing, failed, expired), or Graine could not check it just now (unavailable, 503: new conversations wait) |
GraineAgent.setTokenProvider
Call it when where the agent's server tokens come from changes — after your visitor signs in, say; load({ tokenProvider }) sets the same.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
fn | function | null | required | A function returning a promise of a token your server minted for the signed-in visitor (or of null when there is none right now); null stops sending tokens. |
Returns — nothing. A token held from before is let go of and a fresh one is asked for at once; the widget hears each new token. Safe before load(): the next load() uses it.
Errors — none thrown: anything but a function or null is refused with a console error, and nothing changes. New in loader 1.5.0.
Identity, memory and conversations that continue
Tell the agent who the visitor is, so a returning visitor's conversation continues where they left it and the agent can remember them — or not, as they choose. Where the agent remembers its users, an identified visitor who comes back finds the widget's chat where they left it: the earlier messages under day separators, an earlier voice conversation as one “Voice call” row, and New conversation in the chat's header to start afresh.
GraineAgent.identify
Call it after your visitor signs in, and with null when they sign out.
The trait your agent's Who is the user? setting names (user_id unless you chose email, phone or a custom trait) is how Graine tells your visitors apart: it lets the agent remember a visitor and lets a booked call ring their app. Its value goes only to Graine and never becomes a prompt variable; every other trait is masked in the browser and reaches the agent as a prompt variable. A placeholder value ("guest", "0", an empty string, a masked value) identifies nobody. New in loader 1.5.0: traits without a usable value of that trait — user_id sent to an agent that identifies visitors by account_id, say — log one line in the console naming the trait, and what needs the visitor answers identity_required naming it too; memorySettings tells your page which trait it is.
It applies to the next conversation. null signs the visitor out of every agent they used on this page: this browser stops counting as one of their devices, and later conversations are anonymous. Identifying a different visitor signs the previous one out the same way. Safe before load().
A chat belongs to whoever was identified when it connected (SDK 0.14.0). Identify before the chat opens: if the visitor changes while it is open — identify() after the chat connected, another visitor, or null — the chat closes that connection, clears the messages it showed (they were the previous visitor's, or nobody's), keeps a message typed and not yet sent, and connects again at once for the new visitor, who then finds their earlier conversation or a welcome. On a page that draws its own chat (headless), it reconnects at once while your chat is on screen or a message waits, otherwise when you next show it. The same visitor again — other traits, memory switched — changes nothing until the next conversation.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
traits | object | null | required | Who the visitor is, by trait name — { user_id, name, plan }. null signs out. |
options | { memory?: boolean, identityToken?: string | null } | none | { memory: false } keeps this visitor's conversations out of memory (neither remembered nor recalled); { memory: true } turns it back on. Left out, their last choice in this browser stands — on until they make one. identityToken (new in SDK 0.14.4) proves who the visitor is — see below. |
Proving who the visitor is (SDK 0.14.4). Anyone can type an ID into a browser's console, so an agent can require proof: turn on Verified users for the agent (Agent → Embed & Widgets) and pass identityToken with the traits. The token is either an HMAC your server computes from the value of the trait that identifies visitors — HMAC-SHA256 with the agent's identity secret as the key and the value as you pass it (without surrounding spaces) as the message; 64 hex characters, or base64 — or the ID token (a JWT) of your own sign-in, when the agent is set to check those. The loader sends it only inside the identity Graine checks, and only with the value it was given for: never as a prompt variable, never in a URL, never in the console. It is kept in memory only, so pass it again after a page load. Graine answers a verified visitor with a user pass, which the loader sends beside the token for an hour so reconnecting is quick. Calling identify() again for the same visitor without a token keeps the one held; a different visitor, or identify(null), drops the token and the pass in that same call; identityToken: null clears it. A token longer than 4096 characters is not kept (the console says so, without the token). Replace an expiring token with setIdentityToken(), or let identityTokenRefresher fetch one when Graine needs it. A conversation already open is never cut by its token expiring: tokens are checked when a conversation starts.
While the agent only reports (Verified users without Require verified users), nothing changes for a visitor without a token. With Require verified users on, a visitor who is not verified still talks to the agent, anonymously — no memory, no name in Call History — and verification says why; memories(), forgetMemory(), bookings and past sessions are refused identity_unverified (with an identityTokenRefresher, the loader first asks it for a fresh token and sends the request once more).
Returns — nothing.
Errors — none. A sign-out that cannot reach Graine logs a warning in the console; the browser is released anyway after thirty days without use.
The visitor's details for the placeholders in the agent's prompt — a first name, a
plan — go in setVariables(), under the prompt's own
names; the traits reach the prompt too —
Send your user's details to the agent.
GraineAgent.setIdentityToken
Call it when your sign-in gives you a fresh identity token for the visitor already identified — before the last one expires.
New in SDK 0.14.4. Replaces the identity token for the current visitor without changing who they are: nothing is signed out, the chat stays as it is, and the next conversation or request carries the new token (inside the identity, as identify()'s token). null clears it. With nobody identified, the token belongs to nobody and the next visitor to sign in does not get it. A token longer than 4096 characters is not kept. See Proving who the visitor is.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
token | string | null | required | The new identity token, as your server or sign-in gave it; null to clear it. |
Returns — nothing.
Errors — none. A value that is not a string or null logs [Graine] … in the console and changes nothing.
GraineAgent.identityTokenRefresher
Set it once, so the loader can fetch a fresh identity token when Graine needs one.
New in SDK 0.14.4. Your function, resolving a fresh token (or null to keep the one held). The loader calls it when Graine says the visitor's token has expired, when a request is refused identity_unverified — that request is then sent once more with the new token — and before a conversation starts with a JWT that has less than a minute left (waiting at most 10 seconds for it). It is called at most once in 30 seconds for the same visitor and never twice at once. A function that throws, resolves nothing, or resolves after a different visitor signed in leaves the token as it was. It belongs to the page: load() with another agent keeps it. null takes it away.
It also fetches a token you have not given yet (loader 1.6.1). When you identify a visitor without an identity token and the agent has Verified users on, the loader asks your function before a request about the visitor — memories(), forgetMemory(), newConversation(), scheduledCalls(), scheduleCall(), cancelScheduledCall(), startWorkflow(), a headless page's past sessions — and waits up to 10 seconds for the token, so the request goes with it. A conversation in the widget can't be held back that long, so the loader asks as soon as the visitor shows interest in the launcher (or as the widget loads, when you call open() or load it with preload or headless), and the conversation waits up to one more second for the token when it starts. null, a throw or a longer wait lets the request go without a token, as before; the token is used from the moment it arrives, and a refresh the loader already waited for in vain is not waited for again. Another visitor signing in starts afresh: their token is asked for at once, and one still on its way for the visitor before never reaches them. Identify the visitor as soon as you know who they are, and set this function, so their first conversation is verified.
What to expect — reading it returns the function set, or null. Setting anything that is not a function or null logs [Graine] … in the console and changes nothing.
GraineAgent.verification
Read it to show whether the visitor is verified, or why not.
New in SDK 0.14.4. What Graine made of the visitor, a copy: changing it changes nothing. Read it again after load() and identify(), or hear each change with onVerificationChange().
| Field | Type | Meaning |
|---|---|---|
user | "off" | "verified" | "testUser" | "unverified" | "invalid" | "off" until load() has the agent's settings, and while the agent does not verify users. Then "unverified" until a conversation starts and Graine gives its verdict: "verified" (the token or the user pass proved the visitor), "unverified" (no token), or "invalid" (a token that did not prove them). "testUser" is a test user accepted without a token from a registered debug token — the iOS and Android SDKs' development mode, which a website does not have, so a page never sees it. A verdict newer than this loader reads "unverified". |
userReason | string | null | Why, with "unverified" or "invalid": "missing" (no token), "expired", "not_yet_valid", "signature", "audience", "issuer", "claim", "mismatch" (the token is for another value), "malformed", "unknown_key", "unavailable"; otherwise null. |
app | "off" | Always "off" on a website: proving the app is for the iOS and Android SDKs — a browser's requests carry the page's origin, which Allowed domains checks. A website sends no app declaration and no debug token. |
appReason | null | Always null on a website. |
Errors — none.
GraineAgent.onVerificationChange
Call it to hear each change of verification — to show a "verified" badge, or to fetch a new token when one is refused.
New in SDK 0.14.4. handler is called with the new verification — { app, appReason, user, userReason } — each time it changes: the agent's settings arriving, another visitor, Graine's verdict when a conversation starts. Not called with the current value: read GraineAgent.verification for that.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
handler | (verification) => void | required | Called with each new value. One that throws is logged and the others still run. |
Returns — () => void — call it to stop listening.
Errors — none. A handler that is not a function logs [Graine] … in the console; the returned function does nothing.
GraineAgent.setMemory
Call it when the visitor changes their memory choice in your privacy settings.
The same as identify() with the same traits and { memory: enabled }: the choice is kept in this browser for this visitor and applies to their next conversation.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
enabled | boolean | required | true to remember this visitor's conversations, false to stop. |
Returns — nothing.
Errors — none.
GraineAgent.getInstallId
Call it when you need this browser's install ID — to show in a support screen, for example.
A random ID made the first time the loader runs in this browser and kept in localStorage; where storage is refused, it lasts for the page's life. Graine counts a visitor's devices by it; the agent never sees it. The installId property returns the same value.
Parameters — none.
Returns — string — a UUID. Example value: "9b2e7c4a-1f3d-4e8a-b6c5-0d7f2a9e4b13".
Errors — none.
GraineAgent.memorySettings
Read it before you show a memory screen: which trait identifies your visitors for this agent, and whether the agent remembers visitors at all.
New in loader 1.5.0. The agent's memory settings as load() read them, read each time you ask: identityField is the trait its Who is the user? setting names — the key identify() must carry for the agent to know the visitor — and memoryEnabled says whether it remembers visitors at all. null until load() has the agent's settings, and again once the agent leaves the page.
| Field | Type | Meaning |
|---|---|---|
identityField | string | The trait that identifies a visitor for this agent: user_id, email, phone or the custom trait you chose. |
memoryEnabled | boolean | null | false when the agent remembers nobody — say so rather than showing an empty list; true when it remembers identified visitors; null when its settings did not say. |
Parameters — none.
Returns — { identityField, memoryEnabled } | null. Example value: { identityField: "user_id", memoryEnabled: true }.
Errors — none.
GraineAgent.memories
Call it to show the visitor what the agent remembers about them, on a privacy screen.
What the agent remembers about the identified visitor, newest first, at most 100, already redacted. Only from a browser that is one of the visitor's devices. It waits for load() to have the agent's settings, then decides — called as the page opens, it is answered once they arrive, never with identity_required for settings still on their way.
Parameters — none.
Returns — Promise<Array<{ id, text, createdAt, updatedAt }>> — id and text strings; createdAt and updatedAt are Dates, or null when Graine did not say. Example value: [{ id: "m_31", text: "Prefers a call after 6 PM", createdAt: Date("2026-10-12T09:15:00Z"), updatedAt: null }].
Errors — rejects with a GraineError (Errors): identity_required when nobody is identified, its message naming the trait the agent identifies visitors by — Nobody is identified. Call GraineAgent.identify() with the visitor's "user_id" first., or, when the traits you passed lack it, GraineAgent.identify() was given no usable "account_id" …; and identity_required too when the visitor who asked was replaced while the agent's settings loaded — "Someone else was identified while the agent's settings were loading, so nothing was asked for the customer identified before. Ask again for the customer identified now." (signed out meanwhile: the trait-naming sentence) — so nothing is asked for a visitor who did not ask (loader 1.5.0; the same visitor written another way is still them); device_limit from a browser that is not one of the visitor's devices; rate_limited, network, unavailable; and, when load() failed, that failure's own code at once — invalid_key, origin_refused, rate_limited, unavailable or network.
GraineAgent.forgetMemory
Call it when the visitor asks the agent to forget them.
Deletes everything the agent remembers about the identified visitor, and the conversation it kept for them. Only when it succeeds does the widget's chat clear; a refusal leaves it as it was.
Parameters — none.
Returns — Promise<number> — how many memories were deleted. Example value: 3.
Errors — rejects with a GraineError: identity_required (naming the trait, as memories() does — and when someone else was identified while the agent's settings loaded: nothing is forgotten for anyone but the visitor who asked), device_limit, rate_limited, network, unavailable; and, when load() failed, that failure's own code — invalid_key, origin_refused, rate_limited, unavailable or network.
GraineAgent.newConversation
Call it to give the visitor a fresh conversation instead of continuing the last one.
Graine lets go of the conversation it kept for this visitor and agent, and the widget's chat clears and opens fresh, with the welcome again. Memories the agent keeps about the visitor stay as they are. With nobody identified nothing was kept, so only the chat starts over. The chat's own New conversation button does the same.
Parameters — none.
Returns — Promise<void> — resolves once the chat has started over.
Errors — rejects with a GraineError (device_limit, rate_limited, network, unavailable; identity_required when the visitor who asked was replaced, or signed out, while the agent's settings loaded; when load() failed, that failure's own code — invalid_key, origin_refused, …); the chat is then as it was.
Chat
The widget's panel holds the chat (and, where offered, the voice conversation). Open it from your own buttons, at the size you want. The chat shows the visitor's booked calls at the top, with Book a call where booking is available — see Booking with the SDK's sheet.
New in loader 1.4.2. The panel is the chat's window: its chat connects when the visitor first opens the panel, and closes 15 seconds after the panel closes (load({ chatCloseDelaySeconds })), unless it is opened again or a message goes either way first. Opened again, the chat connects again and an identified visitor's conversation continues where it left off, with no new welcome. Before 1.4.2 the chat connected as the page loaded and stayed open while the panel was closed.
New in loader 1.6.0. A conversation goes on across your site's pages, for every visitor, identified or not: on the next page of the same tab, within 30 minutes of the last message, the chat shows the conversation again and the agent carries on from it, with no new welcome. On a computer the panel is open as the visitor left it; on a phone it stays closed and the launcher shows a dot. Nothing connects until the visitor writes. A new tab, newConversation() or the agent ending the chat starts a fresh one. On a phone, a compact window opens as a sheet over most of the page. Opened from the keyboard, the panel takes focus (the message field on a computer), and Escape inside it closes it and returns focus to the launcher.
GraineAgent.open
Call it from your own “Chat with us” or “Talk to us” button to open the panel.
Nothing happens before load() has put an agent on the page. On a computer, compact is the panel above the launcher and large and full open a bigger panel (420 wide, up to 760 tall); on a page narrower than 640 px, large is a sheet over most of the page and full the whole page, and the page behind stops scrolling while it is open. Escape, the panel's close control and a tap on the dimmed page close it.
Loaded headless there is no panel: open() says your page's own chat is on screen — the same as chat.shown(true), which connects the chat — and its options are ignored.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
options | { mode?: "chat" | "call", size?: "compact" | "large" | "full" } | none | mode picks the tab the panel opens on, among those the agent offers. size is for this open only; it wins over load({ chatSize }) and the agent's Window size. |
Returns — nothing.
Errors — none.
GraineAgent.close
Call it to close the panel from your own code — after a task is done, for example.
Closes the panel. A booking sheet open in it closes too, without booking (openBooking() resolves null). The chat's conversation closes 15 seconds later (load({ chatCloseDelaySeconds })) unless the panel is opened again first — new in loader 1.4.2. Loaded headless, it says your page's chat left the screen — the same as chat.shown(false).
Parameters — none.
Returns — nothing.
Errors — none.
GraineAgent.pin
Call it to show what the conversation is about — the page, a step, an item — as a card at the top of the chat.
The card shows a title and, when you give them, a subtitle, a small picture and a badge, drawn in the agent's design where its chat style in the Garage puts it: a bar under the chat's header, or a card at the top of the conversation. A style that shows no card draws nothing. The card is for the visitor only — the agent is not told about it; describe the page to the agent with setScreen(). It belongs to the page: it stays when the panel closes and opens again, and when load() puts another agent on the page. Safe before load().
| Parameter | Type | Default | Meaning |
|---|---|---|---|
card | { title: string, subtitle?: string, imageUrl?: string, badge?: string } | null | required | title is required: one line, up to 60 characters. subtitle is up to 80, badge up to 24, imageUrl an https:// address. Longer words are cut, line breaks become spaces, and a picture at any other kind of address is left out. null takes the card away. |
Returns — nothing.
Errors — none. A card with no title takes the card away.
GraineAgent.on
Call it to hear about what the visitor does in the widget that your page may want to know — the rating they give a chat — and, on a page that draws its own UI, every change to what it draws.
| Event | The handler receives | When |
|---|---|---|
"chat_rated" | { value, scale, style } — style "thumbs" with value 1 (up) or 0 (down) and scale 1, or "stars" / "emoji" with value 1–5 and scale 5 | The agent ended a chat whose style asks for a rating, and the visitor gave one — at most one per conversation. Headless too, when your page rates with chat.rate. |
"state" | { chat, voice, component } — what state() returns | New in loader 1.4.0. Loaded headless: whenever any of it changes (a reply streaming in changes it many times a second), and once, idle, when the agent leaves the page. |
"chat" | state().chat | New in loader 1.4.0. Loaded headless: the chat changed. |
"voice" | state().voice | New in loader 1.4.0. Loaded headless: the voice conversation changed — about five times a second while a call is live, for the levels. |
"component" | state().component — an object, or null | New in loader 1.4.0. Loaded headless: a component arrived, started loading, or went (answered, closed, replaced, the call over). |
| Parameter | Type | Default | Meaning |
|---|---|---|---|
event | string | required | The event's name, from the table above. |
handler | function | required | Called with what the event carries. A handler that throws is logged in the browser console, and the other handlers still run. |
Returns — () => void — call it to stop listening.
Errors — none: a missing event name or handler logs [Graine] … in the console and returns a function that does nothing.
The voice bar
Not on this platform as a separate view: on a website, talking to the agent happens in the widget's panel, on its call tab — open({ mode: "call" }) opens it there, and load({ mode }) decides whether it is offered. The browser asks the visitor for the microphone when the conversation starts. Captions, the connection's state and the call's controls are drawn inside the panel. To draw a voice bar of your own — its status, captions, levels and buttons — load the agent headless and use state().voice and GraineAgent.voice.
Draw your own UI (headless)
New in loader 1.4.0 / SDK 0.14.0. load({ …, headless: true }) puts the agent on the page with no widget at all — no launcher, no panel. Your page draws the chat, the voice conversation and the agent's components in its own design; the loader still runs everything behind them — the connection, the microphone, the audio, the agent — in a frame of its own, 1 × 1 and transparent, out of the way of every click. What the widget's own screens would read is in state(); what their controls do is in chat, voice and component. The values and their meanings are the same as every app SDK's, so one design of yours works on every platform.
- Load it headless, on every page the agent belongs on, as usual.
- Draw from the state. Read
GraineAgent.state()once, then redraw onGraineAgent.on("state", …)— or on the finer"chat","voice"and"component". - Wire your controls to
chat.send(),chat.sendQuickReply(),chat.rate(),voice.start(),voice.stop(),voice.setMuted(),component.submit()andcomponent.dismiss(). They are safe right afterload(): what you ask before the agent is on the page waits for it. - Say when your chat is on screen with
open()andclose()— orchat.shown(true)andchat.shown(false). The chat connects the first time you show it or send a message, so a page that never opens one starts no conversation. New in loader 1.4.2: with no chat on screen, the conversation closes 15 seconds after it left the screen —load({ chatCloseDelaySeconds })sets how long; a message either way meanwhile starts the wait again — andstatusrests at"idle"; showing the chat again, or a message, connects it, and an identified visitor's conversation continues where it left off, with no new welcome. In 1.4.0–1.4.1 it stayed open for 5 idle minutes. A page that never says keeps it until Graine's own idle limit. - Show the visitor's past sessions (new in loader 1.4.2), as your dashboard's Execution History lists them:
chat.refreshPastSessions()fillsstate().chat.pastSessions,chat.loadMorePastSessions()adds the next page, andchat.sessionTranscript(id)resolves one session's whole conversation — see GraineAgent.chat.
Everything else works as it does with the widget: identify, setVariables, setScreen, defineAction, reportEvent, memory, newConversation, scheduleCall and the scheduled-calls list. What the widget would have drawn is yours to draw: pin() is kept but not drawn (draw your own card), and openBooking() resolves null at once — build your own booking screen with bookingSlots() and scheduleCall().
- Start a voice conversation from the visitor's tap or click. The browser asks for the microphone then, and plays the agent's voice on the strength of that tap. Called with no tap behind it, a browser may keep the audio silent until the visitor interacts with your page.
- Your page only. The frame posts its state to your page alone — to the origin of the page that loaded it, never to every listener — and takes commands only from your page. Nothing your page sends can carry Graine's reserved
graine_keys: they are taken out of a component's answer before it leaves your page, and again in the frame. - Not with the widget. Without
headless, the widget is drawn exactly as before;chat,voiceandcomponentthen do nothing (the console says so) andstate()stays idle — the widget's own controls do it all.
GraineAgent.state
Call it to draw your own chat, voice bar or component from what the widget's own screens would read.
New in loader 1.4.0. A snapshot, for a page loaded headless: the chat, the voice conversation and the component the agent drew. A copy, fresh each call — changing it changes nothing. Idle until the agent's frame reports, and idle again once the agent leaves the page. The "state" event carries the same object each time it changes.
Parameters — none.
Returns — { chat, voice, component }, as below.
chat | Type | Meaning |
|---|---|---|
status | string | Where the chat's connection is: idle (not opened yet, resting after the agent ended the conversation, or — new in loader 1.4.2 — closed after no screen showed it for chatCloseDelaySeconds; the chat shown again, or a message, connects), connecting, connected, reconnecting (a drop, being made again), offline (no network, and a message waits), failed (the agent cannot take the chat now — error says so in the visitor's words; it looks again every minute) or disconnected (Graine ended an idle conversation, or its time limit came; the visitor's next message, or the chat shown again, connects). |
turns | Array<object> | The messages, oldest first — the turn fields below. A conversation that continues starts with its earlier messages (restored). |
sessionId | string | null | New in SDK 0.14.0. The id of the chat's current session — this connection's run, the id Execution Logs shows for it. null until Graine names it as the chat connects, while it connects again, and after identify names another visitor. |
sessions | Array<object> | New in SDK 0.14.0. The sessions the thread holds, oldest first — the session fields below: for a "past conversations" list or session dividers of your own. Consecutive turns with the same session make one. |
typing | boolean | The agent is working on a reply: draw a typing indicator. |
quickReplies | Array<{ label, text }> | The replies the agent suggests for its latest turn: draw label as chips, and send one with chat.sendQuickReply. They go once the visitor sends anything, the agent starts another turn, or the conversation ends. |
ended | boolean | The agent ended the conversation: ask "How was this chat?" if you want to, and answer with chat.rate. The visitor's next message starts a new one. |
rating | { value, scale, style } | null | The visitor's answer, once given — at most one per conversation. |
newConversationBefore | Array<string> | The ids of the turns a "Disconnected · new conversation" row goes before — where Graine began a new conversation under earlier lines. Draw it like a day separator; empty when none. |
error | string | null | Why the chat failed, a sentence fit for the visitor, while status is failed; otherwise null. |
pastSessions | { sessions, loading, hasMore, error } | New in loader 1.4.2 / SDK 0.14.3. The identified visitor's earlier sessions with this agent — chats, voice conversations and calls — newest first, as Execution History lists them: sessions (the past-session fields below), loading (a page is being read), hasMore (there are older ones: chat.loadMorePastSessions() reads the next page) and error — why the last read failed, as a code: identity_required (nobody is identified), device_limit (this browser is not one of the visitor's devices), rate_limited, unavailable, network — or, when the agent's load() failed, that failure's own code (loader 1.5.0) — else null. Empty until chat.refreshPastSessions(), and emptied again when identify() names another visitor, or nobody. The session open right now is never in it. |
| A past session | Type | Meaning |
|---|---|---|
id | string | The session's id — the one Execution History shows. Pass it to chat.sessionTranscript(id). |
startedAt | Date | When it began. |
endedAt | Date | null | When it ended; null when Graine did not say. |
durationSeconds | number | null | How long it lasted, in seconds; null when Graine did not say. |
channel | "chat" | "voice" | "call" | How it was held: typed (chat), a voice conversation in the browser or an app (voice), or a call (call). |
direction | "inbound" | "outbound" | null | On a call, who called whom: the visitor (inbound) or Graine (outbound); null when it does not apply. |
status | string | How it ended, in plain words — completed, missed, failed, … — or a newer word, as Graine sent it; "" when it said none. |
turns | number | How many turns it holds. |
preview | string | The visitor's first line, at most 120 characters; "" when there is none. |
| A turn | Type | Meaning |
|---|---|---|
id | string | Use it as your key: stable while the turn is on screen, its words streaming in included. |
role | "agent" | "customer" | Who said it — customer is your visitor. |
text | string | The words, growing while live. The agent's may carry light markdown — bold, italic, links, lists. |
at | Date | null | When it was said. |
live | boolean | The agent's words are still arriving. |
restored | boolean | From an earlier conversation, restored when the chat opened. |
channel | "chat" | "voice" | voice: said on a call — draw a run of them as one "Voice call" row, never their words. |
delivery | "sending" | "sent" | "failed" | A message of the visitor's: waiting for the connection, sent, or not sent (offer to send it again with chat.send). The agent's turns are always sent. |
proactive | boolean | The agent spoke unasked. |
session | string | null | New in SDK 0.14.0. The id of the session it was said in — a chat's, or a call's for a voice turn. A message takes the session of the connection that carries it: one typed before the chat connected, or said before Graine named the session, takes it as soon as Graine does. null for messages kept from before sessions were recorded. |
| A session | Type | Meaning |
|---|---|---|
id | string | null | The session's id; null for the messages kept from before sessions were recorded, which make one session together. |
startedAt | Date | null | When its first message was said. |
endedAt | Date | null | When its last message was said — for the current session, the latest so far. |
channel | "chat" | "voice" | voice when every message of it was said on a call. |
turns | number | How many messages it holds. |
current | boolean | It is the chat's current session (sessionId). |
voice | Type | Meaning |
|---|---|---|
status | string | Where the voice conversation is, first match wins: failed (error says why), reconnecting (the network dropped the call and it is being placed again), connecting, muted, speaking (the agent's line is arriving), thinking (the visitor finished a sentence and the agent has not answered yet), listening, then — off a call — ended (a call ended and no other has started) or idle. |
captions | Array<{ role, text, live }> | This call's transcript, oldest first, its last 12 lines: the agent's line as it is spoken and the visitor's as heard, live until final. A new call starts empty. |
agentLevel | number | The agent's voice, 0–1, about five times a second while the call is live; 0 otherwise. |
micLevel | number | The visitor's microphone, 0–1, likewise; 0 while muted. |
muted | boolean | The microphone is muted (voice.setMuted). |
transport | "websocket" | "webrtc" | null | What the call runs on, once one has been placed; null before. |
transportFallbackReason | string | null | Why a call that asked for WebRTC runs on the WebSocket; null when it did not fall back. |
error | string | null | Why the call could not work, a sentence fit for the visitor, while status is failed — the microphone refused, or the call could not be connected (starting again tries again); otherwise null. |
component | Type | Meaning |
|---|---|---|
id | string | Pass it to component.submit or component.dismiss. |
kind | string | Which component, such as product_list, plan_comparison, quick_actions, calendar_slots, info_card or lead_form — or a newer kind, as Graine sent it. |
data | object | null | What to draw, as the agent's component configured it; null while it loads. |
fallbackText | string | The words to show where you do not draw this kind. |
pending | boolean | The agent asked for it and its content is loading (up to 12 seconds): draw a placeholder. |
component is null when there is none. It is the newest the agent drew, in the chat or on a call, until it is answered or closed, a newer one comes, the chat starts over, or the call ends.
Errors — none.
GraineAgent.chat
Call these from your own chat's controls, on a page loaded headless.
New in loader 1.4.0. The chat connects the first time you show it or send something. Each call is safe right after load(): what you ask before the agent is on the page waits for it, in order. The past sessions (new in loader 1.4.2 / SDK 0.14.3) are read for the identified visitor, only from a browser that is one of the visitor's devices; asking for them opens no chat.
| Function | Parameters | What it does |
|---|---|---|
send(text) | text: string, up to 4,000 characters (trimmed) | Sends the visitor's message. Sent while the chat is not connected, it waits (delivery "sending") and connects the chat; after the agent ended the conversation, it starts a new one. Blank text sends nothing. |
sendQuickReply(reply) | reply: one of state().chat.quickReplies, or its text | Sends the reply's text as the visitor's message — not its label. |
rate(style, value) | style: "thumbs", "stars" or "emoji" · value: thumbs 1 (up) or 0 (down), stars and emoji 1–5 | Answers "How was this chat?" once the agent ended the conversation — once per conversation; rating and the "chat_rated" event follow. Anything else logs [Graine] chat.rate(style, value) needs… and sends nothing. |
newConversation() | none | The same as GraineAgent.newConversation(): Graine lets go of the conversation it kept and the chat starts over. Returns its promise. |
shown(visible) | visible: boolean | Says whether your chat is on screen. true connects the chat (a conversation that closed connects again — an identified visitor's continues where it left off); false closes the conversation 15 seconds after it left the screen (load({ chatCloseDelaySeconds }); a message either way meanwhile starts the wait again). open() and close() say the same. New in loader 1.4.2: in 1.4.0–1.4.1 it closed after 5 idle minutes. |
refreshPastSessions() | none | New in loader 1.4.2. Reads the newest page of the visitor's past sessions into state().chat.pastSessions: loading while it reads; what was loaded stays until the page comes, then is replaced by it. With nobody identified it asks nothing and error says identity_required. |
loadMorePastSessions() | none | New in loader 1.4.2. Reads the next page and adds it after what was loaded — a session already listed is not listed twice. Nothing while a page is being read, or once hasMore is false. |
sessionTranscript(id) | id: string — a past session's id | New in loader 1.4.2. One past session's whole conversation. Resolves { id, startedAt, endedAt, durationSeconds, channel, direction, status, turns } — the past-session fields (state()), with startedAt a Date | null — and turns, oldest first: { role: "customer" | "agent", text, at: Date }. |
Returns — nothing, except newConversation(): a Promise<void>, and sessionTranscript(id): a Promise<object>, as above.
Errors — none: without headless they log [Graine] GraineAgent.chat, .voice and .component drive a headless widget… in the console and do nothing, and with load({ mode: "voice" }), which offers no chat, they say so and do nothing. sessionTranscript(id) instead rejects with a GraineError (Errors): invalid_request with no id, without headless or with mode: "voice"; identity_required when nobody is identified, or someone else was identified while the agent's settings loaded (the frame is not asked); device_limit from a browser that is not one of the visitor's devices; not_found for an unknown session or another visitor's; rate_limited, unavailable (also when the agent is taken off the page first), network; and, when the agent's load() failed, that failure's own code, at once (loader 1.5.0). refreshPastSessions() and loadMorePastSessions() then put that code in state().chat.pastSessions.error.
Past sessions, on a history screen of your own:
GraineAgent.voice
Call these from your own voice bar's buttons, on a page loaded headless.
New in loader 1.4.0. What the widget's call buttons do. Call start() from the visitor's tap or click: the browser asks for the microphone then. Follow the call in state().voice.
| Function | Parameters | What it does |
|---|---|---|
start() | none | Starts a voice conversation: status goes connecting, then listening. Not with load({ mode: "chat" }), which offers no voice — the console says so. |
stop() | none | Ends it: status goes ended — or back to idle for a call that had not connected yet. |
setMuted(muted) | muted: boolean | Mutes or unmutes the microphone: muted, and status muted while the call is live. |
Returns — nothing.
Errors — none: a refused microphone or a call that could not be connected shows in state().voice as status failed, with error.
GraineAgent.component
Call these from your own rendering of the component the agent drew (state().component), on a page loaded headless.
New in loader 1.4.0. What the widget's component controls send, on the conversation it came from — the chat or the call. Either takes the component away.
| Function | Parameters | What it does |
|---|---|---|
submit(id, data, summary) | id: the component's id · data: object — the structured answer · summary: string — the visitor's turn in words, such as "The gold plan, please" | Answers it. data is for your webhook (keys starting with graine_ are taken out); summary is what the agent reads — without it the conversation does not move. Without an id it logs [Graine] component.submit(id, data, summary) needs the component's id. and sends nothing. |
dismiss(id) | id: the component's id | Closes it unanswered. The agent is told quietly, so it does not go on about options nobody can see. |
Returns — nothing.
Errors — none.
The web component
New in loader 1.4.0 / SDK 0.14.0. The loader also defines a custom element, graine-agent: the same agent, declared in your markup instead of called from a script — useful in a framework that renders elements, and headless or not. It draws nothing itself: the widget does, or, with headless, your page.
On the page, it loads the agent with its attributes as load()'s options; taken off the page, it takes the agent off (destroy()); an attribute that changes — headless added or removed, another mode — loads it again. Everything it offers is GraineAgent's own, so one agent stays one agent: use one element per page, as with load().
| Attribute | load() option | Meaning |
|---|---|---|
agent-id | agentId | Required, with publishable-key; nothing loads until both are there. |
publishable-key | publishableKey | The agent's publishable key. |
headless | headless | Present: no widget — draw your own UI (Draw your own UI (headless)). |
mode | mode | both, voice or chat. |
chat-size | chatSize | compact, large or full. |
accent · position · launcher-label | accent · position · launcherLabel | The launcher's fallbacks. |
chat-close-delay-seconds | chatCloseDelaySeconds | New in loader 1.4.2. How long the chat outlasts its window, in seconds — chat-close-delay-seconds="30"; 15 when absent. |
The element's variables property, set to an object before the element is on the page, is load()'s variables; afterwards, use setVariables().
| Member | What it is |
|---|---|
state() · on(event, handler) | GraineAgent.state() and GraineAgent.on() — see GraineAgent.state and GraineAgent.on. |
chat · voice · component | GraineAgent.chat, GraineAgent.voice, GraineAgent.component — the same objects, the past sessions' chat.refreshPastSessions(), chat.loadMorePastSessions() and chat.sessionTranscript(id) included. |
open() · close() | GraineAgent.open() and GraineAgent.close(). |
agent | GraineAgent itself, for everything else: identify, setVariables, setScreen, defineAction, scheduleCall, … |
ready | load()'s promise: true once the agent is on the page. |
| DOM event on the element | event.detail | When |
|---|---|---|
graine-ready | { ok } | The element's load() finished: ok is what it resolved. |
graine-state · graine-chat · graine-voice · graine-component | What the "state", "chat", "voice" and "component" events carry | Headless: each change. |
graine-chat-rated | { value, scale, style } | The visitor rated a chat the agent ended. |
A browser without custom elements simply has no graine-agent; GraineAgent works as ever. A page that defines its own graine-agent keeps it: the loader leaves it alone.
Several agents in one app
A page shows one agent at a time. A single-page app that wants a support agent in its help pages and another agent elsewhere calls load() again with the other agent on that route: the agent on the page is taken off first (its frame, launcher and conversation) and the new one is put on, and load() resolves true once it is there. GraineAgent.switchesAgents says the loader can do this. Who the visitor is, the install ID, the memory choices, the variables from setVariables(), the screen and the page's actions belong to the page and carry over, while load()'s variables are the agent's own; identify(null) signs the visitor out of every agent they used on the page. destroy() takes the agent off without another.
Screen context, actions and components
Tell the agent what the visitor is looking at, and let it act on your page through functions you write. The agent's components (product lists, choices, time slots) are drawn inside the widget; the page needs no code for them — unless it is loaded headless, when your page draws them from state().component and answers with GraineAgent.component.
GraineAgent.setScreen
Call it whenever what the visitor can see changes, so the agent talks about the right thing.
context is { screen, title, journey, fields, error, data, availableActions }: a stable ID for the screen, its title, where it sits in a flow ({ name, step, of, next }), its fields ({ name, label, value, status, error, optional } — status is "empty", "filled", "invalid", "pending" or "locked"), a screen-level error, anything else the agent should know, and which of your actions work here. Report real values: card numbers, phone numbers, email addresses and similar are masked in the browser before anything leaves the page, and your own rules from addMaskRule() apply too. The first change goes at once and later ones at most every 400 ms; before the widget exists the latest screen is kept and sent when it does. null clears it.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
context | object | null | required | What the visitor can see now, as above. |
Returns — nothing.
Errors — none.
GraineAgent.setVariables
Call it to hand the agent what your page learns while it is open — the visitor's first name after they sign in, the plan they just moved to, what is in their cart.
Sets prompt variables while the page is open, the way every app SDK's setVariables does. Merged, not replaced: a later call changes only the names it mentions, null under a name removes it, and setVariables(null) removes every value set this way. A name removed falls back to load()'s value for it, else the agent's default from the dashboard. On a shared name the visitor's traits from identify() win over these, and these win over load()'s variables.
Values become text — 34 arrives as "34", true as "true" — and are masked in the browser like the traits, your own rules from addMaskRule() included; an object, a list or a function is left out, and a name that already had a value keeps it. They reach the next conversation, chat or voice — not one already under way. Safe before load(). They belong to the page: they stay when load() puts another agent on the page and after destroy(), and last until the page is closed or reloaded.
A chat carries up to 12 variables, about 1 KB in all — load()'s, these and the traits together — and over 1 KB none of them reach the agent in that chat; a voice conversation on High quality takes more. Every channel's limits: Variables.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
values | object | null | required | Prompt variables by name, merged into those already set: null under a name removes it; null for the whole object removes them all. |
Returns — nothing.
Errors — none. Anything but an object or null logs [Graine] setVariables(values) needs an object of names and values, or null to clear them. in the console and changes nothing.
GraineAgent.currentVariables
Call it to check exactly which variables the next conversation will carry.
Every variable the next conversation carries, merged in precedence order: the agent's defaults from the dashboard (once load() has them), load()'s variables, setVariables(), then the traits from identify() without the identifying trait — as the prompt reads them: text, masked. A copy: changing it changes nothing. It shows the set before the limits above, which apply when the conversation starts.
Parameters — none.
Returns — object — every variable by name, each value a string. Example value: { app_name: "Acme", name_user: "Asha", plan: "Gold", cart_items: "3" }.
Errors — none.
GraineAgent.defineAction
Call it to let the agent do one thing on your page — open a section, apply a filter, fill a form.
Declare the action on the agent in the dashboard too: a handler with no declaration is never offered, and a declared action this page does not define is refused with “This page does not implement "…".”. The agent can call only the functions you define here. handler(args) receives the agent's arguments and returns { status, message, data } — or a promise of it — where status is "ok" (the default when you leave it out), "refused" or "error", and message is what the agent is told. Answer within 6 seconds — the SDKs' deadline: after that the agent is told “The page did not finish "…" in time.” and a later answer is dropped. A handler that throws answers error with its message. Defining a name again replaces the handler. Safe before load().
| Parameter | Type | Default | Meaning |
|---|---|---|---|
name | string | required | The action's name, exactly as it is declared on the agent. |
handler | (args) => result | Promise<result> | required | Runs the action and says how it went: { status: "ok" | "refused" | "error", message, data }. Return ok only when it really happened. |
Returns — nothing.
Errors — none. A call without a name or a function logs [Graine] defineAction(name, handler) needs both. in the console.
GraineAgent.removeAction
Call it when an action stops making sense — a section unmounting, for example.
The agent stops being offered the action; a request for it afterwards is refused.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
name | string | required | The action's name, as it was defined. |
Returns — nothing.
Errors — none.
GraineAgent.addMaskRule
Call it once at start-up to mask a value shape only your site knows — an account number, say.
Adds a rule applied after the built-in ones (card numbers, government ID numbers, phone numbers, email addresses) to everything the screen context, the traits and setVariables() carry, before it leaves the page — values set before the rule was added included. Every match is replaced, whether or not the pattern has the g flag.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
pattern | RegExp | required | What to mask. |
token | string | "[REDACTED]" | What replaces each match. |
Returns — nothing.
Errors — none. A pattern that is not a RegExp logs [Graine] addMaskRule needs a RegExp. in the console.
GraineAgent.reportEvent
Call it when something happens that the agent may want to speak up about — a payment failing, a form being rejected.
The event reaches the conversation that is live in the widget. With no agent on the page it is dropped, not kept.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
event | { name: string, detail?: string } | required | What happened, in a word (name), and a sentence about it (detail) for the agent. |
Returns — nothing.
Errors — none.
Calls the user places
Not on this platform: a website has no native calls. A visitor talks to the agent in the widget's panel (see The voice bar); phone-style calls are part of the mobile SDKs.
Calls Graine rings
Not on this platform: a browser cannot be rung. A call booked from a website — with openBooking() or scheduleCall() — rings the visitor's app, on a phone where they use your app and are identified with the same trait; the booking sheet says “We'll ring you in the app”.
Booking with the SDK's sheet
“Call me at…” with no screen of your own: the widget draws the booking sheet in the agent's design, and the call it books rings the visitor's app. Offer it from your own button with openBooking(), or let the visitor find it in the chat.
What the sheet shows. A header, “Book a call”, with “{call name} will call you” under it — the call name is the agent's (Calls & scheduling), else the chat's title, else the agent's heading. Day: a chip for each day from today to the furthest day the agent allows — “Today”, “Tomorrow”, then the weekday and date, such as “Thu 16 Oct” — scrolling sideways. Time: the browser's time field, held to the times the chosen day offers, on 5-minute marks, between earliest(now) (rounded up to the next 5 minutes) and latest(now); a time typed outside them moves to the nearest one the day has. Under it, the browser's time zone and the chosen time, such as “Asia/Kolkata · Tue 14 Oct, 6:00 PM”, and “We'll ring you in the app”. What's it about? (optional): one line, at most 120 characters. Then Book call, with a spinner while it books. Once booked: “Booked — {call name} will call you on {day}, {time}” and Done.
It opens over the widget's panel: up from the bottom when the panel is a sheet or fills the page (large or full on a page narrower than 640 px), otherwise as a centred card. Escape, the close control and a tap outside close it. The times offered move on as the clock does while it is open.
A refusal stays in the sheet as one line under the button, in these words:
| Code | The line |
|---|---|
too_soon | Pick a time at least N minutes from now |
too_far | Pick a time within N days |
outside_window | That time is outside the hours we can call — pick another |
too_many_pending | You already have N calls booked — cancel one first |
scheduling_off | Booking a call isn't available right now |
identity_required | Sign in to book a call |
| anything else | Couldn't book just now — try again |
N is the agent's own number — its minimum notice, its furthest day, its limit of calls — singular for one (“1 minute”, “1 day”, “1 call”). The sheet opens even when booking is not available, says why (the scheduling_off or identity_required line) and books nothing — so check bookingAvailable before offering it. After too_soon the offer moves on to what is bookable now.
In the chat. The widget's chat shows the visitor's booked calls first in the conversation — an Upcoming calls card with each call's time in the visitor's time zone, the call name and Cancel (“Cancelling…” while it goes, “Couldn’t cancel · tap to retry” if it fails), at most three, soonest first — and, where booking is available, Book a call under them, or alone in the card's place when nothing is booked. Neither shows when the agent's design hides the booked-calls card (Garage → Chat window → Booked calls). A booking made in the sheet refreshes the card; it is also read again when the chat opens and, after the agent replies, at most every 30 seconds.
GraineAgent.bookingAvailable
Read it to decide whether to show your own “Call me” button.
true when the agent lets visitors book calls (Calls & scheduling → users may book) and the visitor is identified with the trait the agent's Who is the user? setting names. A browser cannot be rung, so unlike on a phone it does not depend on Graine being able to ring this device: the booking rings the visitor's app. false until load() has the agent's settings. Read it again after identify().
Parameters — none.
Returns — boolean. Example value: true.
Errors — none.
GraineAgent.bookingUnavailableReason
Read it to tell the visitor why your “Call me” button is not there — or to sign them in first.
New in loader 1.4.0. The first part of bookingAvailable's rule that fails, as a word, the same as every SDK's: not_loaded (load() does not have the agent's settings yet), scheduling_off (the agent does not let visitors book) or not_identified (nobody is identified with the trait the agent's Who is the user? setting names). null when the visitor can book. A browser is never rung, so the phones' rings_not_set_up is never the reason here. Read it again after load() and identify().
Parameters — none.
Returns — string | null. Example value: "not_identified".
Errors — none.
GraineAgent.openBooking
Call it from your own “Call me” button to let the visitor book a call in the widget's sheet.
Opens the panel on the booking sheet (above) and resolves when the sheet closes. One at a time: a newer openBooking(), the panel closing or the agent leaving the page ends the one before, unbooked. Safe before load(): the sheet opens once the agent is on the page; if load() fails, it resolves null — at once when it is called after a load() that failed. Loaded headless, nothing is drawn: it resolves null at once and the console says to build your own with bookingSlots() and scheduleCall().
| Parameter | Type | Default | Meaning |
|---|---|---|---|
options | { reason?: string } | none | reason fills What's it about?, trimmed to 120 characters; the visitor may change it. It is kept with the call for the agent and never put in the notification that rings it. |
Returns — Promise<GraineScheduledCall | null> — the call booked in the sheet (GraineScheduledCall (website)), or null when the visitor closed it without booking. Example value: { id: "6f1c2a9e-7d1b-4c47-9a6e-2f0d8b1c5e44", at: Date("2026-10-16T12:30:00Z"), status: "scheduled", source: "app", reason: "Talk through my order", isUpcoming: true, canCancel: true }.
Errors — it never rejects: a refusal stays in the sheet as its line.
The scheduled-calls list
Book calls from your own interface, list the visitor's upcoming calls and cancel one — the same calls the sheet and the chat's card show. Each call rings the visitor's app.
GraineAgent.schedulingRules
Read it to build your own booking screen: which times the agent accepts, and whether visitors may book at all.
The agent's rules from its settings (Calls & scheduling), read each time you ask. Before load() has the settings, booking is off and every number is its default.
| Field | Type | Meaning |
|---|---|---|
usersCanBook | boolean | Whether visitors may book calls at all; false until the settings load. |
minLeadMinutes | number | The least notice a booking needs, in minutes — 5 by default. |
maxDaysAhead | number | How far ahead a booking may be, in days — 14 by default. |
maxPendingPerUser | number | How many upcoming calls a visitor may have at once — 3 by default. |
ringTimeoutSeconds | number | How long a call Graine rings keeps ringing before it is missed, 20–60 seconds — 45 by default. |
callName | string | null | The name the agent's calls ring with, when the dashboard sets one. |
hostedRinging | boolean | Whether Graine rings your users' apps itself (the workspace uploaded its push credentials). |
platforms | Array<"ios" | "android"> | The phones Graine rings; empty means every one. |
callingWindow | { start, end, days } | null | New in loader 1.4.1. The agent's calling window — the hours Graine may ring a booked call: start and end as "HH:MM" (24-hour; start is offered, end is not, and a window never crosses midnight) on days (0 Monday … 6 Sunday), read on the visitor's clock in the browser's time zone. bookingSlots() and the widget's sheet offer only the times inside it. null when the agent has none — every time between earliest() and latest() is offered. |
earliest(now?) | (now?: Date) => Date | The soonest time a booking is accepted: now plus minLeadMinutes. now defaults to the current time. |
latest(now?) | (now?: Date) => Date | The latest time a booking is accepted: now plus maxDaysAhead days. |
Parameters — none.
Returns — an object as above. Example value: { usersCanBook: true, minLeadMinutes: 5, maxDaysAhead: 14, maxPendingPerUser: 3, ringTimeoutSeconds: 45, callName: "Acme", hostedRinging: true, platforms: [], callingWindow: { start: "09:00", end: "21:00", days: [0, 1, 2, 3, 4] }, earliest: ƒ, latest: ƒ }.
Errors — none.
GraineAgent.bookingSlots
Call it to fill a time picker of your own with the times the widget's booking sheet would offer on a day.
New in loader 1.4.0. The times on the day day falls on, in the browser's time zone: every 5 minutes from earliest(now) rounded up to the next 5 minutes to latest(now) rounded down, oldest first — the times the booking sheet offers, as on every SDK. New in loader 1.4.1: when the agent has a calling window (schedulingRules.callingWindow), only the times inside it — on its days, from its start up to, not including, its end, on the visitor's clock; a day it leaves out returns []. Empty for a day outside the agent's rules, and before load() has the agent's settings. Graine still checks the time, and the calls already waiting, when it is booked with scheduleCall().
| Parameter | Type | Default | Meaning |
|---|---|---|---|
day | Date | string | today | Any moment of the day, or the day as "YYYY-MM-DD" (that day in the browser's time zone). |
Returns — Date[]. Example value: [Date("2026-10-22T03:30:00Z"), Date("2026-10-22T03:35:00Z"), …].
Errors — none: a day it cannot read returns [].
GraineAgent.scheduleCall
Call it to book a call from your own booking screen.
Books a call from the agent that rings the identified visitor's app at at. The time is sent with the browser's time zone, in which the agent's calling hours are checked. reason is trimmed to 120 characters, kept with the call for the agent, and never put in the notification that rings it.
It waits for load() to have the agent's settings, then refuses on the page — before anything is sent — what the rules already settle, with the booking sheet's words — the same on every SDK: scheduling_off, “Booking a call isn't available right now”; too_soon, “Pick a time at least N minutes from now” (“1 minute” for one; more than 30 seconds before earliest(now)); too_far, “Pick a time within N days” (“1 day” for one). Graine then checks what only it knows: the calling hours, the calls already waiting, who the visitor is.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
at | Date | string | number | required | When the call should ring: a Date, an ISO-8601 time with its offset, or a timestamp in milliseconds. |
reason | string | none | What the call is about, at most 120 characters. |
Returns — Promise<GraineScheduledCall> — the booked call (GraineScheduledCall (website)), status scheduled. Example value: { id: "6f1c2a9e-7d1b-4c47-9a6e-2f0d8b1c5e44", at: Date("2026-10-16T12:30:00Z"), status: "scheduled", source: "app", reason: "Talk through my order", isUpcoming: true, canCancel: true }.
Errors — rejects with a GraineError. On the page: invalid_request (“at must be a Date, an ISO-8601 time or a timestamp.”) at once, then scheduling_off, too_soon, too_far as above. From Graine: outside_window, too_many_pending, identity_required, device_limit, rate_limited, network, unavailable. unknown (“The call was booked, but its details did not come back.”) when Graine booked it without describing it. identity_required on the page when the visitor who asked was replaced, or signed out, while the agent's settings loaded: a call is never booked for a visitor who did not ask for it. When load() failed, that failure's own code, at once.
GraineAgent.scheduledCalls
Call it to list the visitor's upcoming calls in your own interface.
The calls booked for the identified visitor (or, with nobody identified, this browser) that are still to come, in Graine's order — soonest first.
Parameters — none.
Returns — Promise<GraineScheduledCall[]>. Example value: [{ id: "6f1c2a9e-7d1b-4c47-9a6e-2f0d8b1c5e44", at: Date("2026-10-16T12:30:00Z"), status: "scheduled", source: "agent", reason: null, isUpcoming: true, canCancel: true }].
Errors — rejects with a GraineError: network, rate_limited, unavailable; when load() failed, that failure's own code — invalid_key, origin_refused, …
GraineAgent.cancelScheduledCall
Call it when the visitor calls off one of their booked calls.
Cancels a call booked for this visitor or browser; one booked for anyone else is not_found.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
id | string | required | The call's id, from scheduleCall(), scheduledCalls() or openBooking(). |
Returns — Promise<string> — the call's status afterwards, "cancelled". Example value: "cancelled".
Errors — rejects with a GraineError: invalid_request (“Pass the id of the call to cancel.”) for an empty id, not_found, network, rate_limited, unavailable.
GraineScheduledCall (website)
Read it to show a booked call: when it rings, where it is, and whether it can still be cancelled.
{ id, at, status, source, reason, isUpcoming, canCancel }
A plain object, the same fields as on every SDK.
What to expect — Returned by scheduleCall() (status scheduled), scheduledCalls() and openBooking(). at is a moment: show it in the visitor's time zone. A status or source newer than the loader arrives as Graine's own word.
| Field | Type | Meaning |
|---|---|---|
id | string | Use it to cancel the call — Graine's ID for it, a UUID. |
at | Date | null | When the call rings; null only when Graine's time could not be read. |
status | string | Where the call is: scheduled, ringing, answered, completed, declined (nothing rings that visitor again for 6 hours), missed, failed, cancelled, expired (its time passed while it could not ring) or noDevice (no phone of the visitor's could be rung). |
source | string | null | Who booked it: agent (in a conversation), app (your site or app), dashboard (your team) or api; null when Graine does not say. |
reason | string | null | What it is about, as it was booked — at most 120 characters — or null. |
isUpcoming | boolean | Use it to keep a call in an upcoming list: true while it is scheduled or ringing. |
canCancel | boolean | Use it to show a Cancel control: true while it is scheduled, before it rings. |
Workflows your site starts
Start one of your outreach workflows for the visitor your site signed in — a welcome call after sign-up, a follow-up after an order — with no server of your own (0.14.4). The workflow must have Your app can start this on, on its Connect tab (Start from your app). The run is always for the identified visitor, never for anyone the data names, and it never sends to an address your site gives: a visitor the agent knows by phone or email, and verified, is reached there.
GraineAgent.startWorkflow
Call it when something on your page should start a workflow for the identified visitor.
Waits for load() to have the agent's settings, then starts the workflow for the visitor identify() named. Nobody identified: nothing is sent. Someone else identified while the settings were loading (a sign-out, another visitor in the same browser): identity_required, and nothing is sent — a run is never started for a visitor who did not ask for it. The browser's install is one of the visitor's devices only within the agent's Devices per user.
| Parameter | Type | Default | Meaning |
|---|---|---|---|
workflow | string | required | The workflow's exact name, or its id (owf_…); at most 120 characters. |
data | object | none | The contact fields the workflow allows: text (at most 200 characters), numbers and yes/no; at most 12, the first 12 in the object's order. Anything else is left out, never refused — and never a phone number, an email address or another field a step sends to. |
options.idempotencyKey | string | none | 8 to 128 letters, digits, _ - . :. Two calls with the same key start one run. Without one, the SDK makes one for the call, and asks once more with it, a second later, when a request got no answer. |
Returns — a Promise of { runId, workflowId, alreadyRunning }: the run's id (oex_…), the workflow's id (owf_…, or null when Graine's answer did not say), and true when the visitor already had a run of this workflow under way — that run, never a second.
Errors — rejects with a GraineError. On the page: invalid_request (no workflow name, a key that isn't one), identity_required (nobody identified — the message names the trait). From Graine: not_allowed, not_verified, rate_limited (retryAfterSeconds), unavailable, invalid_request (the workflow needs a field your site may not send); network when no answer came twice; unknown when Graine started it but its run id did not come back. When load() failed, that failure's own code, at once.
Design
The widget draws the design the brand chose in the Garage — colours, typeface, corners, the launcher's shape and glyph, the chat window and the booking sheet — and follows the visitor's light or dark setting when the design says “auto”. Nothing to call. The only design inputs on the page are load()'s fallbacks — accent, position and launcherLabel, used where the dashboard sets nothing — and the panel's size (load({ chatSize }), open({ size })). For a design entirely your own, load the agent headless and draw everything yourself: Draw your own UI (headless).
Going live
- Allowed domains. Add every host the widget runs on — production, staging — to the agent's Allowed domains; a page whose host is missing gets no launcher and a console message.
- Content-Security-Policy. Allow
https://www.graine.aiinscript-src,connect-srcandframe-src, and do not deny the microphone to the widget's frame. - The console. The loader logs its problems as
[Graine] …in the browser console and never shows them to visitors: a missingagentIdor key, a refused key or origin, Graine not answering, a sign-out that could not be sent — andidentify()given traits without the one the agent identifies visitors by. - The version.
GraineAgent.versionsays which loader build the page runs; include it when you ask for support.
Events and listeners
GraineAgent.on(event, handler) tells your page what the visitor did in the widget that your page may want to know: "chat_rated", the rating a visitor gives a chat the agent ended — and, loaded headless, "state", "chat", "voice" and "component", each time what your page draws changes — see GraineAgent.on. The loader's other functions answer with promises, the agent reaches your page through the actions you define (defineAction), and everything the visitor sees is drawn inside the widget — or, headless, by your page.
Errors
A function that asks Graine on the visitor's behalf rejects with an Error whose name is "GraineError", carrying a code. Branch on the code; show the message, which is written for the visitor and never carries the identifier, traits or anything personal.
GraineError
Read it in a catch to decide what to do about a refused request.
Error & { name: "GraineError", code, message, status, retryAfterSeconds, reason }
What to expect — code is one of the codes below, or a newer one as Graine sent it. It is the route's own code when Graine sends one (trimmed); otherwise the HTTP status decides, as the table says — one rule on every Graine SDK — and a status the table does not name is unknown. A refusal made on the page before anything was sent has status 0. After a load() that failed, every request is refused at once with that load's own code, status and message — until the next load() (loader 1.5.0; before, they all read invalid_key).
| Field | Type | Meaning |
|---|---|---|
code | string | Branch on it: the reason in one stable word, such as too_soon or network. |
message | string | Show it: a sentence fit for the visitor. |
status | number | Use it in logs: the HTTP status Graine answered with, or 0 when nothing was sent or nothing came back. |
retryAfterSeconds | number | null | Use it to wait before trying again: how long Graine asked, with rate_limited; otherwise null. |
reason | string | null | New in loader 1.5.0. Graine's one word beside the code, when it gave one — which part of a server token failed (scope, user, agent, signature, …); otherwise null. |
| Code | HTTP | Means | Raised by | Fix |
|---|---|---|---|---|
invalid_key | 401 | The publishable key is not one, or belongs to no agent | Every request to Graine | Copy the key again from Agent → Embed & Widgets → Install |
origin_refused | 403 | The page's host is missing from the agent's Allowed domains | Every request | Add the exact host |
rate_limited | 429 | Too many requests from this browser, key or address | Every request | Wait retryAfterSeconds, then retry |
invalid_request | 400 (0 on the page) | A field is missing or malformed — no usable at, no call id, no session id; or chat.sessionTranscript() on a page not loaded headless | scheduleCall, cancelScheduledCall, chat.sessionTranscript | Fix the call |
identity_required | 400 (0 on the page) | Nobody is identified, or the identifier is a placeholder; on the page the message names the trait the agent identifies visitors by — or, for a request made before the agent's settings arrived, someone else was identified while they loaded | memories, forgetMemory, bookings that need a visitor, past sessions (state().chat.pastSessions.error, chat.sessionTranscript) | identify() with that trait first — memorySettings.identityField |
identity_unverified | 403 | New in SDK 0.14.4. The agent has Require verified users on and the visitor is not verified: no identity token, or one that did not prove them | memories, forgetMemory, bookings that need a visitor, past sessions | Pass identityToken to identify(); with identityTokenRefresher set, the loader fetches a fresh token and sends the request once more before refusing. verification.userReason says why |
device_limit | 403 | This browser is not one of the visitor's allowed devices | memories, forgetMemory, newConversation, scheduleCall, past sessions | Sign out on another device, raise Devices per user, or Reset devices for the visitor |
scheduling_off | 403 (0 on the page) | Visitors may not book calls from this agent | scheduleCall | Turn it on in Calls & scheduling, or hide booking when bookingAvailable is false |
too_soon | 400 (0 on the page) | Earlier than earliest(now) | scheduleCall | Offer times from earliest(now) |
too_far | 400 (0 on the page) | Later than latest(now) | scheduleCall | Offer times up to latest(now) |
outside_window | 400 | Outside the agent's calling hours, in the visitor's time zone | scheduleCall | Show the message (it names a time that works); offer another time |
too_many_pending | 409 | The visitor already has the most calls waiting | scheduleCall | Cancel one first |
not_allowed | 403 | No such workflow, Your app can start this is off for it, or it isn't published | startWorkflow | Check the workflow's exact name or id; an Admin turns on Your app can start this |
not_verified | 403 | This device isn't one of the visitor's signed-in devices, or the agent requires a verified visitor | startWorkflow | Sign the visitor in on this device, raise Devices per user, or verify the visitor |
not_found | 404 | No such booking for this visitor or browser; no such session, or another visitor's | cancelScheduledCall, chat.sessionTranscript | Read scheduledCalls(), or the past sessions, again |
unavailable | 502, 503, 504, 520–524 (a gateway or the CDN in front of Graine that could not reach it, or gave up waiting) | Graine could not answer just now — including a booking refused because the agent is switched off or out of credit; also a request left waiting when the agent was taken off the page | Every request | Retry with backoff; check the agent is on and the workspace has credit |
token_required | 401 | Loader 1.5.0. Server tokens are enforced and none came — the loader already asked your tokenProvider again and tried once more | Every request, load() | Give load() a tokenProvider — see Server tokens and the bot check |
token_invalid | 401 | Loader 1.5.0. The token could not be checked (reason says why); already asked for again and tried once more | Every request, load() | Mint it with POST /v2/client-tokens as it comes |
token_expired | 401 | Loader 1.5.0. The token expired, and a fresh one did not come in time | Every request, load() | Make sure tokenProvider answers within 15 seconds |
token_scope | 403 | Loader 1.5.0. Another agent's or visitor's token, or one without the scope this needs (reason). Final | Every request | Mint it for this agent, for the visitor's user_id, with the scopes the page uses |
key_revoked | 401 | Loader 1.5.0. The publishable key was revoked. Final | Every request, load() | Load the agent with its new key |
network | 0 | No answer came back: offline, or the connection dropped — or the agent's settings did not arrive within 30 seconds of load() | Every request | Retry when online |
unknown | any other (a bare 500 among them) | An answer nobody expected — a status the rows above do not name — or one that could not be read. A code newer than the loader is not this: it arrives as its own word | Every request | Log the code and message; show the message |
app_not_allowed and app_not_verified (SDK 0.14.4) belong to the iOS and Android SDKs, which prove which app is calling; a website never receives them — Graine checks a browser's page against the agent's Allowed domains instead.
Rate limits and quotas
| Limit | Value | Where it applies |
|---|---|---|
| Bookings from one install | 10 an hour | scheduleCall, the booking sheet, and the agent's bookings in that install's conversations |
| Bookings in a workspace | 1,000 an hour | All in-app bookings |
| Calls waiting per visitor | 3 by default (1–10) | At most this many upcoming calls per user |
| Devices per visitor | 2 by default (1–10) | Devices per user; idle devices free their place after 30 days |
| Notice and horizon | 5 minutes (2–1440) · 14 days (1–30) | With at least this much notice · Booked at most this far ahead |
| Booking reason · variables | 120 characters · 12 variables, about 1 KB | Bookings and conversations |
| Memories listed | At most 100, newest first | memories() |
| Conversation kept | 50 messages, 7 days after the last | Conversations that continue |
| Requests per key and address, per minute | Starting a conversation 30 (and 300 per key); booking, listing, cancelling, memory list and sign-out 30 (300 per key); forgetting memory 10 (120 per key); listing memories also 30 per install | Answered rate_limited with Retry-After |
| Action handlers · component data | 6 seconds · 8 seconds | After that, the agent is told the action did not finish; a component shows its authored content |
What's new
- Verified users (loader 1.5.0, SDK 0.14.4).
GraineAgent.identify(traits, { identityToken })proves who the visitor is with an HMAC your server computes or your sign-in's ID token (JWT); it goes only inside the identity Graine checks, only with the value it was given for, and is dropped when another visitor signs in.setIdentityToken()replaces it without a sign-out;identityTokenRefresher(also aload()option) fetches a fresh one when Graine needs it.verificationandonVerificationChange()say whether the visitor is verified, and why not. New error codeidentity_unverifiedwhere an agent requires verified users. - A failed
load()says why (loader 1.5.0, SDK 0.14.4). Whenload()cannot start the agent, what your page asks meanwhile and afterwards —memories(),forgetMemory(), bookings, past sessions — is refused at once with the session's own reason (invalid_key,origin_refused,rate_limited,unavailable, ornetworkwhen Graine did not answer within 30 seconds), notinvalid_keyuntil the page reloaded, and the nextload()starts afresh. A 502, 504 or 520–524 isunavailable, a code Graine sent is kept trimmed, and a blank one is no code.identity_requirednames the trait the agent identifies visitors by, and the console says so once whenidentify()is given traits without it. NewGraineAgent.memorySettings: that trait, and whether the agent remembers visitors at all. - Server tokens and the bot check (loader 1.5.0, SDK 0.14.4).
load({ tokenProvider })andGraineAgent.setTokenProvider(): every request carries a short-lived token your server minted for the signed-in visitor, refreshed before it expires; new codestoken_required,token_invalid,token_expired,token_scope,key_revokedandbot_check_failed, withreasonon the error. When the agent's bot check is on, the loader passes Cloudflare Turnstile or reCAPTCHA Enterprise invisibly before a conversation starts — nothing to add to your page. See Server tokens and the bot check. - A failed
load()says why (loader 1.5.0, SDK 0.14.4). Whenload()cannot start the agent, what your page asks meanwhile and afterwards —memories(),forgetMemory(), bookings, past sessions — is refused at once with the session's own reason (invalid_key,origin_refused,rate_limited,unavailable, ornetworkwhen Graine did not answer within 30 seconds), notinvalid_keyuntil the page reloaded, and the nextload()starts afresh. A 502 or 504 isunavailable.identity_requirednames the trait the agent identifies visitors by, and the console says so once whenidentify()is given traits without it. NewGraineAgent.memorySettings: that trait, and whether the agent remembers visitors at all. - Past sessions (loader 1.4.2, SDK 0.14.3). Loaded headless,
state().chat.pastSessionslists the identified visitor's earlier sessions with the agent — chats, voice conversations and calls, newest first, as Execution History lists them — filled byGraineAgent.chat.refreshPastSessions()and paged byloadMorePastSessions();GraineAgent.chat.sessionTranscript(id)resolves one session's whole conversation. Emptied when another visitor signs in. See GraineAgent.chat. - A chat closes when its window does (loader 1.4.2, SDK 0.14.3). Once no window shows the chat — the panel closed, or, headless,
chat.shown(false)— its conversation closes 15 seconds later, unless it is shown again or a message goes either way first;load({ chatCloseDelaySeconds })(orchat-close-delay-secondsongraine-agent) sets how long, from 0 to 300. Shown again, it connects again and an identified visitor's conversation continues. It was 5 idle minutes in 1.4.0–1.4.1. The widget's chat now connects when the panel is first opened, not as the page loads. - Draw your own UI — headless (loader 1.4.0, SDK 0.14.0).
GraineAgent.load({ …, headless: true })shows no widget: your page draws the chat, the voice conversation and the agent's components in its own design fromGraineAgent.state()and the"state","chat","voice"and"component"events, and drives them withGraineAgent.chat(send,sendQuickReply,rate,newConversation,shown),GraineAgent.voice(start,stop,setMuted) andGraineAgent.component(submit,dismiss) — the same values and meanings as every app SDK. The frame keeps the connection, the microphone and the audio, and reports to your page only. See Draw your own UI (headless). - Chat sessions (SDK 0.14.0).
state().chat.sessionIdis the chat's current session — the id Execution Logs shows for it — every turn carries thesessionit was said in, andstate().chat.sessionslists the thread's sessions, oldest first, for a "past conversations" list or session dividers of your own. Until Graine names sessions on your agent's connection,sessionIdisnulland the thread is one session with no id. - A web component (1.4.0).
<graine-agent agent-id="…" publishable-key="…" headless>— the same agent declared in markup, withGraineAgent's API on the element and each change as a DOM event (graine-state,graine-chat,graine-voice,graine-component). See The web component. - Booking inside the calling window (loader 1.4.1, SDK 0.14.1).
GraineAgent.schedulingRules.callingWindowis the agent's calling window ({ start, end, days }, ornull), andGraineAgent.bookingSlots(day)and the widget's booking sheet offer only the times inside it, read on the visitor's clock — so a time a visitor picks is one Graine can ring. - Booking screens of your own (1.4.0).
GraineAgent.bookingSlots(day)returns the times the booking sheet would offer on a day;GraineAgent.bookingUnavailableReasonsays why booking is not offered (not_loaded,scheduling_off,not_identified). - Variables while the page is open (1.3.0).
GraineAgent.setVariables(values)sets prompt variables the way every app SDK does — merged,nullunder a name removes it,nullfor the whole object clears them all — andGraineAgent.currentVariables()returns the set the next conversation carries. - Chat styles. The widget's chat draws the chat style chosen in the Garage — its header, bubbles, wallpaper, the replies the agent suggests as buttons, the typing indicator, the composer and a rating at the end of a chat — with nothing to change on your page.
- A card for what the chat is about.
GraineAgent.pin({ title, subtitle, imageUrl, badge })shows it at the top of the chat;GraineAgent.pin(null)takes it away. - Ratings, to your page.
GraineAgent.on("chat_rated", handler)hears the rating a visitor gives a chat the agent ended. - Book a call from your website.
GraineAgent.openBooking({ reason })opens the widget's booking sheet — the day, the time, the visitor's time zone, What's it about? (optional), Book call — in the agent's design, and resolves with the call booked there, ornullwhen the visitor closed it. At the booked time, Graine rings the visitor in your app. GraineAgent.bookingAvailable: the agent lets visitors book and the visitor is identified. Show your own “Call me” button only then.- Booked calls in the widget's chat. The chat shows the visitor's upcoming calls with Cancel, and Book a call where booking is available.
- The full list of changes is in the Changelog.
Every symbol, A to Z
Every public symbol of the Website SDK — 56 in all — by name, each linked to where this page documents it: a type or function first, then its members.
GraineAgent—addMaskRule·bookingAvailable·bookingSlots·bookingUnavailableReason·cancelScheduledCall·chat·close·component·currentVariables·defineAction·destroy·forgetMemory·getInstallId·identify·identityTokenRefresher·installId·load·memories·memorySettings·newConversation·on·onVerificationChange·open·openBooking·pin·removeAction·reportEvent·scheduleCall·scheduledCalls·schedulingRules·setIdentityToken·setMemory·setScreen·setTokenProvider·setVariables·startWorkflow·state·switchesAgents·verification·version·voiceGraineAgent.load—accent·agentId·chatCloseDelaySeconds·chatSize·headless·identityTokenRefresher·launcherLabel·mode·position·preload·publishableKey·start·tokenProvider·variables

