Graine AI

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

Loaderhttps://www.graine.ai/embed/v1.js — always the current v1, nothing to upgrade; plain JavaScript, no build step, no dependencies
RequiresThe 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.
MicrophoneThe 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.
StorageThe 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)

<script async src="https://www.graine.ai/embed/v1.js"
  data-agent-id="your-website-agent-id"
  data-publishable-key="pk_live_…"></script>

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>

<script src="https://www.graine.ai/embed/v1.js"></script>
<script>
  GraineAgent.load({
    agentId: "your-website-agent-id",      // Agent → Embed & Widgets → Install fills these in
    publishableKey: "pk_live_…",
  });
</script>

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.

load(options)

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:

OptionTypeDefaultMeaning
agentIdstringrequiredWhich agent to show: the website agent's ID from Agent → Embed & Widgets → Install.
publishableKeystringrequiredThe agent's publishable key (pk_live_…), from the same place. It identifies the agent and is safe in page source.
variablesobjectnonePrompt 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'sWhich 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'sNew in loader 1.6.0. Which one opens first where both are offered, over the agent's Opens on.
preloadbooleanfalseNew 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'sHow big the panel opens on this page, over the agent's Window size in the Garage. open({ size }) overrides it for one open.
accentstring (#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.
launcherLabelstring"Chat with us", or "Talk to us" for a voice-only agentWhat a screen reader announces for the launcher (and the words on a pill-shaped launcher) when the dashboard does not say.
chatCloseDelaySecondsnumber15New 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.
tokenProviderfunctionnoneNew 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.
headlessbooleanfalseNew 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>noneNew 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.
ParameterTypeDefaultMeaning
optionsobjectrequiredThe 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.

const ok = await GraineAgent.load({ agentId: "your-website-agent-id", publishableKey: "pk_live_…", chatSize: "large" });
if (!ok) console.warn("The agent is not on this page — see the console.");

GraineAgent.destroy

Call it when the agent should leave the page — a route without it, or a sign-out screen.

destroy()

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.destroy();

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.

PropertyTypeMeaning
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.
switchesAgentstrueRead it to know that load() with another agent switches agents in place; a loader without it needs a page reload to change agent.
installIdstringRead it for this browser's install ID — the same value getInstallId() returns.
schedulingRulesobjectRead it to know what the agent lets visitors book; see GraineAgent.schedulingRules.
bookingAvailablebooleanRead it to decide whether to offer your own “Call me” button; see GraineAgent.bookingAvailable.
bookingUnavailableReasonstring | nullRead it to say why booking is not offered; see GraineAgent.bookingUnavailableReason.
memorySettingsobject | nullNew 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.
verificationobjectNew in SDK 0.14.4. Read it for what Graine made of the visitor — verified, unverified or invalid, and why; see GraineAgent.verification.
identityTokenRefresherfunction | nullNew 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.

GraineAgent.load({
  agentId: "your-website-agent-id",
  publishableKey: "pk_live_…",
  tokenProvider: function () {
    // Your own server: it knows the signed-in visitor from its session, and mints the token for them.
    return fetch("/graine-token", { credentials: "include" })
      .then(function (r) { return r.ok ? r.json() : null; })
      .then(function (d) { return d ? d.token : null; });
  },
});
  • 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); when identify() 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 as null.
  • 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_scope and key_revoked are final: the request rejects with the code and its reason, and a conversation that cannot start says so rather than connecting another way.
  • The loader reads only the token's iat and exp, keeps none in storage, and logs none. Without tokenProvider, 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.

CodeHTTPWhat it means
token_required401The agent requires a server token and none came with the request: give load() a tokenProvider
token_invalid401The token could not be checked — reason: malformed, signature, unknown_key, issuer or not_yet_valid
token_expired401The token expired, and a fresh one did not come in time
token_scope403The token is another agent's (agent) or another visitor's (user), or lacks the scope this needs (scope). Final
key_revoked401This publishable key was revoked: load the agent with its new key. Final
bot_check_failed403 or 503The 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.

setTokenProvider(fn)
ParameterTypeDefaultMeaning
fnfunction | nullrequiredA 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.

GraineAgent.setTokenProvider(function () {
  return fetch("/graine-token", { credentials: "include" }).then(function (r) { return r.ok ? r.json() : null; }).then(function (d) { return d ? d.token : null; });
});

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.

identify(traits, options)

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.

ParameterTypeDefaultMeaning
traitsobject | nullrequiredWho 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.

// On your server, never in the page: the identity secret stays there.
import { createHmac } from "node:crypto";
const identityToken = createHmac("sha256", process.env.GRAINE_IDENTITY_SECRET).update(user.id).digest("hex");
 
// In the page, with the token your server sent along:
GraineAgent.identify({ user_id: user.id, name: user.firstName }, { identityToken });

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.

GraineAgent.identify({ user_id: user.id, name: user.firstName }, { memory: user.allowsMemory });
GraineAgent.identify(null);                              // on sign-out: every agent on the page

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.

setIdentityToken(token)

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.

ParameterTypeDefaultMeaning
tokenstring | nullrequiredThe 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.

auth.onTokenRefreshed((idToken) => GraineAgent.setIdentityToken(idToken));

GraineAgent.identityTokenRefresher

Set it once, so the loader can fetch a fresh identity token when Graine needs one.

GraineAgent.identityTokenRefresher = async () => fetchIdentityTokenFromYourServer();   // or load({ identityTokenRefresher })

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.load({
  agentId: "your-website-agent-id",
  publishableKey: "pk_live_…",
  identityTokenRefresher: async () => (await fetch("/account/graine-token", { credentials: "include" })).text(),
});

GraineAgent.verification

Read it to show whether the visitor is verified, or why not.

GraineAgent.verification   // { app, appReason, user, userReason }, read-only

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().

FieldTypeMeaning
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".
userReasonstring | nullWhy, 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.
appReasonnullAlways null on a website.

Errors — none.

if (GraineAgent.verification.user === "invalid") console.warn("Graine could not verify this visitor:", GraineAgent.verification.userReason);

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.

onVerificationChange(handler)

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.

ParameterTypeDefaultMeaning
handler(verification) => voidrequiredCalled 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.

const stop = GraineAgent.onVerificationChange((v) => {
  badge.hidden = v.user !== "verified";
});

GraineAgent.setMemory

Call it when the visitor changes their memory choice in your privacy settings.

setMemory(enabled)

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.

ParameterTypeDefaultMeaning
enabledbooleanrequiredtrue to remember this visitor's conversations, false to stop.

Returns — nothing.

Errors — none.

GraineAgent.setMemory(false);

GraineAgent.getInstallId

Call it when you need this browser's install ID — to show in a support screen, for example.

getInstallId()

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.

const id = GraineAgent.getInstallId();

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.

GraineAgent.memorySettings   // { identityField, memoryEnabled } | null, read-only

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.

FieldTypeMeaning
identityFieldstringThe trait that identifies a visitor for this agent: user_id, email, phone or the custom trait you chose.
memoryEnabledboolean | nullfalse 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.

const settings = GraineAgent.memorySettings;
if (settings && settings.memoryEnabled === false) {
  showNotice("This assistant does not remember conversations.");
} else {
  render(await GraineAgent.memories());
}

GraineAgent.memories

Call it to show the visitor what the agent remembers about them, on a privacy screen.

memories()

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.

try {
  const list = await GraineAgent.memories();
  render(list.map((m) => m.text));
} catch (e) {
  if (e.code === "identity_required") showSignIn();
}

GraineAgent.forgetMemory

Call it when the visitor asks the agent to forget them.

forgetMemory()

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.

const deleted = await GraineAgent.forgetMemory();

GraineAgent.newConversation

Call it to give the visitor a fresh conversation instead of continuing the last one.

newConversation()

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.

await GraineAgent.newConversation();

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.

open(options)

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.

ParameterTypeDefaultMeaning
options{ mode?: "chat" | "call", size?: "compact" | "large" | "full" }nonemode 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.open({ mode: "chat", size: "full" });

GraineAgent.close

Call it to close the panel from your own code — after a task is done, for example.

close()

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.close();

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.

pin(card)

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().

ParameterTypeDefaultMeaning
card{ title: string, subtitle?: string, imageUrl?: string, badge?: string } | nullrequiredtitle 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.pin({ title: "Getting started", subtitle: "Step 2 of 4", badge: "In progress" });
GraineAgent.pin(null);

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.

on(event, handler)
EventThe handler receivesWhen
"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 5The 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() returnsNew 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().chatNew in loader 1.4.0. Loaded headless: the chat changed.
"voice"state().voiceNew 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 nullNew in loader 1.4.0. Loaded headless: a component arrived, started loading, or went (answered, closed, replaced, the call over).
ParameterTypeDefaultMeaning
eventstringrequiredThe event's name, from the table above.
handlerfunctionrequiredCalled 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.

const stop = GraineAgent.on("chat_rated", (rating) => {
  console.log(rating);   // { value: 4, scale: 5, style: "stars" }
});

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.

  1. Load it headless, on every page the agent belongs on, as usual.
  2. Draw from the state. Read GraineAgent.state() once, then redraw on GraineAgent.on("state", …) — or on the finer "chat", "voice" and "component".
  3. Wire your controls to chat.send(), chat.sendQuickReply(), chat.rate(), voice.start(), voice.stop(), voice.setMuted(), component.submit() and component.dismiss(). They are safe right after load(): what you ask before the agent is on the page waits for it.
  4. Say when your chat is on screen with open() and close() — or chat.shown(true) and chat.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 — and status rests 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.
  5. Show the visitor's past sessions (new in loader 1.4.2), as your dashboard's Execution History lists them: chat.refreshPastSessions() fills state().chat.pastSessions, chat.loadMorePastSessions() adds the next page, and chat.sessionTranscript(id) resolves one session's whole conversation — see GraineAgent.chat.
<script src="https://www.graine.ai/embed/v1.js"></script>
<script>
  GraineAgent.load({ agentId: "your-website-agent-id", publishableKey: "pk_live_…", headless: true });
 
  GraineAgent.on("chat", (chat) => {
    renderTurns(chat.turns, chat.newConversationBefore);       // your bubbles, your day lines
    renderSessions(chat.sessions);                             // "past conversations", by session id
    renderStatus(chat.status);                                 // "connected", "reconnecting", …
    renderSuggestions(chat.quickReplies);                      // chips: sendQuickReply(reply) on tap
    showTyping(chat.typing);
  });
  GraineAgent.on("voice", (voice) => {
    talkButton.textContent = voice.status === "idle" || voice.status === "ended" ? "Talk" : "End";
    meter.style.transform = `scaleY(${0.2 + voice.agentLevel * 0.8})`;
    caption.textContent = voice.captions.length ? voice.captions[voice.captions.length - 1].text : "";
  });
  GraineAgent.on("component", (c) => (c ? renderComponent(c) : clearComponent()));
 
  chatButton.onclick = () => GraineAgent.open();               // your chat panel is on screen
  closeButton.onclick = () => GraineAgent.close();
  form.onsubmit = (e) => { e.preventDefault(); GraineAgent.chat.send(input.value); input.value = ""; };
  talkButton.onclick = () => {                                 // the visitor's tap: the browser asks for the microphone now
    const s = GraineAgent.state().voice.status;
    if (s === "idle" || s === "ended" || s === "failed") GraineAgent.voice.start();
    else GraineAgent.voice.stop();
  };
</script>

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, voice and component then do nothing (the console says so) and state() 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.

state()

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.

chatTypeMeaning
statusstringWhere 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).
turnsArray<object>The messages, oldest first — the turn fields below. A conversation that continues starts with its earlier messages (restored).
sessionIdstring | nullNew 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.
sessionsArray<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.
typingbooleanThe agent is working on a reply: draw a typing indicator.
quickRepliesArray<{ 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.
endedbooleanThe 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 } | nullThe visitor's answer, once given — at most one per conversation.
newConversationBeforeArray<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.
errorstring | nullWhy 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 sessionTypeMeaning
idstringThe session's id — the one Execution History shows. Pass it to chat.sessionTranscript(id).
startedAtDateWhen it began.
endedAtDate | nullWhen it ended; null when Graine did not say.
durationSecondsnumber | nullHow 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" | nullOn a call, who called whom: the visitor (inbound) or Graine (outbound); null when it does not apply.
statusstringHow it ended, in plain words — completed, missed, failed, … — or a newer word, as Graine sent it; "" when it said none.
turnsnumberHow many turns it holds.
previewstringThe visitor's first line, at most 120 characters; "" when there is none.
A turnTypeMeaning
idstringUse 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.
textstringThe words, growing while live. The agent's may carry light markdown — bold, italic, links, lists.
atDate | nullWhen it was said.
livebooleanThe agent's words are still arriving.
restoredbooleanFrom 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.
proactivebooleanThe agent spoke unasked.
sessionstring | nullNew 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 sessionTypeMeaning
idstring | nullThe session's id; null for the messages kept from before sessions were recorded, which make one session together.
startedAtDate | nullWhen its first message was said.
endedAtDate | nullWhen 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.
turnsnumberHow many messages it holds.
currentbooleanIt is the chat's current session (sessionId).
voiceTypeMeaning
statusstringWhere 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.
captionsArray<{ 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.
agentLevelnumberThe agent's voice, 0–1, about five times a second while the call is live; 0 otherwise.
micLevelnumberThe visitor's microphone, 0–1, likewise; 0 while muted.
mutedbooleanThe microphone is muted (voice.setMuted).
transport"websocket" | "webrtc" | nullWhat the call runs on, once one has been placed; null before.
transportFallbackReasonstring | nullWhy a call that asked for WebRTC runs on the WebSocket; null when it did not fall back.
errorstring | nullWhy 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.
componentTypeMeaning
idstringPass it to component.submit or component.dismiss.
kindstringWhich component, such as product_list, plan_comparison, quick_actions, calendar_slots, info_card or lead_form — or a newer kind, as Graine sent it.
dataobject | nullWhat to draw, as the agent's component configured it; null while it loads.
fallbackTextstringThe words to show where you do not draw this kind.
pendingbooleanThe 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.

const { chat, voice, component } = GraineAgent.state();
if (chat.status === "failed") showNotice(chat.error);

GraineAgent.chat

Call these from your own chat's controls, on a page loaded headless.

chat.send(text) · chat.sendQuickReply(reply) · chat.rate(style, value) · chat.newConversation() · chat.shown(visible)
chat.refreshPastSessions() · chat.loadMorePastSessions() · chat.sessionTranscript(id)

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.

FunctionParametersWhat 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 textSends 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–5Answers "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()noneThe same as GraineAgent.newConversation(): Graine lets go of the conversation it kept and the chat starts over. Returns its promise.
shown(visible)visible: booleanSays 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()noneNew 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()noneNew 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 idNew 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.

GraineAgent.chat.shown(true);                 // your chat panel opened
GraineAgent.chat.send("Where is my order?");
GraineAgent.chat.sendQuickReply(GraineAgent.state().chat.quickReplies[0]);
GraineAgent.chat.rate("stars", 5);

Past sessions, on a history screen of your own:

GraineAgent.on("chat", ({ pastSessions }) => {
  renderHistory(pastSessions.sessions.map((s) => ({ id: s.id, when: s.startedAt, line: s.preview || s.channel, status: s.status })));
  moreButton.hidden = !pastSessions.hasMore;
  spinner.hidden = !pastSessions.loading;
  if (pastSessions.error === "identity_required") showSignIn();
});
historyTab.onclick = () => GraineAgent.chat.refreshPastSessions();
moreButton.onclick = () => GraineAgent.chat.loadMorePastSessions();
async function openSession(id) {
  try {
    const t = await GraineAgent.chat.sessionTranscript(id);
    renderTranscript(t.turns);                 // [{ role: "customer" | "agent", text, at }], oldest first
  } catch (e) {
    if (e.code === "not_found") refreshHistory();
  }
}

GraineAgent.voice

Call these from your own voice bar's buttons, on a page loaded headless.

voice.start() · voice.stop() · voice.setMuted(muted)

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.

FunctionParametersWhat it does
start()noneStarts a voice conversation: status goes connecting, then listening. Not with load({ mode: "chat" }), which offers no voice — the console says so.
stop()noneEnds it: status goes ended — or back to idle for a call that had not connected yet.
setMuted(muted)muted: booleanMutes 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.

talkButton.onclick = () => GraineAgent.voice.start();
muteButton.onclick = () => GraineAgent.voice.setMuted(!GraineAgent.state().voice.muted);

GraineAgent.component

Call these from your own rendering of the component the agent drew (state().component), on a page loaded headless.

component.submit(id, data, summary) · component.dismiss(id)

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.

FunctionParametersWhat 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 idCloses it unanswered. The agent is told quietly, so it does not go on about options nobody can see.

Returns — nothing.

Errors — none.

GraineAgent.on("component", (c) => {
  if (!c || c.pending) return;
  renderPlans(c.data, (plan) => GraineAgent.component.submit(c.id, { plan: plan.id }, `The ${plan.name}, please`),
    () => GraineAgent.component.dismiss(c.id));
});

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.

<script src="https://www.graine.ai/embed/v1.js"></script>
<graine-agent agent-id="your-website-agent-id" publishable-key="pk_live_…" headless></graine-agent>
<script>
  const agent = document.querySelector("graine-agent");
  agent.addEventListener("graine-chat", (e) => renderTurns(e.detail.turns));
  agent.addEventListener("graine-voice", (e) => renderVoice(e.detail));
  sendButton.onclick = () => agent.chat.send(input.value);
</script>

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().

Attributeload() optionMeaning
agent-idagentIdRequired, with publishable-key; nothing loads until both are there.
publishable-keypublishableKeyThe agent's publishable key.
headlessheadlessPresent: no widget — draw your own UI (Draw your own UI (headless)).
modemodeboth, voice or chat.
chat-sizechatSizecompact, large or full.
accent · position · launcher-labelaccent · position · launcherLabelThe launcher's fallbacks.
chat-close-delay-secondschatCloseDelaySecondsNew 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().

MemberWhat it is
state() · on(event, handler)GraineAgent.state() and GraineAgent.on() — see GraineAgent.state and GraineAgent.on.
chat · voice · componentGraineAgent.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().
agentGraineAgent itself, for everything else: identify, setVariables, setScreen, defineAction, scheduleCall, …
readyload()'s promise: true once the agent is on the page.
DOM event on the elementevent.detailWhen
graine-ready{ ok }The element's load() finished: ok is what it resolved.
graine-state · graine-chat · graine-voice · graine-componentWhat the "state", "chat", "voice" and "component" events carryHeadless: 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.

router.on("/help", () => GraineAgent.load({ agentId: "support-agent-id", publishableKey: "pk_live_support…" }));
router.on("/plans", () => GraineAgent.load({ agentId: "plans-agent-id", publishableKey: "pk_live_plans…" }));

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.

setScreen(context)

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.

ParameterTypeDefaultMeaning
contextobject | nullrequiredWhat the visitor can see now, as above.

Returns — nothing.

Errors — none.

GraineAgent.setScreen({
  screen: "checkout_address", title: "Delivery address",
  journey: { name: "Checkout", step: 2, of: 3, next: "Payment" },
  fields: [{ name: "postal_code", label: "Postal code", value: postalCode, status: "invalid", error: "We don't deliver there yet" }],
});

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.

setVariables(values)

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.

ParameterTypeDefaultMeaning
valuesobject | nullrequiredPrompt 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.setVariables({ name_user: user.firstName, plan: "Gold", cart_items: 3 });
GraineAgent.setVariables({ cart_items: null });   // removes one
GraineAgent.setVariables(null);                   // on sign-out: every one set this way

GraineAgent.currentVariables

Call it to check exactly which variables the next conversation will carry.

currentVariables()

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.

console.log(GraineAgent.currentVariables());

GraineAgent.defineAction

Call it to let the agent do one thing on your page — open a section, apply a filter, fill a form.

defineAction(name, handler)

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().

ParameterTypeDefaultMeaning
namestringrequiredThe action's name, exactly as it is declared on the agent.
handler(args) => result | Promise<result>requiredRuns 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.defineAction("scroll_to_section", ({ section }) => {
  const el = document.getElementById(section);
  if (!el) return { status: "refused", message: "That section is not on this page." };
  el.scrollIntoView({ behavior: "smooth" });
  return { status: "ok", message: `Scrolled to ${section}.` };
});

GraineAgent.removeAction

Call it when an action stops making sense — a section unmounting, for example.

removeAction(name)

The agent stops being offered the action; a request for it afterwards is refused.

ParameterTypeDefaultMeaning
namestringrequiredThe action's name, as it was defined.

Returns — nothing.

Errors — none.

GraineAgent.removeAction("scroll_to_section");

GraineAgent.addMaskRule

Call it once at start-up to mask a value shape only your site knows — an account number, say.

addMaskRule(pattern, token)

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.

ParameterTypeDefaultMeaning
patternRegExprequiredWhat to mask.
tokenstring"[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.addMaskRule(new RegExp("ACC-[0-9]+", "g"), "[ACCOUNT]");

GraineAgent.reportEvent

Call it when something happens that the agent may want to speak up about — a payment failing, a form being rejected.

reportEvent(event)

The event reaches the conversation that is live in the widget. With no agent on the page it is dropped, not kept.

ParameterTypeDefaultMeaning
event{ name: string, detail?: string }requiredWhat happened, in a word (name), and a sentence about it (detail) for the agent.

Returns — nothing.

Errors — none.

GraineAgent.reportEvent({ name: "payment_failed", detail: "The card was declined." });

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:

CodeThe line
too_soonPick a time at least N minutes from now
too_farPick a time within N days
outside_windowThat time is outside the hours we can call — pick another
too_many_pendingYou already have N calls booked — cancel one first
scheduling_offBooking a call isn't available right now
identity_requiredSign in to book a call
anything elseCouldn'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.

GraineAgent.bookingAvailable   // boolean, read-only

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.

callMeButton.hidden = !GraineAgent.bookingAvailable;

GraineAgent.bookingUnavailableReason

Read it to tell the visitor why your “Call me” button is not there — or to sign them in first.

GraineAgent.bookingUnavailableReason   // string | null, read-only

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.

if (GraineAgent.bookingUnavailableReason === "not_identified") showSignInToBook();

GraineAgent.openBooking

Call it from your own “Call me” button to let the visitor book a call in the widget's sheet.

openBooking(options)

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().

ParameterTypeDefaultMeaning
options{ reason?: string }nonereason 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.

if (GraineAgent.bookingAvailable) {
  const call = await GraineAgent.openBooking({ reason: "Talk through my order" });
  if (call) showToast("We'll call you then.");
}

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.

GraineAgent.schedulingRules   // object, read-only

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.

FieldTypeMeaning
usersCanBookbooleanWhether visitors may book calls at all; false until the settings load.
minLeadMinutesnumberThe least notice a booking needs, in minutes — 5 by default.
maxDaysAheadnumberHow far ahead a booking may be, in days — 14 by default.
maxPendingPerUsernumberHow many upcoming calls a visitor may have at once — 3 by default.
ringTimeoutSecondsnumberHow long a call Graine rings keeps ringing before it is missed, 20–60 seconds — 45 by default.
callNamestring | nullThe name the agent's calls ring with, when the dashboard sets one.
hostedRingingbooleanWhether Graine rings your users' apps itself (the workspace uploaded its push credentials).
platformsArray<"ios" | "android">The phones Graine rings; empty means every one.
callingWindow{ start, end, days } | nullNew 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) => DateThe soonest time a booking is accepted: now plus minLeadMinutes. now defaults to the current time.
latest(now?)(now?: Date) => DateThe 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.

const rules = GraineAgent.schedulingRules;
const first = rules.earliest();   // the soonest a booking is accepted
const last = rules.latest();      // the latest
if (!rules.usersCanBook) hideBooking();

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.

bookingSlots(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().

ParameterTypeDefaultMeaning
dayDate | stringtodayAny 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 [].

const times = GraineAgent.bookingSlots(new Date(Date.now() + 86400000));   // tomorrow
picker.options = times.map((t) => ({ value: t.toISOString(), label: t.toLocaleTimeString() }));

GraineAgent.scheduleCall

Call it to book a call from your own booking screen.

scheduleCall(at, reason) · scheduleCall({ at, reason })

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.

ParameterTypeDefaultMeaning
atDate | string | numberrequiredWhen the call should ring: a Date, an ISO-8601 time with its offset, or a timestamp in milliseconds.
reasonstringnoneWhat 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.

try {
  const call = await GraineAgent.scheduleCall(new Date(Date.now() + 3600000), "Talk through my order");
  showToast(`Booked for ${call.at.toLocaleString()}`);
} catch (e) {
  showMessage(e.message);
}

GraineAgent.scheduledCalls

Call it to list the visitor's upcoming calls in your own interface.

scheduledCalls()

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, …

const calls = await GraineAgent.scheduledCalls();

GraineAgent.cancelScheduledCall

Call it when the visitor calls off one of their booked calls.

cancelScheduledCall(id)

Cancels a call booked for this visitor or browser; one booked for anyone else is not_found.

ParameterTypeDefaultMeaning
idstringrequiredThe 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.

await GraineAgent.cancelScheduledCall("6f1c2a9e-7d1b-4c47-9a6e-2f0d8b1c5e44");

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.

FieldTypeMeaning
idstringUse it to cancel the call — Graine's ID for it, a UUID.
atDate | nullWhen the call rings; null only when Graine's time could not be read.
statusstringWhere 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).
sourcestring | nullWho booked it: agent (in a conversation), app (your site or app), dashboard (your team) or api; null when Graine does not say.
reasonstring | nullWhat it is about, as it was booked — at most 120 characters — or null.
isUpcomingbooleanUse it to keep a call in an upcoming list: true while it is scheduled or ringing.
canCancelbooleanUse 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.

GraineAgent.startWorkflow(workflow, data, { idempotencyKey })   // Promise<{ runId, workflowId, alreadyRunning }>

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.

ParameterTypeDefaultMeaning
workflowstringrequiredThe workflow's exact name, or its id (owf_…); at most 120 characters.
dataobjectnoneThe 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.idempotencyKeystringnone8 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.

GraineAgent.startWorkflow("Welcome call", { plan: "gold" }).then(function (run) {
  if (run.alreadyRunning) showNote("You're already on the list.");
});

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.ai in script-src, connect-src and frame-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 missing agentId or key, a refused key or origin, Graine not answering, a sign-out that could not be sent — and identify() given traits without the one the agent identifies visitors by.
  • The version. GraineAgent.version says 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).

FieldTypeMeaning
codestringBranch on it: the reason in one stable word, such as too_soon or network.
messagestringShow it: a sentence fit for the visitor.
statusnumberUse it in logs: the HTTP status Graine answered with, or 0 when nothing was sent or nothing came back.
retryAfterSecondsnumber | nullUse it to wait before trying again: how long Graine asked, with rate_limited; otherwise null.
reasonstring | nullNew 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.
CodeHTTPMeansRaised byFix
invalid_key401The publishable key is not one, or belongs to no agentEvery request to GraineCopy the key again from Agent → Embed & Widgets → Install
origin_refused403The page's host is missing from the agent's Allowed domainsEvery requestAdd the exact host
rate_limited429Too many requests from this browser, key or addressEvery requestWait retryAfterSeconds, then retry
invalid_request400 (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 headlessscheduleCall, cancelScheduledCall, chat.sessionTranscriptFix the call
identity_required400 (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 loadedmemories, forgetMemory, bookings that need a visitor, past sessions (state().chat.pastSessions.error, chat.sessionTranscript)identify() with that trait first — memorySettings.identityField
identity_unverified403New 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 themmemories, forgetMemory, bookings that need a visitor, past sessionsPass 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_limit403This browser is not one of the visitor's allowed devicesmemories, forgetMemory, newConversation, scheduleCall, past sessionsSign out on another device, raise Devices per user, or Reset devices for the visitor
scheduling_off403 (0 on the page)Visitors may not book calls from this agentscheduleCallTurn it on in Calls & scheduling, or hide booking when bookingAvailable is false
too_soon400 (0 on the page)Earlier than earliest(now)scheduleCallOffer times from earliest(now)
too_far400 (0 on the page)Later than latest(now)scheduleCallOffer times up to latest(now)
outside_window400Outside the agent's calling hours, in the visitor's time zonescheduleCallShow the message (it names a time that works); offer another time
too_many_pending409The visitor already has the most calls waitingscheduleCallCancel one first
not_allowed403No such workflow, Your app can start this is off for it, or it isn't publishedstartWorkflowCheck the workflow's exact name or id; an Admin turns on Your app can start this
not_verified403This device isn't one of the visitor's signed-in devices, or the agent requires a verified visitorstartWorkflowSign the visitor in on this device, raise Devices per user, or verify the visitor
not_found404No such booking for this visitor or browser; no such session, or another visitor'scancelScheduledCall, chat.sessionTranscriptRead scheduledCalls(), or the past sessions, again
unavailable502, 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 pageEvery requestRetry with backoff; check the agent is on and the workspace has credit
token_required401Loader 1.5.0. Server tokens are enforced and none came — the loader already asked your tokenProvider again and tried once moreEvery request, load()Give load() a tokenProvider — see Server tokens and the bot check
token_invalid401Loader 1.5.0. The token could not be checked (reason says why); already asked for again and tried once moreEvery request, load()Mint it with POST /v2/client-tokens as it comes
token_expired401Loader 1.5.0. The token expired, and a fresh one did not come in timeEvery request, load()Make sure tokenProvider answers within 15 seconds
token_scope403Loader 1.5.0. Another agent's or visitor's token, or one without the scope this needs (reason). FinalEvery requestMint it for this agent, for the visitor's user_id, with the scopes the page uses
key_revoked401Loader 1.5.0. The publishable key was revoked. FinalEvery request, load()Load the agent with its new key
network0No answer came back: offline, or the connection dropped — or the agent's settings did not arrive within 30 seconds of load()Every requestRetry when online
unknownany 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 wordEvery requestLog 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

LimitValueWhere it applies
Bookings from one install10 an hourscheduleCall, the booking sheet, and the agent's bookings in that install's conversations
Bookings in a workspace1,000 an hourAll in-app bookings
Calls waiting per visitor3 by default (1–10)At most this many upcoming calls per user
Devices per visitor2 by default (1–10)Devices per user; idle devices free their place after 30 days
Notice and horizon5 minutes (2–1440) · 14 days (1–30)With at least this much notice · Booked at most this far ahead
Booking reason · variables120 characters · 12 variables, about 1 KBBookings and conversations
Memories listedAt most 100, newest firstmemories()
Conversation kept50 messages, 7 days after the lastConversations that continue
Requests per key and address, per minuteStarting 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 installAnswered rate_limited with Retry-After
Action handlers · component data6 seconds · 8 secondsAfter 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 a load() option) fetches a fresh one when Graine needs it. verification and onVerificationChange() say whether the visitor is verified, and why not. New error code identity_unverified where an agent requires verified users.
  • A failed load() says why (loader 1.5.0, SDK 0.14.4). When load() 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, or network when Graine did not answer within 30 seconds), not invalid_key until the page reloaded, and the next load() starts afresh. A 502, 504 or 520–524 is unavailable, a code Graine sent is kept trimmed, and a blank one is no code. identity_required names the trait the agent identifies visitors by, and the console says so once when identify() is given traits without it. New GraineAgent.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 }) and GraineAgent.setTokenProvider(): every request carries a short-lived token your server minted for the signed-in visitor, refreshed before it expires; new codes token_required, token_invalid, token_expired, token_scope, key_revoked and bot_check_failed, with reason on 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). When load() 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, or network when Graine did not answer within 30 seconds), not invalid_key until the page reloaded, and the next load() starts afresh. A 502 or 504 is unavailable. identity_required names the trait the agent identifies visitors by, and the console says so once when identify() is given traits without it. New GraineAgent.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.pastSessions lists the identified visitor's earlier sessions with the agent — chats, voice conversations and calls, newest first, as Execution History lists them — filled by GraineAgent.chat.refreshPastSessions() and paged by loadMorePastSessions(); 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 }) (or chat-close-delay-seconds on graine-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 from GraineAgent.state() and the "state", "chat", "voice" and "component" events, and drives them with GraineAgent.chat (send, sendQuickReply, rate, newConversation, shown), GraineAgent.voice (start, stop, setMuted) and GraineAgent.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.sessionId is the chat's current session — the id Execution Logs shows for it — every turn carries the session it was said in, and state().chat.sessions lists 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, sessionId is null and 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, with GraineAgent'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.callingWindow is the agent's calling window ({ start, end, days }, or null), and GraineAgent.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.bookingUnavailableReason says 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, null under a name removes it, null for the whole object clears them all — and GraineAgent.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, or null when 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.

On this page